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