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.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "CodeGenDAGPatterns.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/TableGen/Error.h"
23 #include "llvm/TableGen/Record.h"
24 #include <algorithm>
25 #include <cstdio>
26 #include <set>
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "dag-patterns"
30 
31 //===----------------------------------------------------------------------===//
32 //  EEVT::TypeSet Implementation
33 //===----------------------------------------------------------------------===//
34 
35 static inline bool isInteger(MVT::SimpleValueType VT) {
36   return MVT(VT).isInteger();
37 }
38 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
39   return MVT(VT).isFloatingPoint();
40 }
41 static inline bool isVector(MVT::SimpleValueType VT) {
42   return MVT(VT).isVector();
43 }
44 static inline bool isScalar(MVT::SimpleValueType VT) {
45   return !MVT(VT).isVector();
46 }
47 
48 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
49   if (VT == MVT::iAny)
50     EnforceInteger(TP);
51   else if (VT == MVT::fAny)
52     EnforceFloatingPoint(TP);
53   else if (VT == MVT::vAny)
54     EnforceVector(TP);
55   else {
56     assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
57             VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
58     TypeVec.push_back(VT);
59   }
60 }
61 
62 
63 EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
64   assert(!VTList.empty() && "empty list?");
65   TypeVec.append(VTList.begin(), VTList.end());
66 
67   if (!VTList.empty())
68     assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
69            VTList[0] != MVT::fAny);
70 
71   // Verify no duplicates.
72   array_pod_sort(TypeVec.begin(), TypeVec.end());
73   assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
74 }
75 
76 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
77 /// on completely unknown type sets.
78 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
79                                           bool (*Pred)(MVT::SimpleValueType),
80                                           const char *PredicateName) {
81   assert(isCompletelyUnknown());
82   ArrayRef<MVT::SimpleValueType> LegalTypes =
83     TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
84 
85   if (TP.hasError())
86     return false;
87 
88   for (MVT::SimpleValueType VT : LegalTypes)
89     if (!Pred || Pred(VT))
90       TypeVec.push_back(VT);
91 
92   // If we have nothing that matches the predicate, bail out.
93   if (TypeVec.empty()) {
94     TP.error("Type inference contradiction found, no " +
95              std::string(PredicateName) + " types found");
96     return false;
97   }
98   // No need to sort with one element.
99   if (TypeVec.size() == 1) return true;
100 
101   // Remove duplicates.
102   array_pod_sort(TypeVec.begin(), TypeVec.end());
103   TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
104 
105   return true;
106 }
107 
108 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
109 /// integer value type.
110 bool EEVT::TypeSet::hasIntegerTypes() const {
111   return any_of(TypeVec, isInteger);
112 }
113 
114 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
115 /// a floating point value type.
116 bool EEVT::TypeSet::hasFloatingPointTypes() const {
117   return any_of(TypeVec, isFloatingPoint);
118 }
119 
120 /// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
121 bool EEVT::TypeSet::hasScalarTypes() const {
122   return any_of(TypeVec, isScalar);
123 }
124 
125 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
126 /// value type.
127 bool EEVT::TypeSet::hasVectorTypes() const {
128   return any_of(TypeVec, isVector);
129 }
130 
131 
132 std::string EEVT::TypeSet::getName() const {
133   if (TypeVec.empty()) return "<empty>";
134 
135   std::string Result;
136 
137   for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
138     std::string VTName = llvm::getEnumName(TypeVec[i]);
139     // Strip off MVT:: prefix if present.
140     if (VTName.substr(0,5) == "MVT::")
141       VTName = VTName.substr(5);
142     if (i) Result += ':';
143     Result += VTName;
144   }
145 
146   if (TypeVec.size() == 1)
147     return Result;
148   return "{" + Result + "}";
149 }
150 
151 /// MergeInTypeInfo - This merges in type information from the specified
152 /// argument.  If 'this' changes, it returns true.  If the two types are
153 /// contradictory (e.g. merge f32 into i32) then this flags an error.
154 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
155   if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
156     return false;
157 
158   if (isCompletelyUnknown()) {
159     *this = InVT;
160     return true;
161   }
162 
163   assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
164 
165   // Handle the abstract cases, seeing if we can resolve them better.
166   switch (TypeVec[0]) {
167   default: break;
168   case MVT::iPTR:
169   case MVT::iPTRAny:
170     if (InVT.hasIntegerTypes()) {
171       EEVT::TypeSet InCopy(InVT);
172       InCopy.EnforceInteger(TP);
173       InCopy.EnforceScalar(TP);
174 
175       if (InCopy.isConcrete()) {
176         // If the RHS has one integer type, upgrade iPTR to i32.
177         TypeVec[0] = InVT.TypeVec[0];
178         return true;
179       }
180 
181       // If the input has multiple scalar integers, this doesn't add any info.
182       if (!InCopy.isCompletelyUnknown())
183         return false;
184     }
185     break;
186   }
187 
188   // If the input constraint is iAny/iPTR and this is an integer type list,
189   // remove non-integer types from the list.
190   if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
191       hasIntegerTypes()) {
192     bool MadeChange = EnforceInteger(TP);
193 
194     // If we're merging in iPTR/iPTRAny and the node currently has a list of
195     // multiple different integer types, replace them with a single iPTR.
196     if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
197         TypeVec.size() != 1) {
198       TypeVec.assign(1, InVT.TypeVec[0]);
199       MadeChange = true;
200     }
201 
202     return MadeChange;
203   }
204 
205   // If this is a type list and the RHS is a typelist as well, eliminate entries
206   // from this list that aren't in the other one.
207   TypeSet InputSet(*this);
208 
209   TypeVec.clear();
210   std::set_intersection(InputSet.TypeVec.begin(), InputSet.TypeVec.end(),
211                         InVT.TypeVec.begin(), InVT.TypeVec.end(),
212                         std::back_inserter(TypeVec));
213 
214   // If the intersection is the same size as the original set then we're done.
215   if (TypeVec.size() == InputSet.TypeVec.size())
216     return false;
217 
218   // If we removed all of our types, we have a type contradiction.
219   if (!TypeVec.empty())
220     return true;
221 
222   // FIXME: Really want an SMLoc here!
223   TP.error("Type inference contradiction found, merging '" +
224            InVT.getName() + "' into '" + InputSet.getName() + "'");
225   return false;
226 }
227 
228 /// EnforceInteger - Remove all non-integer types from this set.
229 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
230   if (TP.hasError())
231     return false;
232   // If we know nothing, then get the full set.
233   if (TypeVec.empty())
234     return FillWithPossibleTypes(TP, isInteger, "integer");
235 
236   if (!hasFloatingPointTypes())
237     return false;
238 
239   TypeSet InputSet(*this);
240 
241   // Filter out all the fp types.
242   TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isInteger))),
243                 TypeVec.end());
244 
245   if (TypeVec.empty()) {
246     TP.error("Type inference contradiction found, '" +
247              InputSet.getName() + "' needs to be integer");
248     return false;
249   }
250   return true;
251 }
252 
253 /// EnforceFloatingPoint - Remove all integer types from this set.
254 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
255   if (TP.hasError())
256     return false;
257   // If we know nothing, then get the full set.
258   if (TypeVec.empty())
259     return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
260 
261   if (!hasIntegerTypes())
262     return false;
263 
264   TypeSet InputSet(*this);
265 
266   // Filter out all the integer types.
267   TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isFloatingPoint))),
268                 TypeVec.end());
269 
270   if (TypeVec.empty()) {
271     TP.error("Type inference contradiction found, '" +
272              InputSet.getName() + "' needs to be floating point");
273     return false;
274   }
275   return true;
276 }
277 
278 /// EnforceScalar - Remove all vector types from this.
279 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
280   if (TP.hasError())
281     return false;
282 
283   // If we know nothing, then get the full set.
284   if (TypeVec.empty())
285     return FillWithPossibleTypes(TP, isScalar, "scalar");
286 
287   if (!hasVectorTypes())
288     return false;
289 
290   TypeSet InputSet(*this);
291 
292   // Filter out all the vector types.
293   TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isScalar))),
294                 TypeVec.end());
295 
296   if (TypeVec.empty()) {
297     TP.error("Type inference contradiction found, '" +
298              InputSet.getName() + "' needs to be scalar");
299     return false;
300   }
301   return true;
302 }
303 
304 /// EnforceVector - Remove all vector types from this.
305 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
306   if (TP.hasError())
307     return false;
308 
309   // If we know nothing, then get the full set.
310   if (TypeVec.empty())
311     return FillWithPossibleTypes(TP, isVector, "vector");
312 
313   TypeSet InputSet(*this);
314   bool MadeChange = false;
315 
316   // Filter out all the scalar types.
317   TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isVector))),
318                 TypeVec.end());
319 
320   if (TypeVec.empty()) {
321     TP.error("Type inference contradiction found, '" +
322              InputSet.getName() + "' needs to be a vector");
323     return false;
324   }
325   return MadeChange;
326 }
327 
328 
329 
330 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
331 /// this should be based on the element type. Update this and other based on
332 /// this information.
333 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
334   if (TP.hasError())
335     return false;
336 
337   // Both operands must be integer or FP, but we don't care which.
338   bool MadeChange = false;
339 
340   if (isCompletelyUnknown())
341     MadeChange = FillWithPossibleTypes(TP);
342 
343   if (Other.isCompletelyUnknown())
344     MadeChange = Other.FillWithPossibleTypes(TP);
345 
346   // If one side is known to be integer or known to be FP but the other side has
347   // no information, get at least the type integrality info in there.
348   if (!hasFloatingPointTypes())
349     MadeChange |= Other.EnforceInteger(TP);
350   else if (!hasIntegerTypes())
351     MadeChange |= Other.EnforceFloatingPoint(TP);
352   if (!Other.hasFloatingPointTypes())
353     MadeChange |= EnforceInteger(TP);
354   else if (!Other.hasIntegerTypes())
355     MadeChange |= EnforceFloatingPoint(TP);
356 
357   assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
358          "Should have a type list now");
359 
360   // If one contains vectors but the other doesn't pull vectors out.
361   if (!hasVectorTypes())
362     MadeChange |= Other.EnforceScalar(TP);
363   else if (!hasScalarTypes())
364     MadeChange |= Other.EnforceVector(TP);
365   if (!Other.hasVectorTypes())
366     MadeChange |= EnforceScalar(TP);
367   else if (!Other.hasScalarTypes())
368     MadeChange |= EnforceVector(TP);
369 
370   // This code does not currently handle nodes which have multiple types,
371   // where some types are integer, and some are fp.  Assert that this is not
372   // the case.
373   assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
374          !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
375          "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
376 
377   if (TP.hasError())
378     return false;
379 
380   // Okay, find the smallest type from current set and remove anything the
381   // same or smaller from the other set. We need to ensure that the scalar
382   // type size is smaller than the scalar size of the smallest type. For
383   // vectors, we also need to make sure that the total size is no larger than
384   // the size of the smallest type.
385   {
386     TypeSet InputSet(Other);
387     MVT Smallest = *std::min_element(TypeVec.begin(), TypeVec.end(),
388       [](MVT A, MVT B) {
389         return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
390                (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
391                 A.getSizeInBits() < B.getSizeInBits());
392       });
393 
394     auto I = remove_if(Other.TypeVec, [Smallest](MVT OtherVT) {
395       // Don't compare vector and non-vector types.
396       if (OtherVT.isVector() != Smallest.isVector())
397         return false;
398       // The getSizeInBits() check here is only needed for vectors, but is
399       // a subset of the scalar check for scalars so no need to qualify.
400       return OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
401              OtherVT.getSizeInBits() < Smallest.getSizeInBits();
402     });
403     MadeChange |= I != Other.TypeVec.end(); // If we're about to remove types.
404     Other.TypeVec.erase(I, Other.TypeVec.end());
405 
406     if (Other.TypeVec.empty()) {
407       TP.error("Type inference contradiction found, '" + InputSet.getName() +
408                "' has nothing larger than '" + getName() +"'!");
409       return false;
410     }
411   }
412 
413   // Okay, find the largest type from the other set and remove anything the
414   // same or smaller from the current set. We need to ensure that the scalar
415   // type size is larger than the scalar size of the largest type. For
416   // vectors, we also need to make sure that the total size is no smaller than
417   // the size of the largest type.
418   {
419     TypeSet InputSet(*this);
420     MVT Largest = *std::max_element(Other.TypeVec.begin(), Other.TypeVec.end(),
421       [](MVT A, MVT B) {
422         return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
423                (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
424                 A.getSizeInBits() < B.getSizeInBits());
425       });
426     auto I = remove_if(TypeVec, [Largest](MVT OtherVT) {
427       // Don't compare vector and non-vector types.
428       if (OtherVT.isVector() != Largest.isVector())
429         return false;
430       return OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
431              OtherVT.getSizeInBits() > Largest.getSizeInBits();
432     });
433     MadeChange |= I != TypeVec.end(); // If we're about to remove types.
434     TypeVec.erase(I, TypeVec.end());
435 
436     if (TypeVec.empty()) {
437       TP.error("Type inference contradiction found, '" + InputSet.getName() +
438                "' has nothing smaller than '" + Other.getName() +"'!");
439       return false;
440     }
441   }
442 
443   return MadeChange;
444 }
445 
446 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
447 /// whose element is specified by VTOperand.
448 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
449                                            TreePattern &TP) {
450   bool MadeChange = false;
451 
452   MadeChange |= EnforceVector(TP);
453 
454   TypeSet InputSet(*this);
455 
456   // Filter out all the types which don't have the right element type.
457   auto I = remove_if(TypeVec, [VT](MVT VVT) {
458     return VVT.getVectorElementType().SimpleTy != VT;
459   });
460   MadeChange |= I != TypeVec.end();
461   TypeVec.erase(I, TypeVec.end());
462 
463   if (TypeVec.empty()) {  // FIXME: Really want an SMLoc here!
464     TP.error("Type inference contradiction found, forcing '" +
465              InputSet.getName() + "' to have a vector element of type " +
466              getEnumName(VT));
467     return false;
468   }
469 
470   return MadeChange;
471 }
472 
473 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
474 /// whose element is specified by VTOperand.
475 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
476                                            TreePattern &TP) {
477   if (TP.hasError())
478     return false;
479 
480   // "This" must be a vector and "VTOperand" must be a scalar.
481   bool MadeChange = false;
482   MadeChange |= EnforceVector(TP);
483   MadeChange |= VTOperand.EnforceScalar(TP);
484 
485   // If we know the vector type, it forces the scalar to agree.
486   if (isConcrete()) {
487     MVT IVT = getConcrete();
488     IVT = IVT.getVectorElementType();
489     return MadeChange || VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
490   }
491 
492   // If the scalar type is known, filter out vector types whose element types
493   // disagree.
494   if (!VTOperand.isConcrete())
495     return MadeChange;
496 
497   MVT::SimpleValueType VT = VTOperand.getConcrete();
498 
499   MadeChange |= EnforceVectorEltTypeIs(VT, TP);
500 
501   return MadeChange;
502 }
503 
504 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
505 /// vector type specified by VTOperand.
506 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
507                                                  TreePattern &TP) {
508   if (TP.hasError())
509     return false;
510 
511   // "This" must be a vector and "VTOperand" must be a vector.
512   bool MadeChange = false;
513   MadeChange |= EnforceVector(TP);
514   MadeChange |= VTOperand.EnforceVector(TP);
515 
516   // If one side is known to be integer or known to be FP but the other side has
517   // no information, get at least the type integrality info in there.
518   if (!hasFloatingPointTypes())
519     MadeChange |= VTOperand.EnforceInteger(TP);
520   else if (!hasIntegerTypes())
521     MadeChange |= VTOperand.EnforceFloatingPoint(TP);
522   if (!VTOperand.hasFloatingPointTypes())
523     MadeChange |= EnforceInteger(TP);
524   else if (!VTOperand.hasIntegerTypes())
525     MadeChange |= EnforceFloatingPoint(TP);
526 
527   assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
528          "Should have a type list now");
529 
530   // If we know the vector type, it forces the scalar types to agree.
531   // Also force one vector to have more elements than the other.
532   if (isConcrete()) {
533     MVT IVT = getConcrete();
534     unsigned NumElems = IVT.getVectorNumElements();
535     IVT = IVT.getVectorElementType();
536 
537     EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
538     MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
539 
540     // Only keep types that have less elements than VTOperand.
541     TypeSet InputSet(VTOperand);
542 
543     auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) {
544       return VVT.getVectorNumElements() >= NumElems;
545     });
546     MadeChange |= I != VTOperand.TypeVec.end();
547     VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
548 
549     if (VTOperand.TypeVec.empty()) {  // FIXME: Really want an SMLoc here!
550       TP.error("Type inference contradiction found, forcing '" +
551                InputSet.getName() + "' to have less vector elements than '" +
552                getName() + "'");
553       return false;
554     }
555   } else if (VTOperand.isConcrete()) {
556     MVT IVT = VTOperand.getConcrete();
557     unsigned NumElems = IVT.getVectorNumElements();
558     IVT = IVT.getVectorElementType();
559 
560     EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
561     MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
562 
563     // Only keep types that have more elements than 'this'.
564     TypeSet InputSet(*this);
565 
566     auto I = remove_if(TypeVec, [NumElems](MVT VVT) {
567       return VVT.getVectorNumElements() <= NumElems;
568     });
569     MadeChange |= I != TypeVec.end();
570     TypeVec.erase(I, TypeVec.end());
571 
572     if (TypeVec.empty()) {  // FIXME: Really want an SMLoc here!
573       TP.error("Type inference contradiction found, forcing '" +
574                InputSet.getName() + "' to have more vector elements than '" +
575                VTOperand.getName() + "'");
576       return false;
577     }
578   }
579 
580   return MadeChange;
581 }
582 
583 /// EnforceVectorSameNumElts - 'this' is now constrained to
584 /// be a vector with same num elements as VTOperand.
585 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
586                                              TreePattern &TP) {
587   if (TP.hasError())
588     return false;
589 
590   // "This" must be a vector and "VTOperand" must be a vector.
591   bool MadeChange = false;
592   MadeChange |= EnforceVector(TP);
593   MadeChange |= VTOperand.EnforceVector(TP);
594 
595   // If we know one of the vector types, it forces the other type to agree.
596   if (isConcrete()) {
597     MVT IVT = getConcrete();
598     unsigned NumElems = IVT.getVectorNumElements();
599 
600     // Only keep types that have same elements as 'this'.
601     TypeSet InputSet(VTOperand);
602 
603     auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) {
604       return VVT.getVectorNumElements() != NumElems;
605     });
606     MadeChange |= I != VTOperand.TypeVec.end();
607     VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
608 
609     if (VTOperand.TypeVec.empty()) {  // FIXME: Really want an SMLoc here!
610       TP.error("Type inference contradiction found, forcing '" +
611                InputSet.getName() + "' to have same number elements as '" +
612                getName() + "'");
613       return false;
614     }
615   } else if (VTOperand.isConcrete()) {
616     MVT IVT = VTOperand.getConcrete();
617     unsigned NumElems = IVT.getVectorNumElements();
618 
619     // Only keep types that have same elements as VTOperand.
620     TypeSet InputSet(*this);
621 
622     auto I = remove_if(TypeVec, [NumElems](MVT VVT) {
623       return VVT.getVectorNumElements() != NumElems;
624     });
625     MadeChange |= I != TypeVec.end();
626     TypeVec.erase(I, TypeVec.end());
627 
628     if (TypeVec.empty()) {  // FIXME: Really want an SMLoc here!
629       TP.error("Type inference contradiction found, forcing '" +
630                InputSet.getName() + "' to have same number elements than '" +
631                VTOperand.getName() + "'");
632       return false;
633     }
634   }
635 
636   return MadeChange;
637 }
638 
639 /// EnforceSameSize - 'this' is now constrained to be same size as VTOperand.
640 bool EEVT::TypeSet::EnforceSameSize(EEVT::TypeSet &VTOperand,
641                                     TreePattern &TP) {
642   if (TP.hasError())
643     return false;
644 
645   bool MadeChange = false;
646 
647   // If we know one of the types, it forces the other type agree.
648   if (isConcrete()) {
649     MVT IVT = getConcrete();
650     unsigned Size = IVT.getSizeInBits();
651 
652     // Only keep types that have the same size as 'this'.
653     TypeSet InputSet(VTOperand);
654 
655     auto I = remove_if(VTOperand.TypeVec,
656                        [&](MVT VT) { return VT.getSizeInBits() != Size; });
657     MadeChange |= I != VTOperand.TypeVec.end();
658     VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
659 
660     if (VTOperand.TypeVec.empty()) {  // FIXME: Really want an SMLoc here!
661       TP.error("Type inference contradiction found, forcing '" +
662                InputSet.getName() + "' to have same size as '" +
663                getName() + "'");
664       return false;
665     }
666   } else if (VTOperand.isConcrete()) {
667     MVT IVT = VTOperand.getConcrete();
668     unsigned Size = IVT.getSizeInBits();
669 
670     // Only keep types that have the same size as VTOperand.
671     TypeSet InputSet(*this);
672 
673     auto I =
674         remove_if(TypeVec, [&](MVT VT) { return VT.getSizeInBits() != Size; });
675     MadeChange |= I != TypeVec.end();
676     TypeVec.erase(I, TypeVec.end());
677 
678     if (TypeVec.empty()) {  // FIXME: Really want an SMLoc here!
679       TP.error("Type inference contradiction found, forcing '" +
680                InputSet.getName() + "' to have same size as '" +
681                VTOperand.getName() + "'");
682       return false;
683     }
684   }
685 
686   return MadeChange;
687 }
688 
689 //===----------------------------------------------------------------------===//
690 // Helpers for working with extended types.
691 
692 /// Dependent variable map for CodeGenDAGPattern variant generation
693 typedef std::map<std::string, int> DepVarMap;
694 
695 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
696   if (N->isLeaf()) {
697     if (isa<DefInit>(N->getLeafValue()))
698       DepMap[N->getName()]++;
699   } else {
700     for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
701       FindDepVarsOf(N->getChild(i), DepMap);
702   }
703 }
704 
705 /// Find dependent variables within child patterns
706 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
707   DepVarMap depcounts;
708   FindDepVarsOf(N, depcounts);
709   for (const std::pair<std::string, int> &Pair : depcounts) {
710     if (Pair.second > 1)
711       DepVars.insert(Pair.first);
712   }
713 }
714 
715 #ifndef NDEBUG
716 /// Dump the dependent variable set:
717 static void DumpDepVars(MultipleUseVarSet &DepVars) {
718   if (DepVars.empty()) {
719     DEBUG(errs() << "<empty set>");
720   } else {
721     DEBUG(errs() << "[ ");
722     for (const std::string &DepVar : DepVars) {
723       DEBUG(errs() << DepVar << " ");
724     }
725     DEBUG(errs() << "]");
726   }
727 }
728 #endif
729 
730 
731 //===----------------------------------------------------------------------===//
732 // TreePredicateFn Implementation
733 //===----------------------------------------------------------------------===//
734 
735 /// TreePredicateFn constructor.  Here 'N' is a subclass of PatFrag.
736 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
737   assert((getPredCode().empty() || getImmCode().empty()) &&
738         ".td file corrupt: can't have a node predicate *and* an imm predicate");
739 }
740 
741 std::string TreePredicateFn::getPredCode() const {
742   return PatFragRec->getRecord()->getValueAsString("PredicateCode");
743 }
744 
745 std::string TreePredicateFn::getImmCode() const {
746   return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
747 }
748 
749 
750 /// isAlwaysTrue - Return true if this is a noop predicate.
751 bool TreePredicateFn::isAlwaysTrue() const {
752   return getPredCode().empty() && getImmCode().empty();
753 }
754 
755 /// Return the name to use in the generated code to reference this, this is
756 /// "Predicate_foo" if from a pattern fragment "foo".
757 std::string TreePredicateFn::getFnName() const {
758   return "Predicate_" + PatFragRec->getRecord()->getName();
759 }
760 
761 /// getCodeToRunOnSDNode - Return the code for the function body that
762 /// evaluates this predicate.  The argument is expected to be in "Node",
763 /// not N.  This handles casting and conversion to a concrete node type as
764 /// appropriate.
765 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
766   // Handle immediate predicates first.
767   std::string ImmCode = getImmCode();
768   if (!ImmCode.empty()) {
769     std::string Result =
770       "    int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
771     return Result + ImmCode;
772   }
773 
774   // Handle arbitrary node predicates.
775   assert(!getPredCode().empty() && "Don't have any predicate code!");
776   std::string ClassName;
777   if (PatFragRec->getOnlyTree()->isLeaf())
778     ClassName = "SDNode";
779   else {
780     Record *Op = PatFragRec->getOnlyTree()->getOperator();
781     ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
782   }
783   std::string Result;
784   if (ClassName == "SDNode")
785     Result = "    SDNode *N = Node;\n";
786   else
787     Result = "    auto *N = cast<" + ClassName + ">(Node);\n";
788 
789   return Result + getPredCode();
790 }
791 
792 //===----------------------------------------------------------------------===//
793 // PatternToMatch implementation
794 //
795 
796 
797 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
798 /// patterns before small ones.  This is used to determine the size of a
799 /// pattern.
800 static unsigned getPatternSize(const TreePatternNode *P,
801                                const CodeGenDAGPatterns &CGP) {
802   unsigned Size = 3;  // The node itself.
803   // If the root node is a ConstantSDNode, increases its size.
804   // e.g. (set R32:$dst, 0).
805   if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
806     Size += 2;
807 
808   const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
809   if (AM) {
810     Size += AM->getComplexity();
811 
812     // We don't want to count any children twice, so return early.
813     return Size;
814   }
815 
816   // If this node has some predicate function that must match, it adds to the
817   // complexity of this node.
818   if (!P->getPredicateFns().empty())
819     ++Size;
820 
821   // Count children in the count if they are also nodes.
822   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
823     TreePatternNode *Child = P->getChild(i);
824     if (!Child->isLeaf() && Child->getNumTypes() &&
825         Child->getType(0) != MVT::Other)
826       Size += getPatternSize(Child, CGP);
827     else if (Child->isLeaf()) {
828       if (isa<IntInit>(Child->getLeafValue()))
829         Size += 5;  // Matches a ConstantSDNode (+3) and a specific value (+2).
830       else if (Child->getComplexPatternInfo(CGP))
831         Size += getPatternSize(Child, CGP);
832       else if (!Child->getPredicateFns().empty())
833         ++Size;
834     }
835   }
836 
837   return Size;
838 }
839 
840 /// Compute the complexity metric for the input pattern.  This roughly
841 /// corresponds to the number of nodes that are covered.
842 int PatternToMatch::
843 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
844   return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
845 }
846 
847 
848 /// getPredicateCheck - Return a single string containing all of this
849 /// pattern's predicates concatenated with "&&" operators.
850 ///
851 std::string PatternToMatch::getPredicateCheck() const {
852   SmallVector<Record *, 4> PredicateRecs;
853   for (Init *I : Predicates->getValues()) {
854     if (DefInit *Pred = dyn_cast<DefInit>(I)) {
855       Record *Def = Pred->getDef();
856       if (!Def->isSubClassOf("Predicate")) {
857 #ifndef NDEBUG
858         Def->dump();
859 #endif
860         llvm_unreachable("Unknown predicate type!");
861       }
862       PredicateRecs.push_back(Def);
863     }
864   }
865   // Sort so that different orders get canonicalized to the same string.
866   std::sort(PredicateRecs.begin(), PredicateRecs.end(), LessRecord());
867 
868   SmallString<128> PredicateCheck;
869   for (Record *Pred : PredicateRecs) {
870     if (!PredicateCheck.empty())
871       PredicateCheck += " && ";
872     PredicateCheck += "(" + Pred->getValueAsString("CondString") + ")";
873   }
874 
875   return PredicateCheck.str();
876 }
877 
878 //===----------------------------------------------------------------------===//
879 // SDTypeConstraint implementation
880 //
881 
882 SDTypeConstraint::SDTypeConstraint(Record *R) {
883   OperandNo = R->getValueAsInt("OperandNum");
884 
885   if (R->isSubClassOf("SDTCisVT")) {
886     ConstraintType = SDTCisVT;
887     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
888     if (x.SDTCisVT_Info.VT == MVT::isVoid)
889       PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
890 
891   } else if (R->isSubClassOf("SDTCisPtrTy")) {
892     ConstraintType = SDTCisPtrTy;
893   } else if (R->isSubClassOf("SDTCisInt")) {
894     ConstraintType = SDTCisInt;
895   } else if (R->isSubClassOf("SDTCisFP")) {
896     ConstraintType = SDTCisFP;
897   } else if (R->isSubClassOf("SDTCisVec")) {
898     ConstraintType = SDTCisVec;
899   } else if (R->isSubClassOf("SDTCisSameAs")) {
900     ConstraintType = SDTCisSameAs;
901     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
902   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
903     ConstraintType = SDTCisVTSmallerThanOp;
904     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
905       R->getValueAsInt("OtherOperandNum");
906   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
907     ConstraintType = SDTCisOpSmallerThanOp;
908     x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
909       R->getValueAsInt("BigOperandNum");
910   } else if (R->isSubClassOf("SDTCisEltOfVec")) {
911     ConstraintType = SDTCisEltOfVec;
912     x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
913   } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
914     ConstraintType = SDTCisSubVecOfVec;
915     x.SDTCisSubVecOfVec_Info.OtherOperandNum =
916       R->getValueAsInt("OtherOpNum");
917   } else if (R->isSubClassOf("SDTCVecEltisVT")) {
918     ConstraintType = SDTCVecEltisVT;
919     x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
920     if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
921       PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
922     if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
923         !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
924       PrintFatalError(R->getLoc(), "Must use integer or floating point type "
925                                    "as SDTCVecEltisVT");
926   } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
927     ConstraintType = SDTCisSameNumEltsAs;
928     x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
929       R->getValueAsInt("OtherOperandNum");
930   } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
931     ConstraintType = SDTCisSameSizeAs;
932     x.SDTCisSameSizeAs_Info.OtherOperandNum =
933       R->getValueAsInt("OtherOperandNum");
934   } else {
935     PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
936   }
937 }
938 
939 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
940 /// N, and the result number in ResNo.
941 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
942                                       const SDNodeInfo &NodeInfo,
943                                       unsigned &ResNo) {
944   unsigned NumResults = NodeInfo.getNumResults();
945   if (OpNo < NumResults) {
946     ResNo = OpNo;
947     return N;
948   }
949 
950   OpNo -= NumResults;
951 
952   if (OpNo >= N->getNumChildren()) {
953     std::string S;
954     raw_string_ostream OS(S);
955     OS << "Invalid operand number in type constraint "
956            << (OpNo+NumResults) << " ";
957     N->print(OS);
958     PrintFatalError(OS.str());
959   }
960 
961   return N->getChild(OpNo);
962 }
963 
964 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
965 /// constraint to the nodes operands.  This returns true if it makes a
966 /// change, false otherwise.  If a type contradiction is found, flag an error.
967 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
968                                            const SDNodeInfo &NodeInfo,
969                                            TreePattern &TP) const {
970   if (TP.hasError())
971     return false;
972 
973   unsigned ResNo = 0; // The result number being referenced.
974   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
975 
976   switch (ConstraintType) {
977   case SDTCisVT:
978     // Operand must be a particular type.
979     return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
980   case SDTCisPtrTy:
981     // Operand must be same as target pointer type.
982     return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
983   case SDTCisInt:
984     // Require it to be one of the legal integer VTs.
985     return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
986   case SDTCisFP:
987     // Require it to be one of the legal fp VTs.
988     return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
989   case SDTCisVec:
990     // Require it to be one of the legal vector VTs.
991     return NodeToApply->getExtType(ResNo).EnforceVector(TP);
992   case SDTCisSameAs: {
993     unsigned OResNo = 0;
994     TreePatternNode *OtherNode =
995       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
996     return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
997            OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
998   }
999   case SDTCisVTSmallerThanOp: {
1000     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
1001     // have an integer type that is smaller than the VT.
1002     if (!NodeToApply->isLeaf() ||
1003         !isa<DefInit>(NodeToApply->getLeafValue()) ||
1004         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
1005                ->isSubClassOf("ValueType")) {
1006       TP.error(N->getOperator()->getName() + " expects a VT operand!");
1007       return false;
1008     }
1009     MVT::SimpleValueType VT =
1010      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
1011 
1012     EEVT::TypeSet TypeListTmp(VT, TP);
1013 
1014     unsigned OResNo = 0;
1015     TreePatternNode *OtherNode =
1016       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1017                     OResNo);
1018 
1019     return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
1020   }
1021   case SDTCisOpSmallerThanOp: {
1022     unsigned BResNo = 0;
1023     TreePatternNode *BigOperand =
1024       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1025                     BResNo);
1026     return NodeToApply->getExtType(ResNo).
1027                   EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
1028   }
1029   case SDTCisEltOfVec: {
1030     unsigned VResNo = 0;
1031     TreePatternNode *VecOperand =
1032       getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1033                     VResNo);
1034 
1035     // Filter vector types out of VecOperand that don't have the right element
1036     // type.
1037     return VecOperand->getExtType(VResNo).
1038       EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
1039   }
1040   case SDTCisSubVecOfVec: {
1041     unsigned VResNo = 0;
1042     TreePatternNode *BigVecOperand =
1043       getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1044                     VResNo);
1045 
1046     // Filter vector types out of BigVecOperand that don't have the
1047     // right subvector type.
1048     return BigVecOperand->getExtType(VResNo).
1049       EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1050   }
1051   case SDTCVecEltisVT: {
1052     return NodeToApply->getExtType(ResNo).
1053       EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1054   }
1055   case SDTCisSameNumEltsAs: {
1056     unsigned OResNo = 0;
1057     TreePatternNode *OtherNode =
1058       getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1059                     N, NodeInfo, OResNo);
1060     return OtherNode->getExtType(OResNo).
1061       EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1062   }
1063   case SDTCisSameSizeAs: {
1064     unsigned OResNo = 0;
1065     TreePatternNode *OtherNode =
1066       getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1067                     N, NodeInfo, OResNo);
1068     return OtherNode->getExtType(OResNo).
1069       EnforceSameSize(NodeToApply->getExtType(ResNo), TP);
1070   }
1071   }
1072   llvm_unreachable("Invalid ConstraintType!");
1073 }
1074 
1075 // Update the node type to match an instruction operand or result as specified
1076 // in the ins or outs lists on the instruction definition. Return true if the
1077 // type was actually changed.
1078 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1079                                              Record *Operand,
1080                                              TreePattern &TP) {
1081   // The 'unknown' operand indicates that types should be inferred from the
1082   // context.
1083   if (Operand->isSubClassOf("unknown_class"))
1084     return false;
1085 
1086   // The Operand class specifies a type directly.
1087   if (Operand->isSubClassOf("Operand"))
1088     return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1089                           TP);
1090 
1091   // PointerLikeRegClass has a type that is determined at runtime.
1092   if (Operand->isSubClassOf("PointerLikeRegClass"))
1093     return UpdateNodeType(ResNo, MVT::iPTR, TP);
1094 
1095   // Both RegisterClass and RegisterOperand operands derive their types from a
1096   // register class def.
1097   Record *RC = nullptr;
1098   if (Operand->isSubClassOf("RegisterClass"))
1099     RC = Operand;
1100   else if (Operand->isSubClassOf("RegisterOperand"))
1101     RC = Operand->getValueAsDef("RegClass");
1102 
1103   assert(RC && "Unknown operand type");
1104   CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1105   return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1106 }
1107 
1108 
1109 //===----------------------------------------------------------------------===//
1110 // SDNodeInfo implementation
1111 //
1112 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1113   EnumName    = R->getValueAsString("Opcode");
1114   SDClassName = R->getValueAsString("SDClass");
1115   Record *TypeProfile = R->getValueAsDef("TypeProfile");
1116   NumResults = TypeProfile->getValueAsInt("NumResults");
1117   NumOperands = TypeProfile->getValueAsInt("NumOperands");
1118 
1119   // Parse the properties.
1120   Properties = 0;
1121   for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1122     if (Property->getName() == "SDNPCommutative") {
1123       Properties |= 1 << SDNPCommutative;
1124     } else if (Property->getName() == "SDNPAssociative") {
1125       Properties |= 1 << SDNPAssociative;
1126     } else if (Property->getName() == "SDNPHasChain") {
1127       Properties |= 1 << SDNPHasChain;
1128     } else if (Property->getName() == "SDNPOutGlue") {
1129       Properties |= 1 << SDNPOutGlue;
1130     } else if (Property->getName() == "SDNPInGlue") {
1131       Properties |= 1 << SDNPInGlue;
1132     } else if (Property->getName() == "SDNPOptInGlue") {
1133       Properties |= 1 << SDNPOptInGlue;
1134     } else if (Property->getName() == "SDNPMayStore") {
1135       Properties |= 1 << SDNPMayStore;
1136     } else if (Property->getName() == "SDNPMayLoad") {
1137       Properties |= 1 << SDNPMayLoad;
1138     } else if (Property->getName() == "SDNPSideEffect") {
1139       Properties |= 1 << SDNPSideEffect;
1140     } else if (Property->getName() == "SDNPMemOperand") {
1141       Properties |= 1 << SDNPMemOperand;
1142     } else if (Property->getName() == "SDNPVariadic") {
1143       Properties |= 1 << SDNPVariadic;
1144     } else {
1145       PrintFatalError("Unknown SD Node property '" +
1146                       Property->getName() + "' on node '" +
1147                       R->getName() + "'!");
1148     }
1149   }
1150 
1151 
1152   // Parse the type constraints.
1153   std::vector<Record*> ConstraintList =
1154     TypeProfile->getValueAsListOfDefs("Constraints");
1155   TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1156 }
1157 
1158 /// getKnownType - If the type constraints on this node imply a fixed type
1159 /// (e.g. all stores return void, etc), then return it as an
1160 /// MVT::SimpleValueType.  Otherwise, return EEVT::Other.
1161 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1162   unsigned NumResults = getNumResults();
1163   assert(NumResults <= 1 &&
1164          "We only work with nodes with zero or one result so far!");
1165   assert(ResNo == 0 && "Only handles single result nodes so far");
1166 
1167   for (const SDTypeConstraint &Constraint : TypeConstraints) {
1168     // Make sure that this applies to the correct node result.
1169     if (Constraint.OperandNo >= NumResults)  // FIXME: need value #
1170       continue;
1171 
1172     switch (Constraint.ConstraintType) {
1173     default: break;
1174     case SDTypeConstraint::SDTCisVT:
1175       return Constraint.x.SDTCisVT_Info.VT;
1176     case SDTypeConstraint::SDTCisPtrTy:
1177       return MVT::iPTR;
1178     }
1179   }
1180   return MVT::Other;
1181 }
1182 
1183 //===----------------------------------------------------------------------===//
1184 // TreePatternNode implementation
1185 //
1186 
1187 TreePatternNode::~TreePatternNode() {
1188 #if 0 // FIXME: implement refcounted tree nodes!
1189   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1190     delete getChild(i);
1191 #endif
1192 }
1193 
1194 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1195   if (Operator->getName() == "set" ||
1196       Operator->getName() == "implicit")
1197     return 0;  // All return nothing.
1198 
1199   if (Operator->isSubClassOf("Intrinsic"))
1200     return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1201 
1202   if (Operator->isSubClassOf("SDNode"))
1203     return CDP.getSDNodeInfo(Operator).getNumResults();
1204 
1205   if (Operator->isSubClassOf("PatFrag")) {
1206     // If we've already parsed this pattern fragment, get it.  Otherwise, handle
1207     // the forward reference case where one pattern fragment references another
1208     // before it is processed.
1209     if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1210       return PFRec->getOnlyTree()->getNumTypes();
1211 
1212     // Get the result tree.
1213     DagInit *Tree = Operator->getValueAsDag("Fragment");
1214     Record *Op = nullptr;
1215     if (Tree)
1216       if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1217         Op = DI->getDef();
1218     assert(Op && "Invalid Fragment");
1219     return GetNumNodeResults(Op, CDP);
1220   }
1221 
1222   if (Operator->isSubClassOf("Instruction")) {
1223     CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1224 
1225     unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1226 
1227     // Subtract any defaulted outputs.
1228     for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1229       Record *OperandNode = InstInfo.Operands[i].Rec;
1230 
1231       if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1232           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1233         --NumDefsToAdd;
1234     }
1235 
1236     // Add on one implicit def if it has a resolvable type.
1237     if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1238       ++NumDefsToAdd;
1239     return NumDefsToAdd;
1240   }
1241 
1242   if (Operator->isSubClassOf("SDNodeXForm"))
1243     return 1;  // FIXME: Generalize SDNodeXForm
1244 
1245   if (Operator->isSubClassOf("ValueType"))
1246     return 1;  // A type-cast of one result.
1247 
1248   if (Operator->isSubClassOf("ComplexPattern"))
1249     return 1;
1250 
1251   Operator->dump();
1252   PrintFatalError("Unhandled node in GetNumNodeResults");
1253 }
1254 
1255 void TreePatternNode::print(raw_ostream &OS) const {
1256   if (isLeaf())
1257     OS << *getLeafValue();
1258   else
1259     OS << '(' << getOperator()->getName();
1260 
1261   for (unsigned i = 0, e = Types.size(); i != e; ++i)
1262     OS << ':' << getExtType(i).getName();
1263 
1264   if (!isLeaf()) {
1265     if (getNumChildren() != 0) {
1266       OS << " ";
1267       getChild(0)->print(OS);
1268       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1269         OS << ", ";
1270         getChild(i)->print(OS);
1271       }
1272     }
1273     OS << ")";
1274   }
1275 
1276   for (const TreePredicateFn &Pred : PredicateFns)
1277     OS << "<<P:" << Pred.getFnName() << ">>";
1278   if (TransformFn)
1279     OS << "<<X:" << TransformFn->getName() << ">>";
1280   if (!getName().empty())
1281     OS << ":$" << getName();
1282 
1283 }
1284 void TreePatternNode::dump() const {
1285   print(errs());
1286 }
1287 
1288 /// isIsomorphicTo - Return true if this node is recursively
1289 /// isomorphic to the specified node.  For this comparison, the node's
1290 /// entire state is considered. The assigned name is ignored, since
1291 /// nodes with differing names are considered isomorphic. However, if
1292 /// the assigned name is present in the dependent variable set, then
1293 /// the assigned name is considered significant and the node is
1294 /// isomorphic if the names match.
1295 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1296                                      const MultipleUseVarSet &DepVars) const {
1297   if (N == this) return true;
1298   if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1299       getPredicateFns() != N->getPredicateFns() ||
1300       getTransformFn() != N->getTransformFn())
1301     return false;
1302 
1303   if (isLeaf()) {
1304     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1305       if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1306         return ((DI->getDef() == NDI->getDef())
1307                 && (DepVars.find(getName()) == DepVars.end()
1308                     || getName() == N->getName()));
1309       }
1310     }
1311     return getLeafValue() == N->getLeafValue();
1312   }
1313 
1314   if (N->getOperator() != getOperator() ||
1315       N->getNumChildren() != getNumChildren()) return false;
1316   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1317     if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1318       return false;
1319   return true;
1320 }
1321 
1322 /// clone - Make a copy of this tree and all of its children.
1323 ///
1324 TreePatternNode *TreePatternNode::clone() const {
1325   TreePatternNode *New;
1326   if (isLeaf()) {
1327     New = new TreePatternNode(getLeafValue(), getNumTypes());
1328   } else {
1329     std::vector<TreePatternNode*> CChildren;
1330     CChildren.reserve(Children.size());
1331     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1332       CChildren.push_back(getChild(i)->clone());
1333     New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1334   }
1335   New->setName(getName());
1336   New->Types = Types;
1337   New->setPredicateFns(getPredicateFns());
1338   New->setTransformFn(getTransformFn());
1339   return New;
1340 }
1341 
1342 /// RemoveAllTypes - Recursively strip all the types of this tree.
1343 void TreePatternNode::RemoveAllTypes() {
1344   // Reset to unknown type.
1345   std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
1346   if (isLeaf()) return;
1347   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1348     getChild(i)->RemoveAllTypes();
1349 }
1350 
1351 
1352 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1353 /// with actual values specified by ArgMap.
1354 void TreePatternNode::
1355 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1356   if (isLeaf()) return;
1357 
1358   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1359     TreePatternNode *Child = getChild(i);
1360     if (Child->isLeaf()) {
1361       Init *Val = Child->getLeafValue();
1362       // Note that, when substituting into an output pattern, Val might be an
1363       // UnsetInit.
1364       if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1365           cast<DefInit>(Val)->getDef()->getName() == "node")) {
1366         // We found a use of a formal argument, replace it with its value.
1367         TreePatternNode *NewChild = ArgMap[Child->getName()];
1368         assert(NewChild && "Couldn't find formal argument!");
1369         assert((Child->getPredicateFns().empty() ||
1370                 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1371                "Non-empty child predicate clobbered!");
1372         setChild(i, NewChild);
1373       }
1374     } else {
1375       getChild(i)->SubstituteFormalArguments(ArgMap);
1376     }
1377   }
1378 }
1379 
1380 
1381 /// InlinePatternFragments - If this pattern refers to any pattern
1382 /// fragments, inline them into place, giving us a pattern without any
1383 /// PatFrag references.
1384 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1385   if (TP.hasError())
1386     return nullptr;
1387 
1388   if (isLeaf())
1389      return this;  // nothing to do.
1390   Record *Op = getOperator();
1391 
1392   if (!Op->isSubClassOf("PatFrag")) {
1393     // Just recursively inline children nodes.
1394     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1395       TreePatternNode *Child = getChild(i);
1396       TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1397 
1398       assert((Child->getPredicateFns().empty() ||
1399               NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1400              "Non-empty child predicate clobbered!");
1401 
1402       setChild(i, NewChild);
1403     }
1404     return this;
1405   }
1406 
1407   // Otherwise, we found a reference to a fragment.  First, look up its
1408   // TreePattern record.
1409   TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1410 
1411   // Verify that we are passing the right number of operands.
1412   if (Frag->getNumArgs() != Children.size()) {
1413     TP.error("'" + Op->getName() + "' fragment requires " +
1414              utostr(Frag->getNumArgs()) + " operands!");
1415     return nullptr;
1416   }
1417 
1418   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1419 
1420   TreePredicateFn PredFn(Frag);
1421   if (!PredFn.isAlwaysTrue())
1422     FragTree->addPredicateFn(PredFn);
1423 
1424   // Resolve formal arguments to their actual value.
1425   if (Frag->getNumArgs()) {
1426     // Compute the map of formal to actual arguments.
1427     std::map<std::string, TreePatternNode*> ArgMap;
1428     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1429       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1430 
1431     FragTree->SubstituteFormalArguments(ArgMap);
1432   }
1433 
1434   FragTree->setName(getName());
1435   for (unsigned i = 0, e = Types.size(); i != e; ++i)
1436     FragTree->UpdateNodeType(i, getExtType(i), TP);
1437 
1438   // Transfer in the old predicates.
1439   for (const TreePredicateFn &Pred : getPredicateFns())
1440     FragTree->addPredicateFn(Pred);
1441 
1442   // Get a new copy of this fragment to stitch into here.
1443   //delete this;    // FIXME: implement refcounting!
1444 
1445   // The fragment we inlined could have recursive inlining that is needed.  See
1446   // if there are any pattern fragments in it and inline them as needed.
1447   return FragTree->InlinePatternFragments(TP);
1448 }
1449 
1450 /// getImplicitType - Check to see if the specified record has an implicit
1451 /// type which should be applied to it.  This will infer the type of register
1452 /// references from the register file information, for example.
1453 ///
1454 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1455 /// the F8RC register class argument in:
1456 ///
1457 ///   (COPY_TO_REGCLASS GPR:$src, F8RC)
1458 ///
1459 /// When Unnamed is false, return the type of a named DAG operand such as the
1460 /// GPR:$src operand above.
1461 ///
1462 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1463                                      bool NotRegisters,
1464                                      bool Unnamed,
1465                                      TreePattern &TP) {
1466   // Check to see if this is a register operand.
1467   if (R->isSubClassOf("RegisterOperand")) {
1468     assert(ResNo == 0 && "Regoperand ref only has one result!");
1469     if (NotRegisters)
1470       return EEVT::TypeSet(); // Unknown.
1471     Record *RegClass = R->getValueAsDef("RegClass");
1472     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1473     return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1474   }
1475 
1476   // Check to see if this is a register or a register class.
1477   if (R->isSubClassOf("RegisterClass")) {
1478     assert(ResNo == 0 && "Regclass ref only has one result!");
1479     // An unnamed register class represents itself as an i32 immediate, for
1480     // example on a COPY_TO_REGCLASS instruction.
1481     if (Unnamed)
1482       return EEVT::TypeSet(MVT::i32, TP);
1483 
1484     // In a named operand, the register class provides the possible set of
1485     // types.
1486     if (NotRegisters)
1487       return EEVT::TypeSet(); // Unknown.
1488     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1489     return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1490   }
1491 
1492   if (R->isSubClassOf("PatFrag")) {
1493     assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1494     // Pattern fragment types will be resolved when they are inlined.
1495     return EEVT::TypeSet(); // Unknown.
1496   }
1497 
1498   if (R->isSubClassOf("Register")) {
1499     assert(ResNo == 0 && "Registers only produce one result!");
1500     if (NotRegisters)
1501       return EEVT::TypeSet(); // Unknown.
1502     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1503     return EEVT::TypeSet(T.getRegisterVTs(R));
1504   }
1505 
1506   if (R->isSubClassOf("SubRegIndex")) {
1507     assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1508     return EEVT::TypeSet(MVT::i32, TP);
1509   }
1510 
1511   if (R->isSubClassOf("ValueType")) {
1512     assert(ResNo == 0 && "This node only has one result!");
1513     // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1514     //
1515     //   (sext_inreg GPR:$src, i16)
1516     //                         ~~~
1517     if (Unnamed)
1518       return EEVT::TypeSet(MVT::Other, TP);
1519     // With a name, the ValueType simply provides the type of the named
1520     // variable.
1521     //
1522     //   (sext_inreg i32:$src, i16)
1523     //               ~~~~~~~~
1524     if (NotRegisters)
1525       return EEVT::TypeSet(); // Unknown.
1526     return EEVT::TypeSet(getValueType(R), TP);
1527   }
1528 
1529   if (R->isSubClassOf("CondCode")) {
1530     assert(ResNo == 0 && "This node only has one result!");
1531     // Using a CondCodeSDNode.
1532     return EEVT::TypeSet(MVT::Other, TP);
1533   }
1534 
1535   if (R->isSubClassOf("ComplexPattern")) {
1536     assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1537     if (NotRegisters)
1538       return EEVT::TypeSet(); // Unknown.
1539    return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1540                          TP);
1541   }
1542   if (R->isSubClassOf("PointerLikeRegClass")) {
1543     assert(ResNo == 0 && "Regclass can only have one result!");
1544     return EEVT::TypeSet(MVT::iPTR, TP);
1545   }
1546 
1547   if (R->getName() == "node" || R->getName() == "srcvalue" ||
1548       R->getName() == "zero_reg") {
1549     // Placeholder.
1550     return EEVT::TypeSet(); // Unknown.
1551   }
1552 
1553   if (R->isSubClassOf("Operand"))
1554     return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1555 
1556   TP.error("Unknown node flavor used in pattern: " + R->getName());
1557   return EEVT::TypeSet(MVT::Other, TP);
1558 }
1559 
1560 
1561 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1562 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1563 const CodeGenIntrinsic *TreePatternNode::
1564 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1565   if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1566       getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1567       getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1568     return nullptr;
1569 
1570   unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1571   return &CDP.getIntrinsicInfo(IID);
1572 }
1573 
1574 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1575 /// return the ComplexPattern information, otherwise return null.
1576 const ComplexPattern *
1577 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1578   Record *Rec;
1579   if (isLeaf()) {
1580     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1581     if (!DI)
1582       return nullptr;
1583     Rec = DI->getDef();
1584   } else
1585     Rec = getOperator();
1586 
1587   if (!Rec->isSubClassOf("ComplexPattern"))
1588     return nullptr;
1589   return &CGP.getComplexPattern(Rec);
1590 }
1591 
1592 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1593   // A ComplexPattern specifically declares how many results it fills in.
1594   if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1595     return CP->getNumOperands();
1596 
1597   // If MIOperandInfo is specified, that gives the count.
1598   if (isLeaf()) {
1599     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1600     if (DI && DI->getDef()->isSubClassOf("Operand")) {
1601       DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1602       if (MIOps->getNumArgs())
1603         return MIOps->getNumArgs();
1604     }
1605   }
1606 
1607   // Otherwise there is just one result.
1608   return 1;
1609 }
1610 
1611 /// NodeHasProperty - Return true if this node has the specified property.
1612 bool TreePatternNode::NodeHasProperty(SDNP Property,
1613                                       const CodeGenDAGPatterns &CGP) const {
1614   if (isLeaf()) {
1615     if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1616       return CP->hasProperty(Property);
1617     return false;
1618   }
1619 
1620   Record *Operator = getOperator();
1621   if (!Operator->isSubClassOf("SDNode")) return false;
1622 
1623   return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1624 }
1625 
1626 
1627 
1628 
1629 /// TreeHasProperty - Return true if any node in this tree has the specified
1630 /// property.
1631 bool TreePatternNode::TreeHasProperty(SDNP Property,
1632                                       const CodeGenDAGPatterns &CGP) const {
1633   if (NodeHasProperty(Property, CGP))
1634     return true;
1635   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1636     if (getChild(i)->TreeHasProperty(Property, CGP))
1637       return true;
1638   return false;
1639 }
1640 
1641 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1642 /// commutative intrinsic.
1643 bool
1644 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1645   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1646     return Int->isCommutative;
1647   return false;
1648 }
1649 
1650 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1651   if (!N->isLeaf())
1652     return N->getOperator()->isSubClassOf(Class);
1653 
1654   DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1655   if (DI && DI->getDef()->isSubClassOf(Class))
1656     return true;
1657 
1658   return false;
1659 }
1660 
1661 static void emitTooManyOperandsError(TreePattern &TP,
1662                                      StringRef InstName,
1663                                      unsigned Expected,
1664                                      unsigned Actual) {
1665   TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1666            " operands but expected only " + Twine(Expected) + "!");
1667 }
1668 
1669 static void emitTooFewOperandsError(TreePattern &TP,
1670                                     StringRef InstName,
1671                                     unsigned Actual) {
1672   TP.error("Instruction '" + InstName +
1673            "' expects more than the provided " + Twine(Actual) + " operands!");
1674 }
1675 
1676 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1677 /// this node and its children in the tree.  This returns true if it makes a
1678 /// change, false otherwise.  If a type contradiction is found, flag an error.
1679 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1680   if (TP.hasError())
1681     return false;
1682 
1683   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1684   if (isLeaf()) {
1685     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1686       // If it's a regclass or something else known, include the type.
1687       bool MadeChange = false;
1688       for (unsigned i = 0, e = Types.size(); i != e; ++i)
1689         MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1690                                                         NotRegisters,
1691                                                         !hasName(), TP), TP);
1692       return MadeChange;
1693     }
1694 
1695     if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1696       assert(Types.size() == 1 && "Invalid IntInit");
1697 
1698       // Int inits are always integers. :)
1699       bool MadeChange = Types[0].EnforceInteger(TP);
1700 
1701       if (!Types[0].isConcrete())
1702         return MadeChange;
1703 
1704       MVT::SimpleValueType VT = getType(0);
1705       if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1706         return MadeChange;
1707 
1708       unsigned Size = MVT(VT).getSizeInBits();
1709       // Make sure that the value is representable for this type.
1710       if (Size >= 32) return MadeChange;
1711 
1712       // Check that the value doesn't use more bits than we have. It must either
1713       // be a sign- or zero-extended equivalent of the original.
1714       int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1715       if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1716         return MadeChange;
1717 
1718       TP.error("Integer value '" + itostr(II->getValue()) +
1719                "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1720       return false;
1721     }
1722     return false;
1723   }
1724 
1725   // special handling for set, which isn't really an SDNode.
1726   if (getOperator()->getName() == "set") {
1727     assert(getNumTypes() == 0 && "Set doesn't produce a value");
1728     assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1729     unsigned NC = getNumChildren();
1730 
1731     TreePatternNode *SetVal = getChild(NC-1);
1732     bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1733 
1734     for (unsigned i = 0; i < NC-1; ++i) {
1735       TreePatternNode *Child = getChild(i);
1736       MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1737 
1738       // Types of operands must match.
1739       MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1740       MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1741     }
1742     return MadeChange;
1743   }
1744 
1745   if (getOperator()->getName() == "implicit") {
1746     assert(getNumTypes() == 0 && "Node doesn't produce a value");
1747 
1748     bool MadeChange = false;
1749     for (unsigned i = 0; i < getNumChildren(); ++i)
1750       MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1751     return MadeChange;
1752   }
1753 
1754   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1755     bool MadeChange = false;
1756 
1757     // Apply the result type to the node.
1758     unsigned NumRetVTs = Int->IS.RetVTs.size();
1759     unsigned NumParamVTs = Int->IS.ParamVTs.size();
1760 
1761     for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1762       MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1763 
1764     if (getNumChildren() != NumParamVTs + 1) {
1765       TP.error("Intrinsic '" + Int->Name + "' expects " +
1766                utostr(NumParamVTs) + " operands, not " +
1767                utostr(getNumChildren() - 1) + " operands!");
1768       return false;
1769     }
1770 
1771     // Apply type info to the intrinsic ID.
1772     MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1773 
1774     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1775       MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1776 
1777       MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1778       assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1779       MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1780     }
1781     return MadeChange;
1782   }
1783 
1784   if (getOperator()->isSubClassOf("SDNode")) {
1785     const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1786 
1787     // Check that the number of operands is sane.  Negative operands -> varargs.
1788     if (NI.getNumOperands() >= 0 &&
1789         getNumChildren() != (unsigned)NI.getNumOperands()) {
1790       TP.error(getOperator()->getName() + " node requires exactly " +
1791                itostr(NI.getNumOperands()) + " operands!");
1792       return false;
1793     }
1794 
1795     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1796     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1797       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1798     return MadeChange;
1799   }
1800 
1801   if (getOperator()->isSubClassOf("Instruction")) {
1802     const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1803     CodeGenInstruction &InstInfo =
1804       CDP.getTargetInfo().getInstruction(getOperator());
1805 
1806     bool MadeChange = false;
1807 
1808     // Apply the result types to the node, these come from the things in the
1809     // (outs) list of the instruction.
1810     unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1811                                         Inst.getNumResults());
1812     for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1813       MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1814 
1815     // If the instruction has implicit defs, we apply the first one as a result.
1816     // FIXME: This sucks, it should apply all implicit defs.
1817     if (!InstInfo.ImplicitDefs.empty()) {
1818       unsigned ResNo = NumResultsToAdd;
1819 
1820       // FIXME: Generalize to multiple possible types and multiple possible
1821       // ImplicitDefs.
1822       MVT::SimpleValueType VT =
1823         InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1824 
1825       if (VT != MVT::Other)
1826         MadeChange |= UpdateNodeType(ResNo, VT, TP);
1827     }
1828 
1829     // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1830     // be the same.
1831     if (getOperator()->getName() == "INSERT_SUBREG") {
1832       assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1833       MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1834       MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1835     } else if (getOperator()->getName() == "REG_SEQUENCE") {
1836       // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1837       // variadic.
1838 
1839       unsigned NChild = getNumChildren();
1840       if (NChild < 3) {
1841         TP.error("REG_SEQUENCE requires at least 3 operands!");
1842         return false;
1843       }
1844 
1845       if (NChild % 2 == 0) {
1846         TP.error("REG_SEQUENCE requires an odd number of operands!");
1847         return false;
1848       }
1849 
1850       if (!isOperandClass(getChild(0), "RegisterClass")) {
1851         TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1852         return false;
1853       }
1854 
1855       for (unsigned I = 1; I < NChild; I += 2) {
1856         TreePatternNode *SubIdxChild = getChild(I + 1);
1857         if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1858           TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1859                    itostr(I + 1) + "!");
1860           return false;
1861         }
1862       }
1863     }
1864 
1865     unsigned ChildNo = 0;
1866     for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1867       Record *OperandNode = Inst.getOperand(i);
1868 
1869       // If the instruction expects a predicate or optional def operand, we
1870       // codegen this by setting the operand to it's default value if it has a
1871       // non-empty DefaultOps field.
1872       if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1873           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1874         continue;
1875 
1876       // Verify that we didn't run out of provided operands.
1877       if (ChildNo >= getNumChildren()) {
1878         emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1879         return false;
1880       }
1881 
1882       TreePatternNode *Child = getChild(ChildNo++);
1883       unsigned ChildResNo = 0;  // Instructions always use res #0 of their op.
1884 
1885       // If the operand has sub-operands, they may be provided by distinct
1886       // child patterns, so attempt to match each sub-operand separately.
1887       if (OperandNode->isSubClassOf("Operand")) {
1888         DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1889         if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1890           // But don't do that if the whole operand is being provided by
1891           // a single ComplexPattern-related Operand.
1892 
1893           if (Child->getNumMIResults(CDP) < NumArgs) {
1894             // Match first sub-operand against the child we already have.
1895             Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1896             MadeChange |=
1897               Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1898 
1899             // And the remaining sub-operands against subsequent children.
1900             for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1901               if (ChildNo >= getNumChildren()) {
1902                 emitTooFewOperandsError(TP, getOperator()->getName(),
1903                                         getNumChildren());
1904                 return false;
1905               }
1906               Child = getChild(ChildNo++);
1907 
1908               SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1909               MadeChange |=
1910                 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1911             }
1912             continue;
1913           }
1914         }
1915       }
1916 
1917       // If we didn't match by pieces above, attempt to match the whole
1918       // operand now.
1919       MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1920     }
1921 
1922     if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1923       emitTooManyOperandsError(TP, getOperator()->getName(),
1924                                ChildNo, getNumChildren());
1925       return false;
1926     }
1927 
1928     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1929       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1930     return MadeChange;
1931   }
1932 
1933   if (getOperator()->isSubClassOf("ComplexPattern")) {
1934     bool MadeChange = false;
1935 
1936     for (unsigned i = 0; i < getNumChildren(); ++i)
1937       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1938 
1939     return MadeChange;
1940   }
1941 
1942   assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1943 
1944   // Node transforms always take one operand.
1945   if (getNumChildren() != 1) {
1946     TP.error("Node transform '" + getOperator()->getName() +
1947              "' requires one operand!");
1948     return false;
1949   }
1950 
1951   bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1952 
1953 
1954   // If either the output or input of the xform does not have exact
1955   // type info. We assume they must be the same. Otherwise, it is perfectly
1956   // legal to transform from one type to a completely different type.
1957 #if 0
1958   if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1959     bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1960     MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1961     return MadeChange;
1962   }
1963 #endif
1964   return MadeChange;
1965 }
1966 
1967 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1968 /// RHS of a commutative operation, not the on LHS.
1969 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1970   if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1971     return true;
1972   if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1973     return true;
1974   return false;
1975 }
1976 
1977 
1978 /// canPatternMatch - If it is impossible for this pattern to match on this
1979 /// target, fill in Reason and return false.  Otherwise, return true.  This is
1980 /// used as a sanity check for .td files (to prevent people from writing stuff
1981 /// that can never possibly work), and to prevent the pattern permuter from
1982 /// generating stuff that is useless.
1983 bool TreePatternNode::canPatternMatch(std::string &Reason,
1984                                       const CodeGenDAGPatterns &CDP) {
1985   if (isLeaf()) return true;
1986 
1987   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1988     if (!getChild(i)->canPatternMatch(Reason, CDP))
1989       return false;
1990 
1991   // If this is an intrinsic, handle cases that would make it not match.  For
1992   // example, if an operand is required to be an immediate.
1993   if (getOperator()->isSubClassOf("Intrinsic")) {
1994     // TODO:
1995     return true;
1996   }
1997 
1998   if (getOperator()->isSubClassOf("ComplexPattern"))
1999     return true;
2000 
2001   // If this node is a commutative operator, check that the LHS isn't an
2002   // immediate.
2003   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2004   bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2005   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2006     // Scan all of the operands of the node and make sure that only the last one
2007     // is a constant node, unless the RHS also is.
2008     if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2009       bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2010       for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
2011         if (OnlyOnRHSOfCommutative(getChild(i))) {
2012           Reason="Immediate value must be on the RHS of commutative operators!";
2013           return false;
2014         }
2015     }
2016   }
2017 
2018   return true;
2019 }
2020 
2021 //===----------------------------------------------------------------------===//
2022 // TreePattern implementation
2023 //
2024 
2025 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2026                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2027                          isInputPattern(isInput), HasError(false) {
2028   for (Init *I : RawPat->getValues())
2029     Trees.push_back(ParseTreePattern(I, ""));
2030 }
2031 
2032 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2033                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2034                          isInputPattern(isInput), HasError(false) {
2035   Trees.push_back(ParseTreePattern(Pat, ""));
2036 }
2037 
2038 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
2039                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2040                          isInputPattern(isInput), HasError(false) {
2041   Trees.push_back(Pat);
2042 }
2043 
2044 void TreePattern::error(const Twine &Msg) {
2045   if (HasError)
2046     return;
2047   dump();
2048   PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2049   HasError = true;
2050 }
2051 
2052 void TreePattern::ComputeNamedNodes() {
2053   for (TreePatternNode *Tree : Trees)
2054     ComputeNamedNodes(Tree);
2055 }
2056 
2057 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2058   if (!N->getName().empty())
2059     NamedNodes[N->getName()].push_back(N);
2060 
2061   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2062     ComputeNamedNodes(N->getChild(i));
2063 }
2064 
2065 
2066 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2067   if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2068     Record *R = DI->getDef();
2069 
2070     // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
2071     // TreePatternNode of its own.  For example:
2072     ///   (foo GPR, imm) -> (foo GPR, (imm))
2073     if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2074       return ParseTreePattern(
2075         DagInit::get(DI, "",
2076                      std::vector<std::pair<Init*, std::string> >()),
2077         OpName);
2078 
2079     // Input argument?
2080     TreePatternNode *Res = new TreePatternNode(DI, 1);
2081     if (R->getName() == "node" && !OpName.empty()) {
2082       if (OpName.empty())
2083         error("'node' argument requires a name to match with operand list");
2084       Args.push_back(OpName);
2085     }
2086 
2087     Res->setName(OpName);
2088     return Res;
2089   }
2090 
2091   // ?:$name or just $name.
2092   if (isa<UnsetInit>(TheInit)) {
2093     if (OpName.empty())
2094       error("'?' argument requires a name to match with operand list");
2095     TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2096     Args.push_back(OpName);
2097     Res->setName(OpName);
2098     return Res;
2099   }
2100 
2101   if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2102     if (!OpName.empty())
2103       error("Constant int argument should not have a name!");
2104     return new TreePatternNode(II, 1);
2105   }
2106 
2107   if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2108     // Turn this into an IntInit.
2109     Init *II = BI->convertInitializerTo(IntRecTy::get());
2110     if (!II || !isa<IntInit>(II))
2111       error("Bits value must be constants!");
2112     return ParseTreePattern(II, OpName);
2113   }
2114 
2115   DagInit *Dag = dyn_cast<DagInit>(TheInit);
2116   if (!Dag) {
2117     TheInit->dump();
2118     error("Pattern has unexpected init kind!");
2119   }
2120   DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2121   if (!OpDef) error("Pattern has unexpected operator type!");
2122   Record *Operator = OpDef->getDef();
2123 
2124   if (Operator->isSubClassOf("ValueType")) {
2125     // If the operator is a ValueType, then this must be "type cast" of a leaf
2126     // node.
2127     if (Dag->getNumArgs() != 1)
2128       error("Type cast only takes one operand!");
2129 
2130     TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2131 
2132     // Apply the type cast.
2133     assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2134     New->UpdateNodeType(0, getValueType(Operator), *this);
2135 
2136     if (!OpName.empty())
2137       error("ValueType cast should not have a name!");
2138     return New;
2139   }
2140 
2141   // Verify that this is something that makes sense for an operator.
2142   if (!Operator->isSubClassOf("PatFrag") &&
2143       !Operator->isSubClassOf("SDNode") &&
2144       !Operator->isSubClassOf("Instruction") &&
2145       !Operator->isSubClassOf("SDNodeXForm") &&
2146       !Operator->isSubClassOf("Intrinsic") &&
2147       !Operator->isSubClassOf("ComplexPattern") &&
2148       Operator->getName() != "set" &&
2149       Operator->getName() != "implicit")
2150     error("Unrecognized node '" + Operator->getName() + "'!");
2151 
2152   //  Check to see if this is something that is illegal in an input pattern.
2153   if (isInputPattern) {
2154     if (Operator->isSubClassOf("Instruction") ||
2155         Operator->isSubClassOf("SDNodeXForm"))
2156       error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2157   } else {
2158     if (Operator->isSubClassOf("Intrinsic"))
2159       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2160 
2161     if (Operator->isSubClassOf("SDNode") &&
2162         Operator->getName() != "imm" &&
2163         Operator->getName() != "fpimm" &&
2164         Operator->getName() != "tglobaltlsaddr" &&
2165         Operator->getName() != "tconstpool" &&
2166         Operator->getName() != "tjumptable" &&
2167         Operator->getName() != "tframeindex" &&
2168         Operator->getName() != "texternalsym" &&
2169         Operator->getName() != "tblockaddress" &&
2170         Operator->getName() != "tglobaladdr" &&
2171         Operator->getName() != "bb" &&
2172         Operator->getName() != "vt" &&
2173         Operator->getName() != "mcsym")
2174       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2175   }
2176 
2177   std::vector<TreePatternNode*> Children;
2178 
2179   // Parse all the operands.
2180   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2181     Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2182 
2183   // If the operator is an intrinsic, then this is just syntactic sugar for for
2184   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and
2185   // convert the intrinsic name to a number.
2186   if (Operator->isSubClassOf("Intrinsic")) {
2187     const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2188     unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2189 
2190     // If this intrinsic returns void, it must have side-effects and thus a
2191     // chain.
2192     if (Int.IS.RetVTs.empty())
2193       Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2194     else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2195       // Has side-effects, requires chain.
2196       Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2197     else // Otherwise, no chain.
2198       Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2199 
2200     TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2201     Children.insert(Children.begin(), IIDNode);
2202   }
2203 
2204   if (Operator->isSubClassOf("ComplexPattern")) {
2205     for (unsigned i = 0; i < Children.size(); ++i) {
2206       TreePatternNode *Child = Children[i];
2207 
2208       if (Child->getName().empty())
2209         error("All arguments to a ComplexPattern must be named");
2210 
2211       // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2212       // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2213       // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2214       auto OperandId = std::make_pair(Operator, i);
2215       auto PrevOp = ComplexPatternOperands.find(Child->getName());
2216       if (PrevOp != ComplexPatternOperands.end()) {
2217         if (PrevOp->getValue() != OperandId)
2218           error("All ComplexPattern operands must appear consistently: "
2219                 "in the same order in just one ComplexPattern instance.");
2220       } else
2221         ComplexPatternOperands[Child->getName()] = OperandId;
2222     }
2223   }
2224 
2225   unsigned NumResults = GetNumNodeResults(Operator, CDP);
2226   TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2227   Result->setName(OpName);
2228 
2229   if (!Dag->getName().empty()) {
2230     assert(Result->getName().empty());
2231     Result->setName(Dag->getName());
2232   }
2233   return Result;
2234 }
2235 
2236 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2237 /// will never match in favor of something obvious that will.  This is here
2238 /// strictly as a convenience to target authors because it allows them to write
2239 /// more type generic things and have useless type casts fold away.
2240 ///
2241 /// This returns true if any change is made.
2242 static bool SimplifyTree(TreePatternNode *&N) {
2243   if (N->isLeaf())
2244     return false;
2245 
2246   // If we have a bitconvert with a resolved type and if the source and
2247   // destination types are the same, then the bitconvert is useless, remove it.
2248   if (N->getOperator()->getName() == "bitconvert" &&
2249       N->getExtType(0).isConcrete() &&
2250       N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2251       N->getName().empty()) {
2252     N = N->getChild(0);
2253     SimplifyTree(N);
2254     return true;
2255   }
2256 
2257   // Walk all children.
2258   bool MadeChange = false;
2259   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2260     TreePatternNode *Child = N->getChild(i);
2261     MadeChange |= SimplifyTree(Child);
2262     N->setChild(i, Child);
2263   }
2264   return MadeChange;
2265 }
2266 
2267 
2268 
2269 /// InferAllTypes - Infer/propagate as many types throughout the expression
2270 /// patterns as possible.  Return true if all types are inferred, false
2271 /// otherwise.  Flags an error if a type contradiction is found.
2272 bool TreePattern::
2273 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2274   if (NamedNodes.empty())
2275     ComputeNamedNodes();
2276 
2277   bool MadeChange = true;
2278   while (MadeChange) {
2279     MadeChange = false;
2280     for (TreePatternNode *Tree : Trees) {
2281       MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2282       MadeChange |= SimplifyTree(Tree);
2283     }
2284 
2285     // If there are constraints on our named nodes, apply them.
2286     for (auto &Entry : NamedNodes) {
2287       SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2288 
2289       // If we have input named node types, propagate their types to the named
2290       // values here.
2291       if (InNamedTypes) {
2292         if (!InNamedTypes->count(Entry.getKey())) {
2293           error("Node '" + std::string(Entry.getKey()) +
2294                 "' in output pattern but not input pattern");
2295           return true;
2296         }
2297 
2298         const SmallVectorImpl<TreePatternNode*> &InNodes =
2299           InNamedTypes->find(Entry.getKey())->second;
2300 
2301         // The input types should be fully resolved by now.
2302         for (TreePatternNode *Node : Nodes) {
2303           // If this node is a register class, and it is the root of the pattern
2304           // then we're mapping something onto an input register.  We allow
2305           // changing the type of the input register in this case.  This allows
2306           // us to match things like:
2307           //  def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2308           if (Node == Trees[0] && Node->isLeaf()) {
2309             DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2310             if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2311                        DI->getDef()->isSubClassOf("RegisterOperand")))
2312               continue;
2313           }
2314 
2315           assert(Node->getNumTypes() == 1 &&
2316                  InNodes[0]->getNumTypes() == 1 &&
2317                  "FIXME: cannot name multiple result nodes yet");
2318           MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2319                                              *this);
2320         }
2321       }
2322 
2323       // If there are multiple nodes with the same name, they must all have the
2324       // same type.
2325       if (Entry.second.size() > 1) {
2326         for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2327           TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2328           assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2329                  "FIXME: cannot name multiple result nodes yet");
2330 
2331           MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2332           MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2333         }
2334       }
2335     }
2336   }
2337 
2338   bool HasUnresolvedTypes = false;
2339   for (const TreePatternNode *Tree : Trees)
2340     HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
2341   return !HasUnresolvedTypes;
2342 }
2343 
2344 void TreePattern::print(raw_ostream &OS) const {
2345   OS << getRecord()->getName();
2346   if (!Args.empty()) {
2347     OS << "(" << Args[0];
2348     for (unsigned i = 1, e = Args.size(); i != e; ++i)
2349       OS << ", " << Args[i];
2350     OS << ")";
2351   }
2352   OS << ": ";
2353 
2354   if (Trees.size() > 1)
2355     OS << "[\n";
2356   for (const TreePatternNode *Tree : Trees) {
2357     OS << "\t";
2358     Tree->print(OS);
2359     OS << "\n";
2360   }
2361 
2362   if (Trees.size() > 1)
2363     OS << "]\n";
2364 }
2365 
2366 void TreePattern::dump() const { print(errs()); }
2367 
2368 //===----------------------------------------------------------------------===//
2369 // CodeGenDAGPatterns implementation
2370 //
2371 
2372 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2373   Records(R), Target(R) {
2374 
2375   Intrinsics = CodeGenIntrinsicTable(Records, false);
2376   TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
2377   ParseNodeInfo();
2378   ParseNodeTransforms();
2379   ParseComplexPatterns();
2380   ParsePatternFragments();
2381   ParseDefaultOperands();
2382   ParseInstructions();
2383   ParsePatternFragments(/*OutFrags*/true);
2384   ParsePatterns();
2385 
2386   // Generate variants.  For example, commutative patterns can match
2387   // multiple ways.  Add them to PatternsToMatch as well.
2388   GenerateVariants();
2389 
2390   // Infer instruction flags.  For example, we can detect loads,
2391   // stores, and side effects in many cases by examining an
2392   // instruction's pattern.
2393   InferInstructionFlags();
2394 
2395   // Verify that instruction flags match the patterns.
2396   VerifyInstructionFlags();
2397 }
2398 
2399 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2400   Record *N = Records.getDef(Name);
2401   if (!N || !N->isSubClassOf("SDNode"))
2402     PrintFatalError("Error getting SDNode '" + Name + "'!");
2403 
2404   return N;
2405 }
2406 
2407 // Parse all of the SDNode definitions for the target, populating SDNodes.
2408 void CodeGenDAGPatterns::ParseNodeInfo() {
2409   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2410   while (!Nodes.empty()) {
2411     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2412     Nodes.pop_back();
2413   }
2414 
2415   // Get the builtin intrinsic nodes.
2416   intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
2417   intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
2418   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2419 }
2420 
2421 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2422 /// map, and emit them to the file as functions.
2423 void CodeGenDAGPatterns::ParseNodeTransforms() {
2424   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2425   while (!Xforms.empty()) {
2426     Record *XFormNode = Xforms.back();
2427     Record *SDNode = XFormNode->getValueAsDef("Opcode");
2428     std::string Code = XFormNode->getValueAsString("XFormFunction");
2429     SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2430 
2431     Xforms.pop_back();
2432   }
2433 }
2434 
2435 void CodeGenDAGPatterns::ParseComplexPatterns() {
2436   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2437   while (!AMs.empty()) {
2438     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2439     AMs.pop_back();
2440   }
2441 }
2442 
2443 
2444 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2445 /// file, building up the PatternFragments map.  After we've collected them all,
2446 /// inline fragments together as necessary, so that there are no references left
2447 /// inside a pattern fragment to a pattern fragment.
2448 ///
2449 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2450   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2451 
2452   // First step, parse all of the fragments.
2453   for (Record *Frag : Fragments) {
2454     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2455       continue;
2456 
2457     DagInit *Tree = Frag->getValueAsDag("Fragment");
2458     TreePattern *P =
2459         (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2460              Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2461              *this)).get();
2462 
2463     // Validate the argument list, converting it to set, to discard duplicates.
2464     std::vector<std::string> &Args = P->getArgList();
2465     std::set<std::string> OperandsSet(Args.begin(), Args.end());
2466 
2467     if (OperandsSet.count(""))
2468       P->error("Cannot have unnamed 'node' values in pattern fragment!");
2469 
2470     // Parse the operands list.
2471     DagInit *OpsList = Frag->getValueAsDag("Operands");
2472     DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2473     // Special cases: ops == outs == ins. Different names are used to
2474     // improve readability.
2475     if (!OpsOp ||
2476         (OpsOp->getDef()->getName() != "ops" &&
2477          OpsOp->getDef()->getName() != "outs" &&
2478          OpsOp->getDef()->getName() != "ins"))
2479       P->error("Operands list should start with '(ops ... '!");
2480 
2481     // Copy over the arguments.
2482     Args.clear();
2483     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2484       if (!isa<DefInit>(OpsList->getArg(j)) ||
2485           cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2486         P->error("Operands list should all be 'node' values.");
2487       if (OpsList->getArgName(j).empty())
2488         P->error("Operands list should have names for each operand!");
2489       if (!OperandsSet.count(OpsList->getArgName(j)))
2490         P->error("'" + OpsList->getArgName(j) +
2491                  "' does not occur in pattern or was multiply specified!");
2492       OperandsSet.erase(OpsList->getArgName(j));
2493       Args.push_back(OpsList->getArgName(j));
2494     }
2495 
2496     if (!OperandsSet.empty())
2497       P->error("Operands list does not contain an entry for operand '" +
2498                *OperandsSet.begin() + "'!");
2499 
2500     // If there is a code init for this fragment, keep track of the fact that
2501     // this fragment uses it.
2502     TreePredicateFn PredFn(P);
2503     if (!PredFn.isAlwaysTrue())
2504       P->getOnlyTree()->addPredicateFn(PredFn);
2505 
2506     // If there is a node transformation corresponding to this, keep track of
2507     // it.
2508     Record *Transform = Frag->getValueAsDef("OperandTransform");
2509     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
2510       P->getOnlyTree()->setTransformFn(Transform);
2511   }
2512 
2513   // Now that we've parsed all of the tree fragments, do a closure on them so
2514   // that there are not references to PatFrags left inside of them.
2515   for (Record *Frag : Fragments) {
2516     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2517       continue;
2518 
2519     TreePattern &ThePat = *PatternFragments[Frag];
2520     ThePat.InlinePatternFragments();
2521 
2522     // Infer as many types as possible.  Don't worry about it if we don't infer
2523     // all of them, some may depend on the inputs of the pattern.
2524     ThePat.InferAllTypes();
2525     ThePat.resetError();
2526 
2527     // If debugging, print out the pattern fragment result.
2528     DEBUG(ThePat.dump());
2529   }
2530 }
2531 
2532 void CodeGenDAGPatterns::ParseDefaultOperands() {
2533   std::vector<Record*> DefaultOps;
2534   DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2535 
2536   // Find some SDNode.
2537   assert(!SDNodes.empty() && "No SDNodes parsed?");
2538   Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2539 
2540   for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2541     DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2542 
2543     // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2544     // SomeSDnode so that we can parse this.
2545     std::vector<std::pair<Init*, std::string> > Ops;
2546     for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2547       Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2548                                    DefaultInfo->getArgName(op)));
2549     DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2550 
2551     // Create a TreePattern to parse this.
2552     TreePattern P(DefaultOps[i], DI, false, *this);
2553     assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2554 
2555     // Copy the operands over into a DAGDefaultOperand.
2556     DAGDefaultOperand DefaultOpInfo;
2557 
2558     TreePatternNode *T = P.getTree(0);
2559     for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2560       TreePatternNode *TPN = T->getChild(op);
2561       while (TPN->ApplyTypeConstraints(P, false))
2562         /* Resolve all types */;
2563 
2564       if (TPN->ContainsUnresolvedType()) {
2565         PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2566                         DefaultOps[i]->getName() +
2567                         "' doesn't have a concrete type!");
2568       }
2569       DefaultOpInfo.DefaultOps.push_back(TPN);
2570     }
2571 
2572     // Insert it into the DefaultOperands map so we can find it later.
2573     DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2574   }
2575 }
2576 
2577 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2578 /// instruction input.  Return true if this is a real use.
2579 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2580                       std::map<std::string, TreePatternNode*> &InstInputs) {
2581   // No name -> not interesting.
2582   if (Pat->getName().empty()) {
2583     if (Pat->isLeaf()) {
2584       DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2585       if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2586                  DI->getDef()->isSubClassOf("RegisterOperand")))
2587         I->error("Input " + DI->getDef()->getName() + " must be named!");
2588     }
2589     return false;
2590   }
2591 
2592   Record *Rec;
2593   if (Pat->isLeaf()) {
2594     DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2595     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2596     Rec = DI->getDef();
2597   } else {
2598     Rec = Pat->getOperator();
2599   }
2600 
2601   // SRCVALUE nodes are ignored.
2602   if (Rec->getName() == "srcvalue")
2603     return false;
2604 
2605   TreePatternNode *&Slot = InstInputs[Pat->getName()];
2606   if (!Slot) {
2607     Slot = Pat;
2608     return true;
2609   }
2610   Record *SlotRec;
2611   if (Slot->isLeaf()) {
2612     SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2613   } else {
2614     assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2615     SlotRec = Slot->getOperator();
2616   }
2617 
2618   // Ensure that the inputs agree if we've already seen this input.
2619   if (Rec != SlotRec)
2620     I->error("All $" + Pat->getName() + " inputs must agree with each other");
2621   if (Slot->getExtTypes() != Pat->getExtTypes())
2622     I->error("All $" + Pat->getName() + " inputs must agree with each other");
2623   return true;
2624 }
2625 
2626 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2627 /// part of "I", the instruction), computing the set of inputs and outputs of
2628 /// the pattern.  Report errors if we see anything naughty.
2629 void CodeGenDAGPatterns::
2630 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2631                             std::map<std::string, TreePatternNode*> &InstInputs,
2632                             std::map<std::string, TreePatternNode*>&InstResults,
2633                             std::vector<Record*> &InstImpResults) {
2634   if (Pat->isLeaf()) {
2635     bool isUse = HandleUse(I, Pat, InstInputs);
2636     if (!isUse && Pat->getTransformFn())
2637       I->error("Cannot specify a transform function for a non-input value!");
2638     return;
2639   }
2640 
2641   if (Pat->getOperator()->getName() == "implicit") {
2642     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2643       TreePatternNode *Dest = Pat->getChild(i);
2644       if (!Dest->isLeaf())
2645         I->error("implicitly defined value should be a register!");
2646 
2647       DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2648       if (!Val || !Val->getDef()->isSubClassOf("Register"))
2649         I->error("implicitly defined value should be a register!");
2650       InstImpResults.push_back(Val->getDef());
2651     }
2652     return;
2653   }
2654 
2655   if (Pat->getOperator()->getName() != "set") {
2656     // If this is not a set, verify that the children nodes are not void typed,
2657     // and recurse.
2658     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2659       if (Pat->getChild(i)->getNumTypes() == 0)
2660         I->error("Cannot have void nodes inside of patterns!");
2661       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2662                                   InstImpResults);
2663     }
2664 
2665     // If this is a non-leaf node with no children, treat it basically as if
2666     // it were a leaf.  This handles nodes like (imm).
2667     bool isUse = HandleUse(I, Pat, InstInputs);
2668 
2669     if (!isUse && Pat->getTransformFn())
2670       I->error("Cannot specify a transform function for a non-input value!");
2671     return;
2672   }
2673 
2674   // Otherwise, this is a set, validate and collect instruction results.
2675   if (Pat->getNumChildren() == 0)
2676     I->error("set requires operands!");
2677 
2678   if (Pat->getTransformFn())
2679     I->error("Cannot specify a transform function on a set node!");
2680 
2681   // Check the set destinations.
2682   unsigned NumDests = Pat->getNumChildren()-1;
2683   for (unsigned i = 0; i != NumDests; ++i) {
2684     TreePatternNode *Dest = Pat->getChild(i);
2685     if (!Dest->isLeaf())
2686       I->error("set destination should be a register!");
2687 
2688     DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2689     if (!Val) {
2690       I->error("set destination should be a register!");
2691       continue;
2692     }
2693 
2694     if (Val->getDef()->isSubClassOf("RegisterClass") ||
2695         Val->getDef()->isSubClassOf("ValueType") ||
2696         Val->getDef()->isSubClassOf("RegisterOperand") ||
2697         Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2698       if (Dest->getName().empty())
2699         I->error("set destination must have a name!");
2700       if (InstResults.count(Dest->getName()))
2701         I->error("cannot set '" + Dest->getName() +"' multiple times");
2702       InstResults[Dest->getName()] = Dest;
2703     } else if (Val->getDef()->isSubClassOf("Register")) {
2704       InstImpResults.push_back(Val->getDef());
2705     } else {
2706       I->error("set destination should be a register!");
2707     }
2708   }
2709 
2710   // Verify and collect info from the computation.
2711   FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2712                               InstInputs, InstResults, InstImpResults);
2713 }
2714 
2715 //===----------------------------------------------------------------------===//
2716 // Instruction Analysis
2717 //===----------------------------------------------------------------------===//
2718 
2719 class InstAnalyzer {
2720   const CodeGenDAGPatterns &CDP;
2721 public:
2722   bool hasSideEffects;
2723   bool mayStore;
2724   bool mayLoad;
2725   bool isBitcast;
2726   bool isVariadic;
2727 
2728   InstAnalyzer(const CodeGenDAGPatterns &cdp)
2729     : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2730       isBitcast(false), isVariadic(false) {}
2731 
2732   void Analyze(const TreePattern *Pat) {
2733     // Assume only the first tree is the pattern. The others are clobber nodes.
2734     AnalyzeNode(Pat->getTree(0));
2735   }
2736 
2737   void Analyze(const PatternToMatch *Pat) {
2738     AnalyzeNode(Pat->getSrcPattern());
2739   }
2740 
2741 private:
2742   bool IsNodeBitcast(const TreePatternNode *N) const {
2743     if (hasSideEffects || mayLoad || mayStore || isVariadic)
2744       return false;
2745 
2746     if (N->getNumChildren() != 2)
2747       return false;
2748 
2749     const TreePatternNode *N0 = N->getChild(0);
2750     if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2751       return false;
2752 
2753     const TreePatternNode *N1 = N->getChild(1);
2754     if (N1->isLeaf())
2755       return false;
2756     if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2757       return false;
2758 
2759     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2760     if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2761       return false;
2762     return OpInfo.getEnumName() == "ISD::BITCAST";
2763   }
2764 
2765 public:
2766   void AnalyzeNode(const TreePatternNode *N) {
2767     if (N->isLeaf()) {
2768       if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2769         Record *LeafRec = DI->getDef();
2770         // Handle ComplexPattern leaves.
2771         if (LeafRec->isSubClassOf("ComplexPattern")) {
2772           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2773           if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2774           if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2775           if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2776         }
2777       }
2778       return;
2779     }
2780 
2781     // Analyze children.
2782     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2783       AnalyzeNode(N->getChild(i));
2784 
2785     // Ignore set nodes, which are not SDNodes.
2786     if (N->getOperator()->getName() == "set") {
2787       isBitcast = IsNodeBitcast(N);
2788       return;
2789     }
2790 
2791     // Notice properties of the node.
2792     if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2793     if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2794     if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2795     if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2796 
2797     if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2798       // If this is an intrinsic, analyze it.
2799       if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
2800         mayLoad = true;// These may load memory.
2801 
2802       if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
2803         mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2804 
2805       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2806         // ReadWriteMem intrinsics can have other strange effects.
2807         hasSideEffects = true;
2808     }
2809   }
2810 
2811 };
2812 
2813 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2814                              const InstAnalyzer &PatInfo,
2815                              Record *PatDef) {
2816   bool Error = false;
2817 
2818   // Remember where InstInfo got its flags.
2819   if (InstInfo.hasUndefFlags())
2820       InstInfo.InferredFrom = PatDef;
2821 
2822   // Check explicitly set flags for consistency.
2823   if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2824       !InstInfo.hasSideEffects_Unset) {
2825     // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2826     // the pattern has no side effects. That could be useful for div/rem
2827     // instructions that may trap.
2828     if (!InstInfo.hasSideEffects) {
2829       Error = true;
2830       PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2831                  Twine(InstInfo.hasSideEffects));
2832     }
2833   }
2834 
2835   if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2836     Error = true;
2837     PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2838                Twine(InstInfo.mayStore));
2839   }
2840 
2841   if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2842     // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2843     // Some targets translate immediates to loads.
2844     if (!InstInfo.mayLoad) {
2845       Error = true;
2846       PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2847                  Twine(InstInfo.mayLoad));
2848     }
2849   }
2850 
2851   // Transfer inferred flags.
2852   InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2853   InstInfo.mayStore |= PatInfo.mayStore;
2854   InstInfo.mayLoad |= PatInfo.mayLoad;
2855 
2856   // These flags are silently added without any verification.
2857   InstInfo.isBitcast |= PatInfo.isBitcast;
2858 
2859   // Don't infer isVariadic. This flag means something different on SDNodes and
2860   // instructions. For example, a CALL SDNode is variadic because it has the
2861   // call arguments as operands, but a CALL instruction is not variadic - it
2862   // has argument registers as implicit, not explicit uses.
2863 
2864   return Error;
2865 }
2866 
2867 /// hasNullFragReference - Return true if the DAG has any reference to the
2868 /// null_frag operator.
2869 static bool hasNullFragReference(DagInit *DI) {
2870   DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2871   if (!OpDef) return false;
2872   Record *Operator = OpDef->getDef();
2873 
2874   // If this is the null fragment, return true.
2875   if (Operator->getName() == "null_frag") return true;
2876   // If any of the arguments reference the null fragment, return true.
2877   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2878     DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2879     if (Arg && hasNullFragReference(Arg))
2880       return true;
2881   }
2882 
2883   return false;
2884 }
2885 
2886 /// hasNullFragReference - Return true if any DAG in the list references
2887 /// the null_frag operator.
2888 static bool hasNullFragReference(ListInit *LI) {
2889   for (Init *I : LI->getValues()) {
2890     DagInit *DI = dyn_cast<DagInit>(I);
2891     assert(DI && "non-dag in an instruction Pattern list?!");
2892     if (hasNullFragReference(DI))
2893       return true;
2894   }
2895   return false;
2896 }
2897 
2898 /// Get all the instructions in a tree.
2899 static void
2900 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2901   if (Tree->isLeaf())
2902     return;
2903   if (Tree->getOperator()->isSubClassOf("Instruction"))
2904     Instrs.push_back(Tree->getOperator());
2905   for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2906     getInstructionsInTree(Tree->getChild(i), Instrs);
2907 }
2908 
2909 /// Check the class of a pattern leaf node against the instruction operand it
2910 /// represents.
2911 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2912                               Record *Leaf) {
2913   if (OI.Rec == Leaf)
2914     return true;
2915 
2916   // Allow direct value types to be used in instruction set patterns.
2917   // The type will be checked later.
2918   if (Leaf->isSubClassOf("ValueType"))
2919     return true;
2920 
2921   // Patterns can also be ComplexPattern instances.
2922   if (Leaf->isSubClassOf("ComplexPattern"))
2923     return true;
2924 
2925   return false;
2926 }
2927 
2928 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2929     CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2930 
2931   assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2932 
2933   // Parse the instruction.
2934   TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2935   // Inline pattern fragments into it.
2936   I->InlinePatternFragments();
2937 
2938   // Infer as many types as possible.  If we cannot infer all of them, we can
2939   // never do anything with this instruction pattern: report it to the user.
2940   if (!I->InferAllTypes())
2941     I->error("Could not infer all types in pattern!");
2942 
2943   // InstInputs - Keep track of all of the inputs of the instruction, along
2944   // with the record they are declared as.
2945   std::map<std::string, TreePatternNode*> InstInputs;
2946 
2947   // InstResults - Keep track of all the virtual registers that are 'set'
2948   // in the instruction, including what reg class they are.
2949   std::map<std::string, TreePatternNode*> InstResults;
2950 
2951   std::vector<Record*> InstImpResults;
2952 
2953   // Verify that the top-level forms in the instruction are of void type, and
2954   // fill in the InstResults map.
2955   for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2956     TreePatternNode *Pat = I->getTree(j);
2957     if (Pat->getNumTypes() != 0) {
2958       std::string Types;
2959       for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
2960         if (k > 0)
2961           Types += ", ";
2962         Types += Pat->getExtType(k).getName();
2963       }
2964       I->error("Top-level forms in instruction pattern should have"
2965                " void types, has types " + Types);
2966     }
2967 
2968     // Find inputs and outputs, and verify the structure of the uses/defs.
2969     FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2970                                 InstImpResults);
2971   }
2972 
2973   // Now that we have inputs and outputs of the pattern, inspect the operands
2974   // list for the instruction.  This determines the order that operands are
2975   // added to the machine instruction the node corresponds to.
2976   unsigned NumResults = InstResults.size();
2977 
2978   // Parse the operands list from the (ops) list, validating it.
2979   assert(I->getArgList().empty() && "Args list should still be empty here!");
2980 
2981   // Check that all of the results occur first in the list.
2982   std::vector<Record*> Results;
2983   SmallVector<TreePatternNode *, 2> ResNodes;
2984   for (unsigned i = 0; i != NumResults; ++i) {
2985     if (i == CGI.Operands.size())
2986       I->error("'" + InstResults.begin()->first +
2987                "' set but does not appear in operand list!");
2988     const std::string &OpName = CGI.Operands[i].Name;
2989 
2990     // Check that it exists in InstResults.
2991     TreePatternNode *RNode = InstResults[OpName];
2992     if (!RNode)
2993       I->error("Operand $" + OpName + " does not exist in operand list!");
2994 
2995     ResNodes.push_back(RNode);
2996 
2997     Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2998     if (!R)
2999       I->error("Operand $" + OpName + " should be a set destination: all "
3000                "outputs must occur before inputs in operand list!");
3001 
3002     if (!checkOperandClass(CGI.Operands[i], R))
3003       I->error("Operand $" + OpName + " class mismatch!");
3004 
3005     // Remember the return type.
3006     Results.push_back(CGI.Operands[i].Rec);
3007 
3008     // Okay, this one checks out.
3009     InstResults.erase(OpName);
3010   }
3011 
3012   // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
3013   // the copy while we're checking the inputs.
3014   std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3015 
3016   std::vector<TreePatternNode*> ResultNodeOperands;
3017   std::vector<Record*> Operands;
3018   for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3019     CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3020     const std::string &OpName = Op.Name;
3021     if (OpName.empty())
3022       I->error("Operand #" + utostr(i) + " in operands list has no name!");
3023 
3024     if (!InstInputsCheck.count(OpName)) {
3025       // If this is an operand with a DefaultOps set filled in, we can ignore
3026       // this.  When we codegen it, we will do so as always executed.
3027       if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3028         // Does it have a non-empty DefaultOps field?  If so, ignore this
3029         // operand.
3030         if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3031           continue;
3032       }
3033       I->error("Operand $" + OpName +
3034                " does not appear in the instruction pattern");
3035     }
3036     TreePatternNode *InVal = InstInputsCheck[OpName];
3037     InstInputsCheck.erase(OpName);   // It occurred, remove from map.
3038 
3039     if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3040       Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3041       if (!checkOperandClass(Op, InRec))
3042         I->error("Operand $" + OpName + "'s register class disagrees"
3043                  " between the operand and pattern");
3044     }
3045     Operands.push_back(Op.Rec);
3046 
3047     // Construct the result for the dest-pattern operand list.
3048     TreePatternNode *OpNode = InVal->clone();
3049 
3050     // No predicate is useful on the result.
3051     OpNode->clearPredicateFns();
3052 
3053     // Promote the xform function to be an explicit node if set.
3054     if (Record *Xform = OpNode->getTransformFn()) {
3055       OpNode->setTransformFn(nullptr);
3056       std::vector<TreePatternNode*> Children;
3057       Children.push_back(OpNode);
3058       OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3059     }
3060 
3061     ResultNodeOperands.push_back(OpNode);
3062   }
3063 
3064   if (!InstInputsCheck.empty())
3065     I->error("Input operand $" + InstInputsCheck.begin()->first +
3066              " occurs in pattern but not in operands list!");
3067 
3068   TreePatternNode *ResultPattern =
3069     new TreePatternNode(I->getRecord(), ResultNodeOperands,
3070                         GetNumNodeResults(I->getRecord(), *this));
3071   // Copy fully inferred output node types to instruction result pattern.
3072   for (unsigned i = 0; i != NumResults; ++i) {
3073     assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3074     ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3075   }
3076 
3077   // Create and insert the instruction.
3078   // FIXME: InstImpResults should not be part of DAGInstruction.
3079   DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3080   DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3081 
3082   // Use a temporary tree pattern to infer all types and make sure that the
3083   // constructed result is correct.  This depends on the instruction already
3084   // being inserted into the DAGInsts map.
3085   TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3086   Temp.InferAllTypes(&I->getNamedNodesMap());
3087 
3088   DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3089   TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3090 
3091   return TheInsertedInst;
3092 }
3093 
3094 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3095 /// any fragments involved.  This populates the Instructions list with fully
3096 /// resolved instructions.
3097 void CodeGenDAGPatterns::ParseInstructions() {
3098   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3099 
3100   for (Record *Instr : Instrs) {
3101     ListInit *LI = nullptr;
3102 
3103     if (isa<ListInit>(Instr->getValueInit("Pattern")))
3104       LI = Instr->getValueAsListInit("Pattern");
3105 
3106     // If there is no pattern, only collect minimal information about the
3107     // instruction for its operand list.  We have to assume that there is one
3108     // result, as we have no detailed info. A pattern which references the
3109     // null_frag operator is as-if no pattern were specified. Normally this
3110     // is from a multiclass expansion w/ a SDPatternOperator passed in as
3111     // null_frag.
3112     if (!LI || LI->empty() || hasNullFragReference(LI)) {
3113       std::vector<Record*> Results;
3114       std::vector<Record*> Operands;
3115 
3116       CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3117 
3118       if (InstInfo.Operands.size() != 0) {
3119         for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3120           Results.push_back(InstInfo.Operands[j].Rec);
3121 
3122         // The rest are inputs.
3123         for (unsigned j = InstInfo.Operands.NumDefs,
3124                e = InstInfo.Operands.size(); j < e; ++j)
3125           Operands.push_back(InstInfo.Operands[j].Rec);
3126       }
3127 
3128       // Create and insert the instruction.
3129       std::vector<Record*> ImpResults;
3130       Instructions.insert(std::make_pair(Instr,
3131                           DAGInstruction(nullptr, Results, Operands, ImpResults)));
3132       continue;  // no pattern.
3133     }
3134 
3135     CodeGenInstruction &CGI = Target.getInstruction(Instr);
3136     const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3137 
3138     (void)DI;
3139     DEBUG(DI.getPattern()->dump());
3140   }
3141 
3142   // If we can, convert the instructions to be patterns that are matched!
3143   for (auto &Entry : Instructions) {
3144     DAGInstruction &TheInst = Entry.second;
3145     TreePattern *I = TheInst.getPattern();
3146     if (!I) continue;  // No pattern.
3147 
3148     // FIXME: Assume only the first tree is the pattern. The others are clobber
3149     // nodes.
3150     TreePatternNode *Pattern = I->getTree(0);
3151     TreePatternNode *SrcPattern;
3152     if (Pattern->getOperator()->getName() == "set") {
3153       SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3154     } else{
3155       // Not a set (store or something?)
3156       SrcPattern = Pattern;
3157     }
3158 
3159     Record *Instr = Entry.first;
3160     AddPatternToMatch(I,
3161                       PatternToMatch(Instr,
3162                                      Instr->getValueAsListInit("Predicates"),
3163                                      SrcPattern,
3164                                      TheInst.getResultPattern(),
3165                                      TheInst.getImpResults(),
3166                                      Instr->getValueAsInt("AddedComplexity"),
3167                                      Instr->getID()));
3168   }
3169 }
3170 
3171 
3172 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3173 
3174 static void FindNames(const TreePatternNode *P,
3175                       std::map<std::string, NameRecord> &Names,
3176                       TreePattern *PatternTop) {
3177   if (!P->getName().empty()) {
3178     NameRecord &Rec = Names[P->getName()];
3179     // If this is the first instance of the name, remember the node.
3180     if (Rec.second++ == 0)
3181       Rec.first = P;
3182     else if (Rec.first->getExtTypes() != P->getExtTypes())
3183       PatternTop->error("repetition of value: $" + P->getName() +
3184                         " where different uses have different types!");
3185   }
3186 
3187   if (!P->isLeaf()) {
3188     for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3189       FindNames(P->getChild(i), Names, PatternTop);
3190   }
3191 }
3192 
3193 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3194                                            const PatternToMatch &PTM) {
3195   // Do some sanity checking on the pattern we're about to match.
3196   std::string Reason;
3197   if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3198     PrintWarning(Pattern->getRecord()->getLoc(),
3199       Twine("Pattern can never match: ") + Reason);
3200     return;
3201   }
3202 
3203   // If the source pattern's root is a complex pattern, that complex pattern
3204   // must specify the nodes it can potentially match.
3205   if (const ComplexPattern *CP =
3206         PTM.getSrcPattern()->getComplexPatternInfo(*this))
3207     if (CP->getRootNodes().empty())
3208       Pattern->error("ComplexPattern at root must specify list of opcodes it"
3209                      " could match");
3210 
3211 
3212   // Find all of the named values in the input and output, ensure they have the
3213   // same type.
3214   std::map<std::string, NameRecord> SrcNames, DstNames;
3215   FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3216   FindNames(PTM.getDstPattern(), DstNames, Pattern);
3217 
3218   // Scan all of the named values in the destination pattern, rejecting them if
3219   // they don't exist in the input pattern.
3220   for (const auto &Entry : DstNames) {
3221     if (SrcNames[Entry.first].first == nullptr)
3222       Pattern->error("Pattern has input without matching name in output: $" +
3223                      Entry.first);
3224   }
3225 
3226   // Scan all of the named values in the source pattern, rejecting them if the
3227   // name isn't used in the dest, and isn't used to tie two values together.
3228   for (const auto &Entry : SrcNames)
3229     if (DstNames[Entry.first].first == nullptr &&
3230         SrcNames[Entry.first].second == 1)
3231       Pattern->error("Pattern has dead named input: $" + Entry.first);
3232 
3233   PatternsToMatch.push_back(PTM);
3234 }
3235 
3236 
3237 
3238 void CodeGenDAGPatterns::InferInstructionFlags() {
3239   ArrayRef<const CodeGenInstruction*> Instructions =
3240     Target.getInstructionsByEnumValue();
3241 
3242   // First try to infer flags from the primary instruction pattern, if any.
3243   SmallVector<CodeGenInstruction*, 8> Revisit;
3244   unsigned Errors = 0;
3245   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3246     CodeGenInstruction &InstInfo =
3247       const_cast<CodeGenInstruction &>(*Instructions[i]);
3248 
3249     // Get the primary instruction pattern.
3250     const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3251     if (!Pattern) {
3252       if (InstInfo.hasUndefFlags())
3253         Revisit.push_back(&InstInfo);
3254       continue;
3255     }
3256     InstAnalyzer PatInfo(*this);
3257     PatInfo.Analyze(Pattern);
3258     Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3259   }
3260 
3261   // Second, look for single-instruction patterns defined outside the
3262   // instruction.
3263   for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3264     const PatternToMatch &PTM = *I;
3265 
3266     // We can only infer from single-instruction patterns, otherwise we won't
3267     // know which instruction should get the flags.
3268     SmallVector<Record*, 8> PatInstrs;
3269     getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3270     if (PatInstrs.size() != 1)
3271       continue;
3272 
3273     // Get the single instruction.
3274     CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3275 
3276     // Only infer properties from the first pattern. We'll verify the others.
3277     if (InstInfo.InferredFrom)
3278       continue;
3279 
3280     InstAnalyzer PatInfo(*this);
3281     PatInfo.Analyze(&PTM);
3282     Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3283   }
3284 
3285   if (Errors)
3286     PrintFatalError("pattern conflicts");
3287 
3288   // Revisit instructions with undefined flags and no pattern.
3289   if (Target.guessInstructionProperties()) {
3290     for (CodeGenInstruction *InstInfo : Revisit) {
3291       if (InstInfo->InferredFrom)
3292         continue;
3293       // The mayLoad and mayStore flags default to false.
3294       // Conservatively assume hasSideEffects if it wasn't explicit.
3295       if (InstInfo->hasSideEffects_Unset)
3296         InstInfo->hasSideEffects = true;
3297     }
3298     return;
3299   }
3300 
3301   // Complain about any flags that are still undefined.
3302   for (CodeGenInstruction *InstInfo : Revisit) {
3303     if (InstInfo->InferredFrom)
3304       continue;
3305     if (InstInfo->hasSideEffects_Unset)
3306       PrintError(InstInfo->TheDef->getLoc(),
3307                  "Can't infer hasSideEffects from patterns");
3308     if (InstInfo->mayStore_Unset)
3309       PrintError(InstInfo->TheDef->getLoc(),
3310                  "Can't infer mayStore from patterns");
3311     if (InstInfo->mayLoad_Unset)
3312       PrintError(InstInfo->TheDef->getLoc(),
3313                  "Can't infer mayLoad from patterns");
3314   }
3315 }
3316 
3317 
3318 /// Verify instruction flags against pattern node properties.
3319 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3320   unsigned Errors = 0;
3321   for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3322     const PatternToMatch &PTM = *I;
3323     SmallVector<Record*, 8> Instrs;
3324     getInstructionsInTree(PTM.getDstPattern(), Instrs);
3325     if (Instrs.empty())
3326       continue;
3327 
3328     // Count the number of instructions with each flag set.
3329     unsigned NumSideEffects = 0;
3330     unsigned NumStores = 0;
3331     unsigned NumLoads = 0;
3332     for (const Record *Instr : Instrs) {
3333       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3334       NumSideEffects += InstInfo.hasSideEffects;
3335       NumStores += InstInfo.mayStore;
3336       NumLoads += InstInfo.mayLoad;
3337     }
3338 
3339     // Analyze the source pattern.
3340     InstAnalyzer PatInfo(*this);
3341     PatInfo.Analyze(&PTM);
3342 
3343     // Collect error messages.
3344     SmallVector<std::string, 4> Msgs;
3345 
3346     // Check for missing flags in the output.
3347     // Permit extra flags for now at least.
3348     if (PatInfo.hasSideEffects && !NumSideEffects)
3349       Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3350 
3351     // Don't verify store flags on instructions with side effects. At least for
3352     // intrinsics, side effects implies mayStore.
3353     if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3354       Msgs.push_back("pattern may store, but mayStore isn't set");
3355 
3356     // Similarly, mayStore implies mayLoad on intrinsics.
3357     if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3358       Msgs.push_back("pattern may load, but mayLoad isn't set");
3359 
3360     // Print error messages.
3361     if (Msgs.empty())
3362       continue;
3363     ++Errors;
3364 
3365     for (const std::string &Msg : Msgs)
3366       PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3367                  (Instrs.size() == 1 ?
3368                   "instruction" : "output instructions"));
3369     // Provide the location of the relevant instruction definitions.
3370     for (const Record *Instr : Instrs) {
3371       if (Instr != PTM.getSrcRecord())
3372         PrintError(Instr->getLoc(), "defined here");
3373       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3374       if (InstInfo.InferredFrom &&
3375           InstInfo.InferredFrom != InstInfo.TheDef &&
3376           InstInfo.InferredFrom != PTM.getSrcRecord())
3377         PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3378     }
3379   }
3380   if (Errors)
3381     PrintFatalError("Errors in DAG patterns");
3382 }
3383 
3384 /// Given a pattern result with an unresolved type, see if we can find one
3385 /// instruction with an unresolved result type.  Force this result type to an
3386 /// arbitrary element if it's possible types to converge results.
3387 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3388   if (N->isLeaf())
3389     return false;
3390 
3391   // Analyze children.
3392   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3393     if (ForceArbitraryInstResultType(N->getChild(i), TP))
3394       return true;
3395 
3396   if (!N->getOperator()->isSubClassOf("Instruction"))
3397     return false;
3398 
3399   // If this type is already concrete or completely unknown we can't do
3400   // anything.
3401   for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3402     if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3403       continue;
3404 
3405     // Otherwise, force its type to the first possibility (an arbitrary choice).
3406     if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3407       return true;
3408   }
3409 
3410   return false;
3411 }
3412 
3413 void CodeGenDAGPatterns::ParsePatterns() {
3414   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3415 
3416   for (Record *CurPattern : Patterns) {
3417     DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3418 
3419     // If the pattern references the null_frag, there's nothing to do.
3420     if (hasNullFragReference(Tree))
3421       continue;
3422 
3423     TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3424 
3425     // Inline pattern fragments into it.
3426     Pattern->InlinePatternFragments();
3427 
3428     ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3429     if (LI->empty()) continue;  // no pattern.
3430 
3431     // Parse the instruction.
3432     TreePattern Result(CurPattern, LI, false, *this);
3433 
3434     // Inline pattern fragments into it.
3435     Result.InlinePatternFragments();
3436 
3437     if (Result.getNumTrees() != 1)
3438       Result.error("Cannot handle instructions producing instructions "
3439                    "with temporaries yet!");
3440 
3441     bool IterateInference;
3442     bool InferredAllPatternTypes, InferredAllResultTypes;
3443     do {
3444       // Infer as many types as possible.  If we cannot infer all of them, we
3445       // can never do anything with this pattern: report it to the user.
3446       InferredAllPatternTypes =
3447         Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3448 
3449       // Infer as many types as possible.  If we cannot infer all of them, we
3450       // can never do anything with this pattern: report it to the user.
3451       InferredAllResultTypes =
3452           Result.InferAllTypes(&Pattern->getNamedNodesMap());
3453 
3454       IterateInference = false;
3455 
3456       // Apply the type of the result to the source pattern.  This helps us
3457       // resolve cases where the input type is known to be a pointer type (which
3458       // is considered resolved), but the result knows it needs to be 32- or
3459       // 64-bits.  Infer the other way for good measure.
3460       for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3461                                         Pattern->getTree(0)->getNumTypes());
3462            i != e; ++i) {
3463         IterateInference = Pattern->getTree(0)->UpdateNodeType(
3464             i, Result.getTree(0)->getExtType(i), Result);
3465         IterateInference |= Result.getTree(0)->UpdateNodeType(
3466             i, Pattern->getTree(0)->getExtType(i), Result);
3467       }
3468 
3469       // If our iteration has converged and the input pattern's types are fully
3470       // resolved but the result pattern is not fully resolved, we may have a
3471       // situation where we have two instructions in the result pattern and
3472       // the instructions require a common register class, but don't care about
3473       // what actual MVT is used.  This is actually a bug in our modelling:
3474       // output patterns should have register classes, not MVTs.
3475       //
3476       // In any case, to handle this, we just go through and disambiguate some
3477       // arbitrary types to the result pattern's nodes.
3478       if (!IterateInference && InferredAllPatternTypes &&
3479           !InferredAllResultTypes)
3480         IterateInference =
3481             ForceArbitraryInstResultType(Result.getTree(0), Result);
3482     } while (IterateInference);
3483 
3484     // Verify that we inferred enough types that we can do something with the
3485     // pattern and result.  If these fire the user has to add type casts.
3486     if (!InferredAllPatternTypes)
3487       Pattern->error("Could not infer all types in pattern!");
3488     if (!InferredAllResultTypes) {
3489       Pattern->dump();
3490       Result.error("Could not infer all types in pattern result!");
3491     }
3492 
3493     // Validate that the input pattern is correct.
3494     std::map<std::string, TreePatternNode*> InstInputs;
3495     std::map<std::string, TreePatternNode*> InstResults;
3496     std::vector<Record*> InstImpResults;
3497     for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3498       FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3499                                   InstInputs, InstResults,
3500                                   InstImpResults);
3501 
3502     // Promote the xform function to be an explicit node if set.
3503     TreePatternNode *DstPattern = Result.getOnlyTree();
3504     std::vector<TreePatternNode*> ResultNodeOperands;
3505     for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3506       TreePatternNode *OpNode = DstPattern->getChild(ii);
3507       if (Record *Xform = OpNode->getTransformFn()) {
3508         OpNode->setTransformFn(nullptr);
3509         std::vector<TreePatternNode*> Children;
3510         Children.push_back(OpNode);
3511         OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3512       }
3513       ResultNodeOperands.push_back(OpNode);
3514     }
3515     DstPattern = Result.getOnlyTree();
3516     if (!DstPattern->isLeaf())
3517       DstPattern = new TreePatternNode(DstPattern->getOperator(),
3518                                        ResultNodeOperands,
3519                                        DstPattern->getNumTypes());
3520 
3521     for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3522       DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3523 
3524     TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3525     Temp.InferAllTypes();
3526 
3527 
3528     AddPatternToMatch(Pattern,
3529                     PatternToMatch(CurPattern,
3530                                    CurPattern->getValueAsListInit("Predicates"),
3531                                    Pattern->getTree(0),
3532                                    Temp.getOnlyTree(), InstImpResults,
3533                                    CurPattern->getValueAsInt("AddedComplexity"),
3534                                    CurPattern->getID()));
3535   }
3536 }
3537 
3538 /// CombineChildVariants - Given a bunch of permutations of each child of the
3539 /// 'operator' node, put them together in all possible ways.
3540 static void CombineChildVariants(TreePatternNode *Orig,
3541                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3542                                  std::vector<TreePatternNode*> &OutVariants,
3543                                  CodeGenDAGPatterns &CDP,
3544                                  const MultipleUseVarSet &DepVars) {
3545   // Make sure that each operand has at least one variant to choose from.
3546   for (const auto &Variants : ChildVariants)
3547     if (Variants.empty())
3548       return;
3549 
3550   // The end result is an all-pairs construction of the resultant pattern.
3551   std::vector<unsigned> Idxs;
3552   Idxs.resize(ChildVariants.size());
3553   bool NotDone;
3554   do {
3555 #ifndef NDEBUG
3556     DEBUG(if (!Idxs.empty()) {
3557             errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3558               for (unsigned Idx : Idxs) {
3559                 errs() << Idx << " ";
3560             }
3561             errs() << "]\n";
3562           });
3563 #endif
3564     // Create the variant and add it to the output list.
3565     std::vector<TreePatternNode*> NewChildren;
3566     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3567       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3568     auto R = llvm::make_unique<TreePatternNode>(
3569         Orig->getOperator(), NewChildren, Orig->getNumTypes());
3570 
3571     // Copy over properties.
3572     R->setName(Orig->getName());
3573     R->setPredicateFns(Orig->getPredicateFns());
3574     R->setTransformFn(Orig->getTransformFn());
3575     for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3576       R->setType(i, Orig->getExtType(i));
3577 
3578     // If this pattern cannot match, do not include it as a variant.
3579     std::string ErrString;
3580     // Scan to see if this pattern has already been emitted.  We can get
3581     // duplication due to things like commuting:
3582     //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3583     // which are the same pattern.  Ignore the dups.
3584     if (R->canPatternMatch(ErrString, CDP) &&
3585         none_of(OutVariants, [&](TreePatternNode *Variant) {
3586           return R->isIsomorphicTo(Variant, DepVars);
3587         }))
3588       OutVariants.push_back(R.release());
3589 
3590     // Increment indices to the next permutation by incrementing the
3591     // indices from last index backward, e.g., generate the sequence
3592     // [0, 0], [0, 1], [1, 0], [1, 1].
3593     int IdxsIdx;
3594     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3595       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3596         Idxs[IdxsIdx] = 0;
3597       else
3598         break;
3599     }
3600     NotDone = (IdxsIdx >= 0);
3601   } while (NotDone);
3602 }
3603 
3604 /// CombineChildVariants - A helper function for binary operators.
3605 ///
3606 static void CombineChildVariants(TreePatternNode *Orig,
3607                                  const std::vector<TreePatternNode*> &LHS,
3608                                  const std::vector<TreePatternNode*> &RHS,
3609                                  std::vector<TreePatternNode*> &OutVariants,
3610                                  CodeGenDAGPatterns &CDP,
3611                                  const MultipleUseVarSet &DepVars) {
3612   std::vector<std::vector<TreePatternNode*> > ChildVariants;
3613   ChildVariants.push_back(LHS);
3614   ChildVariants.push_back(RHS);
3615   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3616 }
3617 
3618 
3619 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3620                                      std::vector<TreePatternNode *> &Children) {
3621   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3622   Record *Operator = N->getOperator();
3623 
3624   // Only permit raw nodes.
3625   if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3626       N->getTransformFn()) {
3627     Children.push_back(N);
3628     return;
3629   }
3630 
3631   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3632     Children.push_back(N->getChild(0));
3633   else
3634     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3635 
3636   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3637     Children.push_back(N->getChild(1));
3638   else
3639     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3640 }
3641 
3642 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3643 /// the (potentially recursive) pattern by using algebraic laws.
3644 ///
3645 static void GenerateVariantsOf(TreePatternNode *N,
3646                                std::vector<TreePatternNode*> &OutVariants,
3647                                CodeGenDAGPatterns &CDP,
3648                                const MultipleUseVarSet &DepVars) {
3649   // We cannot permute leaves or ComplexPattern uses.
3650   if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3651     OutVariants.push_back(N);
3652     return;
3653   }
3654 
3655   // Look up interesting info about the node.
3656   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3657 
3658   // If this node is associative, re-associate.
3659   if (NodeInfo.hasProperty(SDNPAssociative)) {
3660     // Re-associate by pulling together all of the linked operators
3661     std::vector<TreePatternNode*> MaximalChildren;
3662     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3663 
3664     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
3665     // permutations.
3666     if (MaximalChildren.size() == 3) {
3667       // Find the variants of all of our maximal children.
3668       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3669       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3670       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3671       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3672 
3673       // There are only two ways we can permute the tree:
3674       //   (A op B) op C    and    A op (B op C)
3675       // Within these forms, we can also permute A/B/C.
3676 
3677       // Generate legal pair permutations of A/B/C.
3678       std::vector<TreePatternNode*> ABVariants;
3679       std::vector<TreePatternNode*> BAVariants;
3680       std::vector<TreePatternNode*> ACVariants;
3681       std::vector<TreePatternNode*> CAVariants;
3682       std::vector<TreePatternNode*> BCVariants;
3683       std::vector<TreePatternNode*> CBVariants;
3684       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3685       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3686       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3687       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3688       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3689       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3690 
3691       // Combine those into the result: (x op x) op x
3692       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3693       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3694       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3695       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3696       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3697       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3698 
3699       // Combine those into the result: x op (x op x)
3700       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3701       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3702       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3703       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3704       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3705       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3706       return;
3707     }
3708   }
3709 
3710   // Compute permutations of all children.
3711   std::vector<std::vector<TreePatternNode*> > ChildVariants;
3712   ChildVariants.resize(N->getNumChildren());
3713   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3714     GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3715 
3716   // Build all permutations based on how the children were formed.
3717   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3718 
3719   // If this node is commutative, consider the commuted order.
3720   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3721   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3722     assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3723            "Commutative but doesn't have 2 children!");
3724     // Don't count children which are actually register references.
3725     unsigned NC = 0;
3726     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3727       TreePatternNode *Child = N->getChild(i);
3728       if (Child->isLeaf())
3729         if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3730           Record *RR = DI->getDef();
3731           if (RR->isSubClassOf("Register"))
3732             continue;
3733         }
3734       NC++;
3735     }
3736     // Consider the commuted order.
3737     if (isCommIntrinsic) {
3738       // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3739       // operands are the commutative operands, and there might be more operands
3740       // after those.
3741       assert(NC >= 3 &&
3742              "Commutative intrinsic should have at least 3 children!");
3743       std::vector<std::vector<TreePatternNode*> > Variants;
3744       Variants.push_back(ChildVariants[0]); // Intrinsic id.
3745       Variants.push_back(ChildVariants[2]);
3746       Variants.push_back(ChildVariants[1]);
3747       for (unsigned i = 3; i != NC; ++i)
3748         Variants.push_back(ChildVariants[i]);
3749       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3750     } else if (NC == 2)
3751       CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3752                            OutVariants, CDP, DepVars);
3753   }
3754 }
3755 
3756 
3757 // GenerateVariants - Generate variants.  For example, commutative patterns can
3758 // match multiple ways.  Add them to PatternsToMatch as well.
3759 void CodeGenDAGPatterns::GenerateVariants() {
3760   DEBUG(errs() << "Generating instruction variants.\n");
3761 
3762   // Loop over all of the patterns we've collected, checking to see if we can
3763   // generate variants of the instruction, through the exploitation of
3764   // identities.  This permits the target to provide aggressive matching without
3765   // the .td file having to contain tons of variants of instructions.
3766   //
3767   // Note that this loop adds new patterns to the PatternsToMatch list, but we
3768   // intentionally do not reconsider these.  Any variants of added patterns have
3769   // already been added.
3770   //
3771   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3772     MultipleUseVarSet             DepVars;
3773     std::vector<TreePatternNode*> Variants;
3774     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3775     DEBUG(errs() << "Dependent/multiply used variables: ");
3776     DEBUG(DumpDepVars(DepVars));
3777     DEBUG(errs() << "\n");
3778     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3779                        DepVars);
3780 
3781     assert(!Variants.empty() && "Must create at least original variant!");
3782     Variants.erase(Variants.begin());  // Remove the original pattern.
3783 
3784     if (Variants.empty())  // No variants for this pattern.
3785       continue;
3786 
3787     DEBUG(errs() << "FOUND VARIANTS OF: ";
3788           PatternsToMatch[i].getSrcPattern()->dump();
3789           errs() << "\n");
3790 
3791     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3792       TreePatternNode *Variant = Variants[v];
3793 
3794       DEBUG(errs() << "  VAR#" << v <<  ": ";
3795             Variant->dump();
3796             errs() << "\n");
3797 
3798       // Scan to see if an instruction or explicit pattern already matches this.
3799       bool AlreadyExists = false;
3800       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3801         // Skip if the top level predicates do not match.
3802         if (PatternsToMatch[i].getPredicates() !=
3803             PatternsToMatch[p].getPredicates())
3804           continue;
3805         // Check to see if this variant already exists.
3806         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3807                                     DepVars)) {
3808           DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
3809           AlreadyExists = true;
3810           break;
3811         }
3812       }
3813       // If we already have it, ignore the variant.
3814       if (AlreadyExists) continue;
3815 
3816       // Otherwise, add it to the list of patterns we have.
3817       PatternsToMatch.emplace_back(
3818           PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3819           Variant, PatternsToMatch[i].getDstPattern(),
3820           PatternsToMatch[i].getDstRegs(),
3821           PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
3822     }
3823 
3824     DEBUG(errs() << "\n");
3825   }
3826 }
3827