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