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