1f22ef01cSRoman Divacky //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements the CodeGenDAGPatterns class, which is used to read and
11f22ef01cSRoman Divacky // represent the patterns present in a .td file for instructions.
12f22ef01cSRoman Divacky //
13f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
14f22ef01cSRoman Divacky 
15f22ef01cSRoman Divacky #include "CodeGenDAGPatterns.h"
16*b5893f02SDimitry Andric #include "llvm/ADT/BitVector.h"
172cab237bSDimitry Andric #include "llvm/ADT/DenseSet.h"
18*b5893f02SDimitry Andric #include "llvm/ADT/MapVector.h"
19f22ef01cSRoman Divacky #include "llvm/ADT/STLExtras.h"
202cab237bSDimitry Andric #include "llvm/ADT/SmallSet.h"
217d523365SDimitry Andric #include "llvm/ADT/SmallString.h"
22139f7f9bSDimitry Andric #include "llvm/ADT/StringExtras.h"
232cab237bSDimitry Andric #include "llvm/ADT/StringMap.h"
24cb4dff85SDimitry Andric #include "llvm/ADT/Twine.h"
25f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
26dff0c46cSDimitry Andric #include "llvm/Support/ErrorHandling.h"
27139f7f9bSDimitry Andric #include "llvm/TableGen/Error.h"
28139f7f9bSDimitry Andric #include "llvm/TableGen/Record.h"
29f22ef01cSRoman Divacky #include <algorithm>
30dff0c46cSDimitry Andric #include <cstdio>
31*b5893f02SDimitry Andric #include <iterator>
32dff0c46cSDimitry Andric #include <set>
33f22ef01cSRoman Divacky using namespace llvm;
34f22ef01cSRoman Divacky 
3591bc56edSDimitry Andric #define DEBUG_TYPE "dag-patterns"
3691bc56edSDimitry Andric 
isIntegerOrPtr(MVT VT)372cab237bSDimitry Andric static inline bool isIntegerOrPtr(MVT VT) {
382cab237bSDimitry Andric   return VT.isInteger() || VT == MVT::iPTR;
39f22ef01cSRoman Divacky }
isFloatingPoint(MVT VT)402cab237bSDimitry Andric static inline bool isFloatingPoint(MVT VT) {
412cab237bSDimitry Andric   return VT.isFloatingPoint();
42f22ef01cSRoman Divacky }
isVector(MVT VT)432cab237bSDimitry Andric static inline bool isVector(MVT VT) {
442cab237bSDimitry Andric   return VT.isVector();
45f22ef01cSRoman Divacky }
isScalar(MVT VT)462cab237bSDimitry Andric static inline bool isScalar(MVT VT) {
472cab237bSDimitry Andric   return !VT.isVector();
48f22ef01cSRoman Divacky }
49f22ef01cSRoman Divacky 
502cab237bSDimitry Andric template <typename Predicate>
berase_if(MachineValueTypeSet & S,Predicate P)512cab237bSDimitry Andric static bool berase_if(MachineValueTypeSet &S, Predicate P) {
522cab237bSDimitry Andric   bool Erased = false;
532cab237bSDimitry Andric   // It is ok to iterate over MachineValueTypeSet and remove elements from it
542cab237bSDimitry Andric   // at the same time.
552cab237bSDimitry Andric   for (MVT T : S) {
562cab237bSDimitry Andric     if (!P(T))
572cab237bSDimitry Andric       continue;
582cab237bSDimitry Andric     Erased = true;
592cab237bSDimitry Andric     S.erase(T);
602cab237bSDimitry Andric   }
612cab237bSDimitry Andric   return Erased;
622cab237bSDimitry Andric }
632cab237bSDimitry Andric 
642cab237bSDimitry Andric // --- TypeSetByHwMode
652cab237bSDimitry Andric 
662cab237bSDimitry Andric // This is a parameterized type-set class. For each mode there is a list
672cab237bSDimitry Andric // of types that are currently possible for a given tree node. Type
682cab237bSDimitry Andric // inference will apply to each mode separately.
692cab237bSDimitry Andric 
TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList)702cab237bSDimitry Andric TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
712cab237bSDimitry Andric   for (const ValueTypeByHwMode &VVT : VTList)
722cab237bSDimitry Andric     insert(VVT);
732cab237bSDimitry Andric }
742cab237bSDimitry Andric 
isValueTypeByHwMode(bool AllowEmpty) const752cab237bSDimitry Andric bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
762cab237bSDimitry Andric   for (const auto &I : *this) {
772cab237bSDimitry Andric     if (I.second.size() > 1)
782cab237bSDimitry Andric       return false;
792cab237bSDimitry Andric     if (!AllowEmpty && I.second.empty())
802cab237bSDimitry Andric       return false;
812cab237bSDimitry Andric   }
822cab237bSDimitry Andric   return true;
832cab237bSDimitry Andric }
842cab237bSDimitry Andric 
getValueTypeByHwMode() const852cab237bSDimitry Andric ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
862cab237bSDimitry Andric   assert(isValueTypeByHwMode(true) &&
872cab237bSDimitry Andric          "The type set has multiple types for at least one HW mode");
882cab237bSDimitry Andric   ValueTypeByHwMode VVT;
892cab237bSDimitry Andric   for (const auto &I : *this) {
902cab237bSDimitry Andric     MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
912cab237bSDimitry Andric     VVT.getOrCreateTypeForMode(I.first, T);
922cab237bSDimitry Andric   }
932cab237bSDimitry Andric   return VVT;
942cab237bSDimitry Andric }
952cab237bSDimitry Andric 
isPossible() const962cab237bSDimitry Andric bool TypeSetByHwMode::isPossible() const {
972cab237bSDimitry Andric   for (const auto &I : *this)
982cab237bSDimitry Andric     if (!I.second.empty())
992cab237bSDimitry Andric       return true;
1002cab237bSDimitry Andric   return false;
1012cab237bSDimitry Andric }
1022cab237bSDimitry Andric 
insert(const ValueTypeByHwMode & VVT)1032cab237bSDimitry Andric bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
1042cab237bSDimitry Andric   bool Changed = false;
105*b5893f02SDimitry Andric   bool ContainsDefault = false;
106*b5893f02SDimitry Andric   MVT DT = MVT::Other;
107*b5893f02SDimitry Andric 
1082cab237bSDimitry Andric   SmallDenseSet<unsigned, 4> Modes;
1092cab237bSDimitry Andric   for (const auto &P : VVT) {
1102cab237bSDimitry Andric     unsigned M = P.first;
1112cab237bSDimitry Andric     Modes.insert(M);
1122cab237bSDimitry Andric     // Make sure there exists a set for each specific mode from VVT.
1132cab237bSDimitry Andric     Changed |= getOrCreate(M).insert(P.second).second;
114*b5893f02SDimitry Andric     // Cache VVT's default mode.
115*b5893f02SDimitry Andric     if (DefaultMode == M) {
116*b5893f02SDimitry Andric       ContainsDefault = true;
117*b5893f02SDimitry Andric       DT = P.second;
118*b5893f02SDimitry Andric     }
1192cab237bSDimitry Andric   }
1202cab237bSDimitry Andric 
1212cab237bSDimitry Andric   // If VVT has a default mode, add the corresponding type to all
1222cab237bSDimitry Andric   // modes in "this" that do not exist in VVT.
123*b5893f02SDimitry Andric   if (ContainsDefault)
1242cab237bSDimitry Andric     for (auto &I : *this)
1252cab237bSDimitry Andric       if (!Modes.count(I.first))
1262cab237bSDimitry Andric         Changed |= I.second.insert(DT).second;
127*b5893f02SDimitry Andric 
1282cab237bSDimitry Andric   return Changed;
1292cab237bSDimitry Andric }
1302cab237bSDimitry Andric 
1312cab237bSDimitry Andric // Constrain the type set to be the intersection with VTS.
constrain(const TypeSetByHwMode & VTS)1322cab237bSDimitry Andric bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
1332cab237bSDimitry Andric   bool Changed = false;
1342cab237bSDimitry Andric   if (hasDefault()) {
1352cab237bSDimitry Andric     for (const auto &I : VTS) {
1362cab237bSDimitry Andric       unsigned M = I.first;
1372cab237bSDimitry Andric       if (M == DefaultMode || hasMode(M))
1382cab237bSDimitry Andric         continue;
1392cab237bSDimitry Andric       Map.insert({M, Map.at(DefaultMode)});
1402cab237bSDimitry Andric       Changed = true;
141f22ef01cSRoman Divacky     }
142f22ef01cSRoman Divacky   }
143f22ef01cSRoman Divacky 
1442cab237bSDimitry Andric   for (auto &I : *this) {
1452cab237bSDimitry Andric     unsigned M = I.first;
1462cab237bSDimitry Andric     SetType &S = I.second;
1472cab237bSDimitry Andric     if (VTS.hasMode(M) || VTS.hasDefault()) {
1482cab237bSDimitry Andric       Changed |= intersect(I.second, VTS.get(M));
1492cab237bSDimitry Andric     } else if (!S.empty()) {
1502cab237bSDimitry Andric       S.clear();
1512cab237bSDimitry Andric       Changed = true;
1522cab237bSDimitry Andric     }
1532cab237bSDimitry Andric   }
1542cab237bSDimitry Andric   return Changed;
155f22ef01cSRoman Divacky }
156f22ef01cSRoman Divacky 
1572cab237bSDimitry Andric template <typename Predicate>
constrain(Predicate P)1582cab237bSDimitry Andric bool TypeSetByHwMode::constrain(Predicate P) {
1592cab237bSDimitry Andric   bool Changed = false;
1602cab237bSDimitry Andric   for (auto &I : *this)
1612cab237bSDimitry Andric     Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
1622cab237bSDimitry Andric   return Changed;
1632cab237bSDimitry Andric }
164f22ef01cSRoman Divacky 
1652cab237bSDimitry Andric template <typename Predicate>
assign_if(const TypeSetByHwMode & VTS,Predicate P)1662cab237bSDimitry Andric bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
1672cab237bSDimitry Andric   assert(empty());
1682cab237bSDimitry Andric   for (const auto &I : VTS) {
1692cab237bSDimitry Andric     SetType &S = getOrCreate(I.first);
1702cab237bSDimitry Andric     for (auto J : I.second)
1712cab237bSDimitry Andric       if (P(J))
1722cab237bSDimitry Andric         S.insert(J);
1732cab237bSDimitry Andric   }
1742cab237bSDimitry Andric   return !empty();
1752cab237bSDimitry Andric }
1762cab237bSDimitry Andric 
writeToStream(raw_ostream & OS) const1772cab237bSDimitry Andric void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
1782cab237bSDimitry Andric   SmallVector<unsigned, 4> Modes;
1792cab237bSDimitry Andric   Modes.reserve(Map.size());
1802cab237bSDimitry Andric 
1812cab237bSDimitry Andric   for (const auto &I : *this)
1822cab237bSDimitry Andric     Modes.push_back(I.first);
1832cab237bSDimitry Andric   if (Modes.empty()) {
1842cab237bSDimitry Andric     OS << "{}";
1852cab237bSDimitry Andric     return;
1862cab237bSDimitry Andric   }
1872cab237bSDimitry Andric   array_pod_sort(Modes.begin(), Modes.end());
1882cab237bSDimitry Andric 
1892cab237bSDimitry Andric   OS << '{';
1902cab237bSDimitry Andric   for (unsigned M : Modes) {
1912cab237bSDimitry Andric     OS << ' ' << getModeName(M) << ':';
1922cab237bSDimitry Andric     writeToStream(get(M), OS);
1932cab237bSDimitry Andric   }
1942cab237bSDimitry Andric   OS << " }";
1952cab237bSDimitry Andric }
1962cab237bSDimitry Andric 
writeToStream(const SetType & S,raw_ostream & OS)1972cab237bSDimitry Andric void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
1982cab237bSDimitry Andric   SmallVector<MVT, 4> Types(S.begin(), S.end());
1992cab237bSDimitry Andric   array_pod_sort(Types.begin(), Types.end());
2002cab237bSDimitry Andric 
2012cab237bSDimitry Andric   OS << '[';
2022cab237bSDimitry Andric   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
2032cab237bSDimitry Andric     OS << ValueTypeByHwMode::getMVTName(Types[i]);
2042cab237bSDimitry Andric     if (i != e-1)
2052cab237bSDimitry Andric       OS << ' ';
2062cab237bSDimitry Andric   }
2072cab237bSDimitry Andric   OS << ']';
2082cab237bSDimitry Andric }
2092cab237bSDimitry Andric 
operator ==(const TypeSetByHwMode & VTS) const2102cab237bSDimitry Andric bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
211*b5893f02SDimitry Andric   // The isSimple call is much quicker than hasDefault - check this first.
212*b5893f02SDimitry Andric   bool IsSimple = isSimple();
213*b5893f02SDimitry Andric   bool VTSIsSimple = VTS.isSimple();
214*b5893f02SDimitry Andric   if (IsSimple && VTSIsSimple)
2152cab237bSDimitry Andric     return *begin() == *VTS.begin();
216*b5893f02SDimitry Andric 
217*b5893f02SDimitry Andric   // Speedup: We have a default if the set is simple.
218*b5893f02SDimitry Andric   bool HaveDefault = IsSimple || hasDefault();
219*b5893f02SDimitry Andric   bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
220*b5893f02SDimitry Andric   if (HaveDefault != VTSHaveDefault)
2212cab237bSDimitry Andric     return false;
2222cab237bSDimitry Andric 
2232cab237bSDimitry Andric   SmallDenseSet<unsigned, 4> Modes;
2242cab237bSDimitry Andric   for (auto &I : *this)
2252cab237bSDimitry Andric     Modes.insert(I.first);
2262cab237bSDimitry Andric   for (const auto &I : VTS)
2272cab237bSDimitry Andric     Modes.insert(I.first);
2282cab237bSDimitry Andric 
2292cab237bSDimitry Andric   if (HaveDefault) {
2302cab237bSDimitry Andric     // Both sets have default mode.
2312cab237bSDimitry Andric     for (unsigned M : Modes) {
2322cab237bSDimitry Andric       if (get(M) != VTS.get(M))
2332cab237bSDimitry Andric         return false;
2342cab237bSDimitry Andric     }
2352cab237bSDimitry Andric   } else {
2362cab237bSDimitry Andric     // Neither set has default mode.
2372cab237bSDimitry Andric     for (unsigned M : Modes) {
2382cab237bSDimitry Andric       // If there is no default mode, an empty set is equivalent to not having
2392cab237bSDimitry Andric       // the corresponding mode.
2402cab237bSDimitry Andric       bool NoModeThis = !hasMode(M) || get(M).empty();
2412cab237bSDimitry Andric       bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
2422cab237bSDimitry Andric       if (NoModeThis != NoModeVTS)
2432cab237bSDimitry Andric         return false;
2442cab237bSDimitry Andric       if (!NoModeThis)
2452cab237bSDimitry Andric         if (get(M) != VTS.get(M))
2462cab237bSDimitry Andric           return false;
2472cab237bSDimitry Andric     }
2482cab237bSDimitry Andric   }
2492cab237bSDimitry Andric 
2502cab237bSDimitry Andric   return true;
2512cab237bSDimitry Andric }
2522cab237bSDimitry Andric 
2532cab237bSDimitry Andric namespace llvm {
operator <<(raw_ostream & OS,const TypeSetByHwMode & T)2542cab237bSDimitry Andric   raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
2552cab237bSDimitry Andric     T.writeToStream(OS);
2562cab237bSDimitry Andric     return OS;
2572cab237bSDimitry Andric   }
2582cab237bSDimitry Andric }
2592cab237bSDimitry Andric 
2602cab237bSDimitry Andric LLVM_DUMP_METHOD
dump() const2612cab237bSDimitry Andric void TypeSetByHwMode::dump() const {
2622cab237bSDimitry Andric   dbgs() << *this << '\n';
2632cab237bSDimitry Andric }
2642cab237bSDimitry Andric 
intersect(SetType & Out,const SetType & In)2652cab237bSDimitry Andric bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
2662cab237bSDimitry Andric   bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
2672cab237bSDimitry Andric   auto Int = [&In](MVT T) -> bool { return !In.count(T); };
2682cab237bSDimitry Andric 
2692cab237bSDimitry Andric   if (OutP == InP)
2702cab237bSDimitry Andric     return berase_if(Out, Int);
2712cab237bSDimitry Andric 
2722cab237bSDimitry Andric   // Compute the intersection of scalars separately to account for only
2732cab237bSDimitry Andric   // one set containing iPTR.
2742cab237bSDimitry Andric   // The itersection of iPTR with a set of integer scalar types that does not
2752cab237bSDimitry Andric   // include iPTR will result in the most specific scalar type:
2762cab237bSDimitry Andric   // - iPTR is more specific than any set with two elements or more
2772cab237bSDimitry Andric   // - iPTR is less specific than any single integer scalar type.
2782cab237bSDimitry Andric   // For example
2792cab237bSDimitry Andric   // { iPTR } * { i32 }     -> { i32 }
2802cab237bSDimitry Andric   // { iPTR } * { i32 i64 } -> { iPTR }
2812cab237bSDimitry Andric   // and
2822cab237bSDimitry Andric   // { iPTR i32 } * { i32 }          -> { i32 }
2832cab237bSDimitry Andric   // { iPTR i32 } * { i32 i64 }      -> { i32 i64 }
2842cab237bSDimitry Andric   // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
2852cab237bSDimitry Andric 
2862cab237bSDimitry Andric   // Compute the difference between the two sets in such a way that the
2872cab237bSDimitry Andric   // iPTR is in the set that is being subtracted. This is to see if there
2882cab237bSDimitry Andric   // are any extra scalars in the set without iPTR that are not in the
2892cab237bSDimitry Andric   // set containing iPTR. Then the iPTR could be considered a "wildcard"
2902cab237bSDimitry Andric   // matching these scalars. If there is only one such scalar, it would
2912cab237bSDimitry Andric   // replace the iPTR, if there are more, the iPTR would be retained.
2922cab237bSDimitry Andric   SetType Diff;
2932cab237bSDimitry Andric   if (InP) {
2942cab237bSDimitry Andric     Diff = Out;
2952cab237bSDimitry Andric     berase_if(Diff, [&In](MVT T) { return In.count(T); });
2962cab237bSDimitry Andric     // Pre-remove these elements and rely only on InP/OutP to determine
2972cab237bSDimitry Andric     // whether a change has been made.
2982cab237bSDimitry Andric     berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
2992cab237bSDimitry Andric   } else {
3002cab237bSDimitry Andric     Diff = In;
3012cab237bSDimitry Andric     berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
3022cab237bSDimitry Andric     Out.erase(MVT::iPTR);
3032cab237bSDimitry Andric   }
3042cab237bSDimitry Andric 
3052cab237bSDimitry Andric   // The actual intersection.
3062cab237bSDimitry Andric   bool Changed = berase_if(Out, Int);
3072cab237bSDimitry Andric   unsigned NumD = Diff.size();
3082cab237bSDimitry Andric   if (NumD == 0)
3092cab237bSDimitry Andric     return Changed;
3102cab237bSDimitry Andric 
3112cab237bSDimitry Andric   if (NumD == 1) {
3122cab237bSDimitry Andric     Out.insert(*Diff.begin());
3132cab237bSDimitry Andric     // This is a change only if Out was the one with iPTR (which is now
3142cab237bSDimitry Andric     // being replaced).
3152cab237bSDimitry Andric     Changed |= OutP;
3162cab237bSDimitry Andric   } else {
3172cab237bSDimitry Andric     // Multiple elements from Out are now replaced with iPTR.
3182cab237bSDimitry Andric     Out.insert(MVT::iPTR);
3192cab237bSDimitry Andric     Changed |= !OutP;
3202cab237bSDimitry Andric   }
3212cab237bSDimitry Andric   return Changed;
3222cab237bSDimitry Andric }
3232cab237bSDimitry Andric 
validate() const324da09e106SDimitry Andric bool TypeSetByHwMode::validate() const {
3252cab237bSDimitry Andric #ifndef NDEBUG
3262cab237bSDimitry Andric   if (empty())
327da09e106SDimitry Andric     return true;
3282cab237bSDimitry Andric   bool AllEmpty = true;
3292cab237bSDimitry Andric   for (const auto &I : *this)
3302cab237bSDimitry Andric     AllEmpty &= I.second.empty();
331da09e106SDimitry Andric   return !AllEmpty;
3322cab237bSDimitry Andric #endif
333da09e106SDimitry Andric   return true;
3342cab237bSDimitry Andric }
3352cab237bSDimitry Andric 
3362cab237bSDimitry Andric // --- TypeInfer
3372cab237bSDimitry Andric 
MergeInTypeInfo(TypeSetByHwMode & Out,const TypeSetByHwMode & In)3382cab237bSDimitry Andric bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
3392cab237bSDimitry Andric                                 const TypeSetByHwMode &In) {
340da09e106SDimitry Andric   ValidateOnExit _1(Out, *this);
3412cab237bSDimitry Andric   In.validate();
3422cab237bSDimitry Andric   if (In.empty() || Out == In || TP.hasError())
3432cab237bSDimitry Andric     return false;
3442cab237bSDimitry Andric   if (Out.empty()) {
3452cab237bSDimitry Andric     Out = In;
3462cab237bSDimitry Andric     return true;
3472cab237bSDimitry Andric   }
3482cab237bSDimitry Andric 
3492cab237bSDimitry Andric   bool Changed = Out.constrain(In);
3502cab237bSDimitry Andric   if (Changed && Out.empty())
3512cab237bSDimitry Andric     TP.error("Type contradiction");
3522cab237bSDimitry Andric 
3532cab237bSDimitry Andric   return Changed;
3542cab237bSDimitry Andric }
3552cab237bSDimitry Andric 
forceArbitrary(TypeSetByHwMode & Out)3562cab237bSDimitry Andric bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
357da09e106SDimitry Andric   ValidateOnExit _1(Out, *this);
3582cab237bSDimitry Andric   if (TP.hasError())
3592cab237bSDimitry Andric     return false;
3602cab237bSDimitry Andric   assert(!Out.empty() && "cannot pick from an empty set");
3612cab237bSDimitry Andric 
3622cab237bSDimitry Andric   bool Changed = false;
3632cab237bSDimitry Andric   for (auto &I : Out) {
3642cab237bSDimitry Andric     TypeSetByHwMode::SetType &S = I.second;
3652cab237bSDimitry Andric     if (S.size() <= 1)
3662cab237bSDimitry Andric       continue;
3672cab237bSDimitry Andric     MVT T = *S.begin(); // Pick the first element.
3682cab237bSDimitry Andric     S.clear();
3692cab237bSDimitry Andric     S.insert(T);
3702cab237bSDimitry Andric     Changed = true;
3712cab237bSDimitry Andric   }
3722cab237bSDimitry Andric   return Changed;
3732cab237bSDimitry Andric }
3742cab237bSDimitry Andric 
EnforceInteger(TypeSetByHwMode & Out)3752cab237bSDimitry Andric bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
376da09e106SDimitry Andric   ValidateOnExit _1(Out, *this);
3772cab237bSDimitry Andric   if (TP.hasError())
3782cab237bSDimitry Andric     return false;
3792cab237bSDimitry Andric   if (!Out.empty())
3802cab237bSDimitry Andric     return Out.constrain(isIntegerOrPtr);
3812cab237bSDimitry Andric 
3822cab237bSDimitry Andric   return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
3832cab237bSDimitry Andric }
3842cab237bSDimitry Andric 
EnforceFloatingPoint(TypeSetByHwMode & Out)3852cab237bSDimitry Andric bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
386da09e106SDimitry Andric   ValidateOnExit _1(Out, *this);
3872cab237bSDimitry Andric   if (TP.hasError())
3882cab237bSDimitry Andric     return false;
3892cab237bSDimitry Andric   if (!Out.empty())
3902cab237bSDimitry Andric     return Out.constrain(isFloatingPoint);
3912cab237bSDimitry Andric 
3922cab237bSDimitry Andric   return Out.assign_if(getLegalTypes(), isFloatingPoint);
3932cab237bSDimitry Andric }
3942cab237bSDimitry Andric 
EnforceScalar(TypeSetByHwMode & Out)3952cab237bSDimitry Andric bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
396da09e106SDimitry Andric   ValidateOnExit _1(Out, *this);
3972cab237bSDimitry Andric   if (TP.hasError())
3982cab237bSDimitry Andric     return false;
3992cab237bSDimitry Andric   if (!Out.empty())
4002cab237bSDimitry Andric     return Out.constrain(isScalar);
4012cab237bSDimitry Andric 
4022cab237bSDimitry Andric   return Out.assign_if(getLegalTypes(), isScalar);
4032cab237bSDimitry Andric }
4042cab237bSDimitry Andric 
EnforceVector(TypeSetByHwMode & Out)4052cab237bSDimitry Andric bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
406da09e106SDimitry Andric   ValidateOnExit _1(Out, *this);
4072cab237bSDimitry Andric   if (TP.hasError())
4082cab237bSDimitry Andric     return false;
4092cab237bSDimitry Andric   if (!Out.empty())
4102cab237bSDimitry Andric     return Out.constrain(isVector);
4112cab237bSDimitry Andric 
4122cab237bSDimitry Andric   return Out.assign_if(getLegalTypes(), isVector);
4132cab237bSDimitry Andric }
4142cab237bSDimitry Andric 
EnforceAny(TypeSetByHwMode & Out)4152cab237bSDimitry Andric bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
416da09e106SDimitry Andric   ValidateOnExit _1(Out, *this);
4172cab237bSDimitry Andric   if (TP.hasError() || !Out.empty())
4182cab237bSDimitry Andric     return false;
4192cab237bSDimitry Andric 
4202cab237bSDimitry Andric   Out = getLegalTypes();
4212cab237bSDimitry Andric   return true;
4222cab237bSDimitry Andric }
4232cab237bSDimitry Andric 
4242cab237bSDimitry Andric template <typename Iter, typename Pred, typename Less>
min_if(Iter B,Iter E,Pred P,Less L)4252cab237bSDimitry Andric static Iter min_if(Iter B, Iter E, Pred P, Less L) {
4262cab237bSDimitry Andric   if (B == E)
4272cab237bSDimitry Andric     return E;
4282cab237bSDimitry Andric   Iter Min = E;
4292cab237bSDimitry Andric   for (Iter I = B; I != E; ++I) {
4302cab237bSDimitry Andric     if (!P(*I))
4312cab237bSDimitry Andric       continue;
4322cab237bSDimitry Andric     if (Min == E || L(*I, *Min))
4332cab237bSDimitry Andric       Min = I;
4342cab237bSDimitry Andric   }
4352cab237bSDimitry Andric   return Min;
4362cab237bSDimitry Andric }
4372cab237bSDimitry Andric 
4382cab237bSDimitry Andric template <typename Iter, typename Pred, typename Less>
max_if(Iter B,Iter E,Pred P,Less L)4392cab237bSDimitry Andric static Iter max_if(Iter B, Iter E, Pred P, Less L) {
4402cab237bSDimitry Andric   if (B == E)
4412cab237bSDimitry Andric     return E;
4422cab237bSDimitry Andric   Iter Max = E;
4432cab237bSDimitry Andric   for (Iter I = B; I != E; ++I) {
4442cab237bSDimitry Andric     if (!P(*I))
4452cab237bSDimitry Andric       continue;
4462cab237bSDimitry Andric     if (Max == E || L(*Max, *I))
4472cab237bSDimitry Andric       Max = I;
4482cab237bSDimitry Andric   }
4492cab237bSDimitry Andric   return Max;
4502cab237bSDimitry Andric }
4512cab237bSDimitry Andric 
4522cab237bSDimitry Andric /// Make sure that for each type in Small, there exists a larger type in Big.
EnforceSmallerThan(TypeSetByHwMode & Small,TypeSetByHwMode & Big)4532cab237bSDimitry Andric bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
4542cab237bSDimitry Andric                                    TypeSetByHwMode &Big) {
455da09e106SDimitry Andric   ValidateOnExit _1(Small, *this), _2(Big, *this);
4562cab237bSDimitry Andric   if (TP.hasError())
4572cab237bSDimitry Andric     return false;
4582cab237bSDimitry Andric   bool Changed = false;
4592cab237bSDimitry Andric 
4602cab237bSDimitry Andric   if (Small.empty())
4612cab237bSDimitry Andric     Changed |= EnforceAny(Small);
4622cab237bSDimitry Andric   if (Big.empty())
4632cab237bSDimitry Andric     Changed |= EnforceAny(Big);
4642cab237bSDimitry Andric 
4652cab237bSDimitry Andric   assert(Small.hasDefault() && Big.hasDefault());
4662cab237bSDimitry Andric 
4672cab237bSDimitry Andric   std::vector<unsigned> Modes = union_modes(Small, Big);
4682cab237bSDimitry Andric 
4692cab237bSDimitry Andric   // 1. Only allow integer or floating point types and make sure that
4702cab237bSDimitry Andric   //    both sides are both integer or both floating point.
4712cab237bSDimitry Andric   // 2. Make sure that either both sides have vector types, or neither
4722cab237bSDimitry Andric   //    of them does.
4732cab237bSDimitry Andric   for (unsigned M : Modes) {
4742cab237bSDimitry Andric     TypeSetByHwMode::SetType &S = Small.get(M);
4752cab237bSDimitry Andric     TypeSetByHwMode::SetType &B = Big.get(M);
4762cab237bSDimitry Andric 
4772cab237bSDimitry Andric     if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
4782cab237bSDimitry Andric       auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
4792cab237bSDimitry Andric       Changed |= berase_if(S, NotInt) |
4802cab237bSDimitry Andric                  berase_if(B, NotInt);
4812cab237bSDimitry Andric     } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
4822cab237bSDimitry Andric       auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
4832cab237bSDimitry Andric       Changed |= berase_if(S, NotFP) |
4842cab237bSDimitry Andric                  berase_if(B, NotFP);
4852cab237bSDimitry Andric     } else if (S.empty() || B.empty()) {
4862cab237bSDimitry Andric       Changed = !S.empty() || !B.empty();
4872cab237bSDimitry Andric       S.clear();
4882cab237bSDimitry Andric       B.clear();
4892cab237bSDimitry Andric     } else {
4902cab237bSDimitry Andric       TP.error("Incompatible types");
4912cab237bSDimitry Andric       return Changed;
4922cab237bSDimitry Andric     }
4932cab237bSDimitry Andric 
4942cab237bSDimitry Andric     if (none_of(S, isVector) || none_of(B, isVector)) {
4952cab237bSDimitry Andric       Changed |= berase_if(S, isVector) |
4962cab237bSDimitry Andric                  berase_if(B, isVector);
4972cab237bSDimitry Andric     }
4982cab237bSDimitry Andric   }
4992cab237bSDimitry Andric 
5002cab237bSDimitry Andric   auto LT = [](MVT A, MVT B) -> bool {
5012cab237bSDimitry Andric     return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
5022cab237bSDimitry Andric            (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
5032cab237bSDimitry Andric             A.getSizeInBits() < B.getSizeInBits());
5042cab237bSDimitry Andric   };
5052cab237bSDimitry Andric   auto LE = [](MVT A, MVT B) -> bool {
5062cab237bSDimitry Andric     // This function is used when removing elements: when a vector is compared
5072cab237bSDimitry Andric     // to a non-vector, it should return false (to avoid removal).
5082cab237bSDimitry Andric     if (A.isVector() != B.isVector())
5092cab237bSDimitry Andric       return false;
5102cab237bSDimitry Andric 
5112cab237bSDimitry Andric     // Note on the < comparison below:
5122cab237bSDimitry Andric     // X86 has patterns like
5132cab237bSDimitry Andric     //   (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
5142cab237bSDimitry Andric     // where the truncated vector is given a type v16i8, while the source
5152cab237bSDimitry Andric     // vector has type v4i32. They both have the same size in bits.
5162cab237bSDimitry Andric     // The minimal type in the result is obviously v16i8, and when we remove
5172cab237bSDimitry Andric     // all types from the source that are smaller-or-equal than v8i16, the
5182cab237bSDimitry Andric     // only source type would also be removed (since it's equal in size).
5192cab237bSDimitry Andric     return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
5202cab237bSDimitry Andric            A.getSizeInBits() < B.getSizeInBits();
5212cab237bSDimitry Andric   };
5222cab237bSDimitry Andric 
5232cab237bSDimitry Andric   for (unsigned M : Modes) {
5242cab237bSDimitry Andric     TypeSetByHwMode::SetType &S = Small.get(M);
5252cab237bSDimitry Andric     TypeSetByHwMode::SetType &B = Big.get(M);
5262cab237bSDimitry Andric     // MinS = min scalar in Small, remove all scalars from Big that are
5272cab237bSDimitry Andric     // smaller-or-equal than MinS.
5282cab237bSDimitry Andric     auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
5292cab237bSDimitry Andric     if (MinS != S.end())
5302cab237bSDimitry Andric       Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
5312cab237bSDimitry Andric 
5322cab237bSDimitry Andric     // MaxS = max scalar in Big, remove all scalars from Small that are
5332cab237bSDimitry Andric     // larger than MaxS.
5342cab237bSDimitry Andric     auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
5352cab237bSDimitry Andric     if (MaxS != B.end())
5362cab237bSDimitry Andric       Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
5372cab237bSDimitry Andric 
5382cab237bSDimitry Andric     // MinV = min vector in Small, remove all vectors from Big that are
5392cab237bSDimitry Andric     // smaller-or-equal than MinV.
5402cab237bSDimitry Andric     auto MinV = min_if(S.begin(), S.end(), isVector, LT);
5412cab237bSDimitry Andric     if (MinV != S.end())
5422cab237bSDimitry Andric       Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
5432cab237bSDimitry Andric 
5442cab237bSDimitry Andric     // MaxV = max vector in Big, remove all vectors from Small that are
5452cab237bSDimitry Andric     // larger than MaxV.
5462cab237bSDimitry Andric     auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
5472cab237bSDimitry Andric     if (MaxV != B.end())
5482cab237bSDimitry Andric       Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
5492cab237bSDimitry Andric   }
5502cab237bSDimitry Andric 
5512cab237bSDimitry Andric   return Changed;
5522cab237bSDimitry Andric }
5532cab237bSDimitry Andric 
5542cab237bSDimitry Andric /// 1. Ensure that for each type T in Vec, T is a vector type, and that
5552cab237bSDimitry Andric ///    for each type U in Elem, U is a scalar type.
5562cab237bSDimitry Andric /// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
5572cab237bSDimitry Andric ///    type T in Vec, such that U is the element type of T.
EnforceVectorEltTypeIs(TypeSetByHwMode & Vec,TypeSetByHwMode & Elem)5582cab237bSDimitry Andric bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
5592cab237bSDimitry Andric                                        TypeSetByHwMode &Elem) {
560da09e106SDimitry Andric   ValidateOnExit _1(Vec, *this), _2(Elem, *this);
5612cab237bSDimitry Andric   if (TP.hasError())
5622cab237bSDimitry Andric     return false;
5632cab237bSDimitry Andric   bool Changed = false;
5642cab237bSDimitry Andric 
5652cab237bSDimitry Andric   if (Vec.empty())
5662cab237bSDimitry Andric     Changed |= EnforceVector(Vec);
5672cab237bSDimitry Andric   if (Elem.empty())
5682cab237bSDimitry Andric     Changed |= EnforceScalar(Elem);
5692cab237bSDimitry Andric 
5702cab237bSDimitry Andric   for (unsigned M : union_modes(Vec, Elem)) {
5712cab237bSDimitry Andric     TypeSetByHwMode::SetType &V = Vec.get(M);
5722cab237bSDimitry Andric     TypeSetByHwMode::SetType &E = Elem.get(M);
5732cab237bSDimitry Andric 
5742cab237bSDimitry Andric     Changed |= berase_if(V, isScalar);  // Scalar = !vector
5752cab237bSDimitry Andric     Changed |= berase_if(E, isVector);  // Vector = !scalar
5762cab237bSDimitry Andric     assert(!V.empty() && !E.empty());
5772cab237bSDimitry Andric 
5782cab237bSDimitry Andric     SmallSet<MVT,4> VT, ST;
5792cab237bSDimitry Andric     // Collect element types from the "vector" set.
5802cab237bSDimitry Andric     for (MVT T : V)
5812cab237bSDimitry Andric       VT.insert(T.getVectorElementType());
5822cab237bSDimitry Andric     // Collect scalar types from the "element" set.
5832cab237bSDimitry Andric     for (MVT T : E)
5842cab237bSDimitry Andric       ST.insert(T);
5852cab237bSDimitry Andric 
5862cab237bSDimitry Andric     // Remove from V all (vector) types whose element type is not in S.
5872cab237bSDimitry Andric     Changed |= berase_if(V, [&ST](MVT T) -> bool {
5882cab237bSDimitry Andric                               return !ST.count(T.getVectorElementType());
5892cab237bSDimitry Andric                             });
5902cab237bSDimitry Andric     // Remove from E all (scalar) types, for which there is no corresponding
5912cab237bSDimitry Andric     // type in V.
5922cab237bSDimitry Andric     Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
5932cab237bSDimitry Andric   }
5942cab237bSDimitry Andric 
5952cab237bSDimitry Andric   return Changed;
5962cab237bSDimitry Andric }
5972cab237bSDimitry Andric 
EnforceVectorEltTypeIs(TypeSetByHwMode & Vec,const ValueTypeByHwMode & VVT)5982cab237bSDimitry Andric bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
5992cab237bSDimitry Andric                                        const ValueTypeByHwMode &VVT) {
6002cab237bSDimitry Andric   TypeSetByHwMode Tmp(VVT);
601da09e106SDimitry Andric   ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
6022cab237bSDimitry Andric   return EnforceVectorEltTypeIs(Vec, Tmp);
6032cab237bSDimitry Andric }
6042cab237bSDimitry Andric 
6052cab237bSDimitry Andric /// Ensure that for each type T in Sub, T is a vector type, and there
6062cab237bSDimitry Andric /// exists a type U in Vec such that U is a vector type with the same
6072cab237bSDimitry Andric /// element type as T and at least as many elements as T.
EnforceVectorSubVectorTypeIs(TypeSetByHwMode & Vec,TypeSetByHwMode & Sub)6082cab237bSDimitry Andric bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
6092cab237bSDimitry Andric                                              TypeSetByHwMode &Sub) {
610da09e106SDimitry Andric   ValidateOnExit _1(Vec, *this), _2(Sub, *this);
6113861d79fSDimitry Andric   if (TP.hasError())
6123861d79fSDimitry Andric     return false;
6133861d79fSDimitry Andric 
6142cab237bSDimitry Andric   /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
6152cab237bSDimitry Andric   auto IsSubVec = [](MVT B, MVT P) -> bool {
6162cab237bSDimitry Andric     if (!B.isVector() || !P.isVector())
6173861d79fSDimitry Andric       return false;
6182cab237bSDimitry Andric     // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
6192cab237bSDimitry Andric     // but until there are obvious use-cases for this, keep the
6202cab237bSDimitry Andric     // types separate.
6212cab237bSDimitry Andric     if (B.isScalableVector() != P.isScalableVector())
6222cab237bSDimitry Andric       return false;
6232cab237bSDimitry Andric     if (B.getVectorElementType() != P.getVectorElementType())
6242cab237bSDimitry Andric       return false;
6252cab237bSDimitry Andric     return B.getVectorNumElements() < P.getVectorNumElements();
6262cab237bSDimitry Andric   };
627f22ef01cSRoman Divacky 
6282cab237bSDimitry Andric   /// Return true if S has no element (vector type) that T is a sub-vector of,
6292cab237bSDimitry Andric   /// i.e. has the same element type as T and more elements.
6302cab237bSDimitry Andric   auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
6312cab237bSDimitry Andric     for (const auto &I : S)
6322cab237bSDimitry Andric       if (IsSubVec(T, I))
6332cab237bSDimitry Andric         return false;
634f22ef01cSRoman Divacky     return true;
6352cab237bSDimitry Andric   };
6362cab237bSDimitry Andric 
6372cab237bSDimitry Andric   /// Return true if S has no element (vector type) that T is a super-vector
6382cab237bSDimitry Andric   /// of, i.e. has the same element type as T and fewer elements.
6392cab237bSDimitry Andric   auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
6402cab237bSDimitry Andric     for (const auto &I : S)
6412cab237bSDimitry Andric       if (IsSubVec(I, T))
6422cab237bSDimitry Andric         return false;
6432cab237bSDimitry Andric     return true;
6442cab237bSDimitry Andric   };
6452cab237bSDimitry Andric 
6462cab237bSDimitry Andric   bool Changed = false;
6472cab237bSDimitry Andric 
6482cab237bSDimitry Andric   if (Vec.empty())
6492cab237bSDimitry Andric     Changed |= EnforceVector(Vec);
6502cab237bSDimitry Andric   if (Sub.empty())
6512cab237bSDimitry Andric     Changed |= EnforceVector(Sub);
6522cab237bSDimitry Andric 
6532cab237bSDimitry Andric   for (unsigned M : union_modes(Vec, Sub)) {
6542cab237bSDimitry Andric     TypeSetByHwMode::SetType &S = Sub.get(M);
6552cab237bSDimitry Andric     TypeSetByHwMode::SetType &V = Vec.get(M);
6562cab237bSDimitry Andric 
6572cab237bSDimitry Andric     Changed |= berase_if(S, isScalar);
6582cab237bSDimitry Andric 
6592cab237bSDimitry Andric     // Erase all types from S that are not sub-vectors of a type in V.
6602cab237bSDimitry Andric     Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
6612cab237bSDimitry Andric 
6622cab237bSDimitry Andric     // Erase all types from V that are not super-vectors of a type in S.
6632cab237bSDimitry Andric     Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
664f22ef01cSRoman Divacky   }
665f22ef01cSRoman Divacky 
6662cab237bSDimitry Andric   return Changed;
667f22ef01cSRoman Divacky }
668f22ef01cSRoman Divacky 
6692cab237bSDimitry Andric /// 1. Ensure that V has a scalar type iff W has a scalar type.
6702cab237bSDimitry Andric /// 2. Ensure that for each vector type T in V, there exists a vector
6712cab237bSDimitry Andric ///    type U in W, such that T and U have the same number of elements.
6722cab237bSDimitry Andric /// 3. Ensure that for each vector type U in W, there exists a vector
6732cab237bSDimitry Andric ///    type T in V, such that T and U have the same number of elements
6742cab237bSDimitry Andric ///    (reverse of 2).
EnforceSameNumElts(TypeSetByHwMode & V,TypeSetByHwMode & W)6752cab237bSDimitry Andric bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
676da09e106SDimitry Andric   ValidateOnExit _1(V, *this), _2(W, *this);
6772cab237bSDimitry Andric   if (TP.hasError())
678f22ef01cSRoman Divacky     return false;
679f22ef01cSRoman Divacky 
6802cab237bSDimitry Andric   bool Changed = false;
6812cab237bSDimitry Andric   if (V.empty())
6822cab237bSDimitry Andric     Changed |= EnforceAny(V);
6832cab237bSDimitry Andric   if (W.empty())
6842cab237bSDimitry Andric     Changed |= EnforceAny(W);
6852cab237bSDimitry Andric 
6862cab237bSDimitry Andric   // An actual vector type cannot have 0 elements, so we can treat scalars
6872cab237bSDimitry Andric   // as zero-length vectors. This way both vectors and scalars can be
6882cab237bSDimitry Andric   // processed identically.
6892cab237bSDimitry Andric   auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
6902cab237bSDimitry Andric     return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
6912cab237bSDimitry Andric   };
6922cab237bSDimitry Andric 
6932cab237bSDimitry Andric   for (unsigned M : union_modes(V, W)) {
6942cab237bSDimitry Andric     TypeSetByHwMode::SetType &VS = V.get(M);
6952cab237bSDimitry Andric     TypeSetByHwMode::SetType &WS = W.get(M);
6962cab237bSDimitry Andric 
6972cab237bSDimitry Andric     SmallSet<unsigned,2> VN, WN;
6982cab237bSDimitry Andric     for (MVT T : VS)
6992cab237bSDimitry Andric       VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
7002cab237bSDimitry Andric     for (MVT T : WS)
7012cab237bSDimitry Andric       WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
7022cab237bSDimitry Andric 
7032cab237bSDimitry Andric     Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
7042cab237bSDimitry Andric     Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
7052cab237bSDimitry Andric   }
7062cab237bSDimitry Andric   return Changed;
707f22ef01cSRoman Divacky }
708f22ef01cSRoman Divacky 
7092cab237bSDimitry Andric /// 1. Ensure that for each type T in A, there exists a type U in B,
7102cab237bSDimitry Andric ///    such that T and U have equal size in bits.
7112cab237bSDimitry Andric /// 2. Ensure that for each type U in B, there exists a type T in A
7122cab237bSDimitry Andric ///    such that T and U have equal size in bits (reverse of 1).
EnforceSameSize(TypeSetByHwMode & A,TypeSetByHwMode & B)7132cab237bSDimitry Andric bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
714da09e106SDimitry Andric   ValidateOnExit _1(A, *this), _2(B, *this);
7152cab237bSDimitry Andric   if (TP.hasError())
7162cab237bSDimitry Andric     return false;
7172cab237bSDimitry Andric   bool Changed = false;
7182cab237bSDimitry Andric   if (A.empty())
7192cab237bSDimitry Andric     Changed |= EnforceAny(A);
7202cab237bSDimitry Andric   if (B.empty())
7212cab237bSDimitry Andric     Changed |= EnforceAny(B);
722f22ef01cSRoman Divacky 
7232cab237bSDimitry Andric   auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
7242cab237bSDimitry Andric     return !Sizes.count(T.getSizeInBits());
7252cab237bSDimitry Andric   };
7262cab237bSDimitry Andric 
7272cab237bSDimitry Andric   for (unsigned M : union_modes(A, B)) {
7282cab237bSDimitry Andric     TypeSetByHwMode::SetType &AS = A.get(M);
7292cab237bSDimitry Andric     TypeSetByHwMode::SetType &BS = B.get(M);
7302cab237bSDimitry Andric     SmallSet<unsigned,2> AN, BN;
7312cab237bSDimitry Andric 
7322cab237bSDimitry Andric     for (MVT T : AS)
7332cab237bSDimitry Andric       AN.insert(T.getSizeInBits());
7342cab237bSDimitry Andric     for (MVT T : BS)
7352cab237bSDimitry Andric       BN.insert(T.getSizeInBits());
7362cab237bSDimitry Andric 
7372cab237bSDimitry Andric     Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
7382cab237bSDimitry Andric     Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
7392cab237bSDimitry Andric   }
7402cab237bSDimitry Andric 
7412cab237bSDimitry Andric   return Changed;
7422cab237bSDimitry Andric }
7432cab237bSDimitry Andric 
expandOverloads(TypeSetByHwMode & VTS)7442cab237bSDimitry Andric void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
745da09e106SDimitry Andric   ValidateOnExit _1(VTS, *this);
746*b5893f02SDimitry Andric   const TypeSetByHwMode &Legal = getLegalTypes();
747*b5893f02SDimitry Andric   assert(Legal.isDefaultOnly() && "Default-mode only expected");
748*b5893f02SDimitry Andric   const TypeSetByHwMode::SetType &LegalTypes = Legal.get(DefaultMode);
7492cab237bSDimitry Andric 
750*b5893f02SDimitry Andric   for (auto &I : VTS)
751*b5893f02SDimitry Andric     expandOverloads(I.second, LegalTypes);
7522cab237bSDimitry Andric }
7532cab237bSDimitry Andric 
expandOverloads(TypeSetByHwMode::SetType & Out,const TypeSetByHwMode::SetType & Legal)7542cab237bSDimitry Andric void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
7552cab237bSDimitry Andric                                 const TypeSetByHwMode::SetType &Legal) {
7562cab237bSDimitry Andric   std::set<MVT> Ovs;
7572cab237bSDimitry Andric   for (MVT T : Out) {
7582cab237bSDimitry Andric     if (!T.isOverloaded())
7592cab237bSDimitry Andric       continue;
7602cab237bSDimitry Andric 
7612cab237bSDimitry Andric     Ovs.insert(T);
7622cab237bSDimitry Andric     // MachineValueTypeSet allows iteration and erasing.
7632cab237bSDimitry Andric     Out.erase(T);
7642cab237bSDimitry Andric   }
7652cab237bSDimitry Andric 
7662cab237bSDimitry Andric   for (MVT Ov : Ovs) {
7672cab237bSDimitry Andric     switch (Ov.SimpleTy) {
768f22ef01cSRoman Divacky       case MVT::iPTRAny:
7692cab237bSDimitry Andric         Out.insert(MVT::iPTR);
7702cab237bSDimitry Andric         return;
7712cab237bSDimitry Andric       case MVT::iAny:
7722cab237bSDimitry Andric         for (MVT T : MVT::integer_valuetypes())
7732cab237bSDimitry Andric           if (Legal.count(T))
7742cab237bSDimitry Andric             Out.insert(T);
7752cab237bSDimitry Andric         for (MVT T : MVT::integer_vector_valuetypes())
7762cab237bSDimitry Andric           if (Legal.count(T))
7772cab237bSDimitry Andric             Out.insert(T);
7782cab237bSDimitry Andric         return;
7792cab237bSDimitry Andric       case MVT::fAny:
7802cab237bSDimitry Andric         for (MVT T : MVT::fp_valuetypes())
7812cab237bSDimitry Andric           if (Legal.count(T))
7822cab237bSDimitry Andric             Out.insert(T);
7832cab237bSDimitry Andric         for (MVT T : MVT::fp_vector_valuetypes())
7842cab237bSDimitry Andric           if (Legal.count(T))
7852cab237bSDimitry Andric             Out.insert(T);
7862cab237bSDimitry Andric         return;
7872cab237bSDimitry Andric       case MVT::vAny:
7882cab237bSDimitry Andric         for (MVT T : MVT::vector_valuetypes())
7892cab237bSDimitry Andric           if (Legal.count(T))
7902cab237bSDimitry Andric             Out.insert(T);
7912cab237bSDimitry Andric         return;
7922cab237bSDimitry Andric       case MVT::Any:
7932cab237bSDimitry Andric         for (MVT T : MVT::all_valuetypes())
7942cab237bSDimitry Andric           if (Legal.count(T))
7952cab237bSDimitry Andric             Out.insert(T);
7962cab237bSDimitry Andric         return;
7972cab237bSDimitry Andric       default:
798f22ef01cSRoman Divacky         break;
799f22ef01cSRoman Divacky     }
8003861d79fSDimitry Andric   }
8017d523365SDimitry Andric }
802f22ef01cSRoman Divacky 
getLegalTypes()803*b5893f02SDimitry Andric const TypeSetByHwMode &TypeInfer::getLegalTypes() {
8042cab237bSDimitry Andric   if (!LegalTypesCached) {
805*b5893f02SDimitry Andric     TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
8062cab237bSDimitry Andric     // Stuff all types from all modes into the default mode.
8072cab237bSDimitry Andric     const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
8082cab237bSDimitry Andric     for (const auto &I : LTS)
809*b5893f02SDimitry Andric       LegalTypes.insert(I.second);
8102cab237bSDimitry Andric     LegalTypesCached = true;
8113861d79fSDimitry Andric   }
812*b5893f02SDimitry Andric   assert(LegalCache.isDefaultOnly() && "Default-mode only expected");
813*b5893f02SDimitry Andric   return LegalCache;
8147d523365SDimitry Andric }
815f22ef01cSRoman Divacky 
816da09e106SDimitry Andric #ifndef NDEBUG
~ValidateOnExit()817da09e106SDimitry Andric TypeInfer::ValidateOnExit::~ValidateOnExit() {
8184ba319b5SDimitry Andric   if (Infer.Validate && !VTS.validate()) {
819da09e106SDimitry Andric     dbgs() << "Type set is empty for each HW mode:\n"
820da09e106SDimitry Andric               "possible type contradiction in the pattern below "
821da09e106SDimitry Andric               "(use -print-records with llvm-tblgen to see all "
822da09e106SDimitry Andric               "expanded records).\n";
823da09e106SDimitry Andric     Infer.TP.dump();
824da09e106SDimitry Andric     llvm_unreachable(nullptr);
825da09e106SDimitry Andric   }
826da09e106SDimitry Andric }
827da09e106SDimitry Andric #endif
828da09e106SDimitry Andric 
829*b5893f02SDimitry Andric 
830*b5893f02SDimitry Andric //===----------------------------------------------------------------------===//
831*b5893f02SDimitry Andric // ScopedName Implementation
832*b5893f02SDimitry Andric //===----------------------------------------------------------------------===//
833*b5893f02SDimitry Andric 
operator ==(const ScopedName & o) const834*b5893f02SDimitry Andric bool ScopedName::operator==(const ScopedName &o) const {
835*b5893f02SDimitry Andric   return Scope == o.Scope && Identifier == o.Identifier;
836*b5893f02SDimitry Andric }
837*b5893f02SDimitry Andric 
operator !=(const ScopedName & o) const838*b5893f02SDimitry Andric bool ScopedName::operator!=(const ScopedName &o) const {
839*b5893f02SDimitry Andric   return !(*this == o);
840*b5893f02SDimitry Andric }
841*b5893f02SDimitry Andric 
842*b5893f02SDimitry Andric 
8433b0f4066SDimitry Andric //===----------------------------------------------------------------------===//
8443b0f4066SDimitry Andric // TreePredicateFn Implementation
8453b0f4066SDimitry Andric //===----------------------------------------------------------------------===//
8463b0f4066SDimitry Andric 
8473b0f4066SDimitry Andric /// TreePredicateFn constructor.  Here 'N' is a subclass of PatFrag.
TreePredicateFn(TreePattern * N)8483b0f4066SDimitry Andric TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
8492cab237bSDimitry Andric   assert(
8502cab237bSDimitry Andric       (!hasPredCode() || !hasImmCode()) &&
8513b0f4066SDimitry Andric       ".td file corrupt: can't have a node predicate *and* an imm predicate");
8523b0f4066SDimitry Andric }
8533b0f4066SDimitry Andric 
hasPredCode() const8542cab237bSDimitry Andric bool TreePredicateFn::hasPredCode() const {
8552cab237bSDimitry Andric   return isLoad() || isStore() || isAtomic() ||
8562cab237bSDimitry Andric          !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
8572cab237bSDimitry Andric }
8582cab237bSDimitry Andric 
getPredCode() const8593b0f4066SDimitry Andric std::string TreePredicateFn::getPredCode() const {
8602cab237bSDimitry Andric   std::string Code = "";
8612cab237bSDimitry Andric 
8622cab237bSDimitry Andric   if (!isLoad() && !isStore() && !isAtomic()) {
8632cab237bSDimitry Andric     Record *MemoryVT = getMemoryVT();
8642cab237bSDimitry Andric 
8652cab237bSDimitry Andric     if (MemoryVT)
8662cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
8672cab237bSDimitry Andric                       "MemoryVT requires IsLoad or IsStore");
8682cab237bSDimitry Andric   }
8692cab237bSDimitry Andric 
8702cab237bSDimitry Andric   if (!isLoad() && !isStore()) {
8712cab237bSDimitry Andric     if (isUnindexed())
8722cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
8732cab237bSDimitry Andric                       "IsUnindexed requires IsLoad or IsStore");
8742cab237bSDimitry Andric 
8752cab237bSDimitry Andric     Record *ScalarMemoryVT = getScalarMemoryVT();
8762cab237bSDimitry Andric 
8772cab237bSDimitry Andric     if (ScalarMemoryVT)
8782cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
8792cab237bSDimitry Andric                       "ScalarMemoryVT requires IsLoad or IsStore");
8802cab237bSDimitry Andric   }
8812cab237bSDimitry Andric 
8822cab237bSDimitry Andric   if (isLoad() + isStore() + isAtomic() > 1)
8832cab237bSDimitry Andric     PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
8842cab237bSDimitry Andric                     "IsLoad, IsStore, and IsAtomic are mutually exclusive");
8852cab237bSDimitry Andric 
8862cab237bSDimitry Andric   if (isLoad()) {
8872cab237bSDimitry Andric     if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
8882cab237bSDimitry Andric         !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
8892cab237bSDimitry Andric         getScalarMemoryVT() == nullptr)
8902cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
8912cab237bSDimitry Andric                       "IsLoad cannot be used by itself");
8922cab237bSDimitry Andric   } else {
8932cab237bSDimitry Andric     if (isNonExtLoad())
8942cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
8952cab237bSDimitry Andric                       "IsNonExtLoad requires IsLoad");
8962cab237bSDimitry Andric     if (isAnyExtLoad())
8972cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
8982cab237bSDimitry Andric                       "IsAnyExtLoad requires IsLoad");
8992cab237bSDimitry Andric     if (isSignExtLoad())
9002cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9012cab237bSDimitry Andric                       "IsSignExtLoad requires IsLoad");
9022cab237bSDimitry Andric     if (isZeroExtLoad())
9032cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9042cab237bSDimitry Andric                       "IsZeroExtLoad requires IsLoad");
9052cab237bSDimitry Andric   }
9062cab237bSDimitry Andric 
9072cab237bSDimitry Andric   if (isStore()) {
9082cab237bSDimitry Andric     if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
9092cab237bSDimitry Andric         getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
9102cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9112cab237bSDimitry Andric                       "IsStore cannot be used by itself");
9122cab237bSDimitry Andric   } else {
9132cab237bSDimitry Andric     if (isNonTruncStore())
9142cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9152cab237bSDimitry Andric                       "IsNonTruncStore requires IsStore");
9162cab237bSDimitry Andric     if (isTruncStore())
9172cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9182cab237bSDimitry Andric                       "IsTruncStore requires IsStore");
9192cab237bSDimitry Andric   }
9202cab237bSDimitry Andric 
9212cab237bSDimitry Andric   if (isAtomic()) {
9222cab237bSDimitry Andric     if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
9232cab237bSDimitry Andric         !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
9242cab237bSDimitry Andric         !isAtomicOrderingAcquireRelease() &&
9252cab237bSDimitry Andric         !isAtomicOrderingSequentiallyConsistent() &&
9262cab237bSDimitry Andric         !isAtomicOrderingAcquireOrStronger() &&
9272cab237bSDimitry Andric         !isAtomicOrderingReleaseOrStronger() &&
9282cab237bSDimitry Andric         !isAtomicOrderingWeakerThanAcquire() &&
9292cab237bSDimitry Andric         !isAtomicOrderingWeakerThanRelease())
9302cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9312cab237bSDimitry Andric                       "IsAtomic cannot be used by itself");
9322cab237bSDimitry Andric   } else {
9332cab237bSDimitry Andric     if (isAtomicOrderingMonotonic())
9342cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9352cab237bSDimitry Andric                       "IsAtomicOrderingMonotonic requires IsAtomic");
9362cab237bSDimitry Andric     if (isAtomicOrderingAcquire())
9372cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9382cab237bSDimitry Andric                       "IsAtomicOrderingAcquire requires IsAtomic");
9392cab237bSDimitry Andric     if (isAtomicOrderingRelease())
9402cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9412cab237bSDimitry Andric                       "IsAtomicOrderingRelease requires IsAtomic");
9422cab237bSDimitry Andric     if (isAtomicOrderingAcquireRelease())
9432cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9442cab237bSDimitry Andric                       "IsAtomicOrderingAcquireRelease requires IsAtomic");
9452cab237bSDimitry Andric     if (isAtomicOrderingSequentiallyConsistent())
9462cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9472cab237bSDimitry Andric                       "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
9482cab237bSDimitry Andric     if (isAtomicOrderingAcquireOrStronger())
9492cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9502cab237bSDimitry Andric                       "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
9512cab237bSDimitry Andric     if (isAtomicOrderingReleaseOrStronger())
9522cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9532cab237bSDimitry Andric                       "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
9542cab237bSDimitry Andric     if (isAtomicOrderingWeakerThanAcquire())
9552cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9562cab237bSDimitry Andric                       "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
9572cab237bSDimitry Andric   }
9582cab237bSDimitry Andric 
9592cab237bSDimitry Andric   if (isLoad() || isStore() || isAtomic()) {
9602cab237bSDimitry Andric     StringRef SDNodeName =
9612cab237bSDimitry Andric         isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
9622cab237bSDimitry Andric 
9632cab237bSDimitry Andric     Record *MemoryVT = getMemoryVT();
9642cab237bSDimitry Andric 
9652cab237bSDimitry Andric     if (MemoryVT)
9662cab237bSDimitry Andric       Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
9672cab237bSDimitry Andric                MemoryVT->getName() + ") return false;\n")
9682cab237bSDimitry Andric                   .str();
9692cab237bSDimitry Andric   }
9702cab237bSDimitry Andric 
9712cab237bSDimitry Andric   if (isAtomic() && isAtomicOrderingMonotonic())
9722cab237bSDimitry Andric     Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
9732cab237bSDimitry Andric             "AtomicOrdering::Monotonic) return false;\n";
9742cab237bSDimitry Andric   if (isAtomic() && isAtomicOrderingAcquire())
9752cab237bSDimitry Andric     Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
9762cab237bSDimitry Andric             "AtomicOrdering::Acquire) return false;\n";
9772cab237bSDimitry Andric   if (isAtomic() && isAtomicOrderingRelease())
9782cab237bSDimitry Andric     Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
9792cab237bSDimitry Andric             "AtomicOrdering::Release) return false;\n";
9802cab237bSDimitry Andric   if (isAtomic() && isAtomicOrderingAcquireRelease())
9812cab237bSDimitry Andric     Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
9822cab237bSDimitry Andric             "AtomicOrdering::AcquireRelease) return false;\n";
9832cab237bSDimitry Andric   if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
9842cab237bSDimitry Andric     Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
9852cab237bSDimitry Andric             "AtomicOrdering::SequentiallyConsistent) return false;\n";
9862cab237bSDimitry Andric 
9872cab237bSDimitry Andric   if (isAtomic() && isAtomicOrderingAcquireOrStronger())
9882cab237bSDimitry Andric     Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
9892cab237bSDimitry Andric             "return false;\n";
9902cab237bSDimitry Andric   if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
9912cab237bSDimitry Andric     Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
9922cab237bSDimitry Andric             "return false;\n";
9932cab237bSDimitry Andric 
9942cab237bSDimitry Andric   if (isAtomic() && isAtomicOrderingReleaseOrStronger())
9952cab237bSDimitry Andric     Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
9962cab237bSDimitry Andric             "return false;\n";
9972cab237bSDimitry Andric   if (isAtomic() && isAtomicOrderingWeakerThanRelease())
9982cab237bSDimitry Andric     Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
9992cab237bSDimitry Andric             "return false;\n";
10002cab237bSDimitry Andric 
10012cab237bSDimitry Andric   if (isLoad() || isStore()) {
10022cab237bSDimitry Andric     StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
10032cab237bSDimitry Andric 
10042cab237bSDimitry Andric     if (isUnindexed())
10052cab237bSDimitry Andric       Code += ("if (cast<" + SDNodeName +
10062cab237bSDimitry Andric                ">(N)->getAddressingMode() != ISD::UNINDEXED) "
10072cab237bSDimitry Andric                "return false;\n")
10082cab237bSDimitry Andric                   .str();
10092cab237bSDimitry Andric 
10102cab237bSDimitry Andric     if (isLoad()) {
10112cab237bSDimitry Andric       if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
10122cab237bSDimitry Andric            isZeroExtLoad()) > 1)
10132cab237bSDimitry Andric         PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
10142cab237bSDimitry Andric                         "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
10152cab237bSDimitry Andric                         "IsZeroExtLoad are mutually exclusive");
10162cab237bSDimitry Andric       if (isNonExtLoad())
10172cab237bSDimitry Andric         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
10182cab237bSDimitry Andric                 "ISD::NON_EXTLOAD) return false;\n";
10192cab237bSDimitry Andric       if (isAnyExtLoad())
10202cab237bSDimitry Andric         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
10212cab237bSDimitry Andric                 "return false;\n";
10222cab237bSDimitry Andric       if (isSignExtLoad())
10232cab237bSDimitry Andric         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
10242cab237bSDimitry Andric                 "return false;\n";
10252cab237bSDimitry Andric       if (isZeroExtLoad())
10262cab237bSDimitry Andric         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
10272cab237bSDimitry Andric                 "return false;\n";
10282cab237bSDimitry Andric     } else {
10292cab237bSDimitry Andric       if ((isNonTruncStore() + isTruncStore()) > 1)
10302cab237bSDimitry Andric         PrintFatalError(
10312cab237bSDimitry Andric             getOrigPatFragRecord()->getRecord()->getLoc(),
10322cab237bSDimitry Andric             "IsNonTruncStore, and IsTruncStore are mutually exclusive");
10332cab237bSDimitry Andric       if (isNonTruncStore())
10342cab237bSDimitry Andric         Code +=
10352cab237bSDimitry Andric             " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
10362cab237bSDimitry Andric       if (isTruncStore())
10372cab237bSDimitry Andric         Code +=
10382cab237bSDimitry Andric             " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
10392cab237bSDimitry Andric     }
10402cab237bSDimitry Andric 
10412cab237bSDimitry Andric     Record *ScalarMemoryVT = getScalarMemoryVT();
10422cab237bSDimitry Andric 
10432cab237bSDimitry Andric     if (ScalarMemoryVT)
10442cab237bSDimitry Andric       Code += ("if (cast<" + SDNodeName +
10452cab237bSDimitry Andric                ">(N)->getMemoryVT().getScalarType() != MVT::" +
10462cab237bSDimitry Andric                ScalarMemoryVT->getName() + ") return false;\n")
10472cab237bSDimitry Andric                   .str();
10482cab237bSDimitry Andric   }
10492cab237bSDimitry Andric 
10502cab237bSDimitry Andric   std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
10512cab237bSDimitry Andric 
10522cab237bSDimitry Andric   Code += PredicateCode;
10532cab237bSDimitry Andric 
10542cab237bSDimitry Andric   if (PredicateCode.empty() && !Code.empty())
10552cab237bSDimitry Andric     Code += "return true;\n";
10562cab237bSDimitry Andric 
10572cab237bSDimitry Andric   return Code;
10582cab237bSDimitry Andric }
10592cab237bSDimitry Andric 
hasImmCode() const10602cab237bSDimitry Andric bool TreePredicateFn::hasImmCode() const {
10612cab237bSDimitry Andric   return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
10623b0f4066SDimitry Andric }
10633b0f4066SDimitry Andric 
getImmCode() const10643b0f4066SDimitry Andric std::string TreePredicateFn::getImmCode() const {
1065dff0c46cSDimitry Andric   return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
10663b0f4066SDimitry Andric }
10673b0f4066SDimitry Andric 
immCodeUsesAPInt() const10682cab237bSDimitry Andric bool TreePredicateFn::immCodeUsesAPInt() const {
10692cab237bSDimitry Andric   return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
10702cab237bSDimitry Andric }
10712cab237bSDimitry Andric 
immCodeUsesAPFloat() const10722cab237bSDimitry Andric bool TreePredicateFn::immCodeUsesAPFloat() const {
10732cab237bSDimitry Andric   bool Unset;
10742cab237bSDimitry Andric   // The return value will be false when IsAPFloat is unset.
10752cab237bSDimitry Andric   return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
10762cab237bSDimitry Andric                                                                    Unset);
10772cab237bSDimitry Andric }
10782cab237bSDimitry Andric 
isPredefinedPredicateEqualTo(StringRef Field,bool Value) const10792cab237bSDimitry Andric bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
10802cab237bSDimitry Andric                                                    bool Value) const {
10812cab237bSDimitry Andric   bool Unset;
10822cab237bSDimitry Andric   bool Result =
10832cab237bSDimitry Andric       getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
10842cab237bSDimitry Andric   if (Unset)
10852cab237bSDimitry Andric     return false;
10862cab237bSDimitry Andric   return Result == Value;
10872cab237bSDimitry Andric }
usesOperands() const1088*b5893f02SDimitry Andric bool TreePredicateFn::usesOperands() const {
1089*b5893f02SDimitry Andric   return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1090*b5893f02SDimitry Andric }
isLoad() const10912cab237bSDimitry Andric bool TreePredicateFn::isLoad() const {
10922cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsLoad", true);
10932cab237bSDimitry Andric }
isStore() const10942cab237bSDimitry Andric bool TreePredicateFn::isStore() const {
10952cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsStore", true);
10962cab237bSDimitry Andric }
isAtomic() const10972cab237bSDimitry Andric bool TreePredicateFn::isAtomic() const {
10982cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomic", true);
10992cab237bSDimitry Andric }
isUnindexed() const11002cab237bSDimitry Andric bool TreePredicateFn::isUnindexed() const {
11012cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsUnindexed", true);
11022cab237bSDimitry Andric }
isNonExtLoad() const11032cab237bSDimitry Andric bool TreePredicateFn::isNonExtLoad() const {
11042cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
11052cab237bSDimitry Andric }
isAnyExtLoad() const11062cab237bSDimitry Andric bool TreePredicateFn::isAnyExtLoad() const {
11072cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
11082cab237bSDimitry Andric }
isSignExtLoad() const11092cab237bSDimitry Andric bool TreePredicateFn::isSignExtLoad() const {
11102cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
11112cab237bSDimitry Andric }
isZeroExtLoad() const11122cab237bSDimitry Andric bool TreePredicateFn::isZeroExtLoad() const {
11132cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
11142cab237bSDimitry Andric }
isNonTruncStore() const11152cab237bSDimitry Andric bool TreePredicateFn::isNonTruncStore() const {
11162cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsTruncStore", false);
11172cab237bSDimitry Andric }
isTruncStore() const11182cab237bSDimitry Andric bool TreePredicateFn::isTruncStore() const {
11192cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsTruncStore", true);
11202cab237bSDimitry Andric }
isAtomicOrderingMonotonic() const11212cab237bSDimitry Andric bool TreePredicateFn::isAtomicOrderingMonotonic() const {
11222cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
11232cab237bSDimitry Andric }
isAtomicOrderingAcquire() const11242cab237bSDimitry Andric bool TreePredicateFn::isAtomicOrderingAcquire() const {
11252cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
11262cab237bSDimitry Andric }
isAtomicOrderingRelease() const11272cab237bSDimitry Andric bool TreePredicateFn::isAtomicOrderingRelease() const {
11282cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
11292cab237bSDimitry Andric }
isAtomicOrderingAcquireRelease() const11302cab237bSDimitry Andric bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
11312cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
11322cab237bSDimitry Andric }
isAtomicOrderingSequentiallyConsistent() const11332cab237bSDimitry Andric bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
11342cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
11352cab237bSDimitry Andric                                       true);
11362cab237bSDimitry Andric }
isAtomicOrderingAcquireOrStronger() const11372cab237bSDimitry Andric bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
11382cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
11392cab237bSDimitry Andric }
isAtomicOrderingWeakerThanAcquire() const11402cab237bSDimitry Andric bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
11412cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
11422cab237bSDimitry Andric }
isAtomicOrderingReleaseOrStronger() const11432cab237bSDimitry Andric bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
11442cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
11452cab237bSDimitry Andric }
isAtomicOrderingWeakerThanRelease() const11462cab237bSDimitry Andric bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
11472cab237bSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
11482cab237bSDimitry Andric }
getMemoryVT() const11492cab237bSDimitry Andric Record *TreePredicateFn::getMemoryVT() const {
11502cab237bSDimitry Andric   Record *R = getOrigPatFragRecord()->getRecord();
11512cab237bSDimitry Andric   if (R->isValueUnset("MemoryVT"))
11522cab237bSDimitry Andric     return nullptr;
11532cab237bSDimitry Andric   return R->getValueAsDef("MemoryVT");
11542cab237bSDimitry Andric }
getScalarMemoryVT() const11552cab237bSDimitry Andric Record *TreePredicateFn::getScalarMemoryVT() const {
11562cab237bSDimitry Andric   Record *R = getOrigPatFragRecord()->getRecord();
11572cab237bSDimitry Andric   if (R->isValueUnset("ScalarMemoryVT"))
11582cab237bSDimitry Andric     return nullptr;
11592cab237bSDimitry Andric   return R->getValueAsDef("ScalarMemoryVT");
11602cab237bSDimitry Andric }
hasGISelPredicateCode() const11614ba319b5SDimitry Andric bool TreePredicateFn::hasGISelPredicateCode() const {
11624ba319b5SDimitry Andric   return !PatFragRec->getRecord()
11634ba319b5SDimitry Andric               ->getValueAsString("GISelPredicateCode")
11644ba319b5SDimitry Andric               .empty();
11654ba319b5SDimitry Andric }
getGISelPredicateCode() const11664ba319b5SDimitry Andric std::string TreePredicateFn::getGISelPredicateCode() const {
11674ba319b5SDimitry Andric   return PatFragRec->getRecord()->getValueAsString("GISelPredicateCode");
11684ba319b5SDimitry Andric }
11692cab237bSDimitry Andric 
getImmType() const11702cab237bSDimitry Andric StringRef TreePredicateFn::getImmType() const {
11712cab237bSDimitry Andric   if (immCodeUsesAPInt())
11722cab237bSDimitry Andric     return "const APInt &";
11732cab237bSDimitry Andric   if (immCodeUsesAPFloat())
11742cab237bSDimitry Andric     return "const APFloat &";
11752cab237bSDimitry Andric   return "int64_t";
11762cab237bSDimitry Andric }
11772cab237bSDimitry Andric 
getImmTypeIdentifier() const11782cab237bSDimitry Andric StringRef TreePredicateFn::getImmTypeIdentifier() const {
11792cab237bSDimitry Andric   if (immCodeUsesAPInt())
11802cab237bSDimitry Andric     return "APInt";
11812cab237bSDimitry Andric   else if (immCodeUsesAPFloat())
11822cab237bSDimitry Andric     return "APFloat";
11832cab237bSDimitry Andric   return "I64";
11842cab237bSDimitry Andric }
11853b0f4066SDimitry Andric 
11863b0f4066SDimitry Andric /// isAlwaysTrue - Return true if this is a noop predicate.
isAlwaysTrue() const11873b0f4066SDimitry Andric bool TreePredicateFn::isAlwaysTrue() const {
11882cab237bSDimitry Andric   return !hasPredCode() && !hasImmCode();
11893b0f4066SDimitry Andric }
11903b0f4066SDimitry Andric 
11913b0f4066SDimitry Andric /// Return the name to use in the generated code to reference this, this is
11923b0f4066SDimitry Andric /// "Predicate_foo" if from a pattern fragment "foo".
getFnName() const11933b0f4066SDimitry Andric std::string TreePredicateFn::getFnName() const {
1194d88c1a5aSDimitry Andric   return "Predicate_" + PatFragRec->getRecord()->getName().str();
11953b0f4066SDimitry Andric }
11963b0f4066SDimitry Andric 
11973b0f4066SDimitry Andric /// getCodeToRunOnSDNode - Return the code for the function body that
11983b0f4066SDimitry Andric /// evaluates this predicate.  The argument is expected to be in "Node",
11993b0f4066SDimitry Andric /// not N.  This handles casting and conversion to a concrete node type as
12003b0f4066SDimitry Andric /// appropriate.
getCodeToRunOnSDNode() const12013b0f4066SDimitry Andric std::string TreePredicateFn::getCodeToRunOnSDNode() const {
12023b0f4066SDimitry Andric   // Handle immediate predicates first.
12033b0f4066SDimitry Andric   std::string ImmCode = getImmCode();
12043b0f4066SDimitry Andric   if (!ImmCode.empty()) {
12052cab237bSDimitry Andric     if (isLoad())
12062cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
12072cab237bSDimitry Andric                       "IsLoad cannot be used with ImmLeaf or its subclasses");
12082cab237bSDimitry Andric     if (isStore())
12092cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
12102cab237bSDimitry Andric                       "IsStore cannot be used with ImmLeaf or its subclasses");
12112cab237bSDimitry Andric     if (isUnindexed())
12122cab237bSDimitry Andric       PrintFatalError(
12132cab237bSDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
12142cab237bSDimitry Andric           "IsUnindexed cannot be used with ImmLeaf or its subclasses");
12152cab237bSDimitry Andric     if (isNonExtLoad())
12162cab237bSDimitry Andric       PrintFatalError(
12172cab237bSDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
12182cab237bSDimitry Andric           "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
12192cab237bSDimitry Andric     if (isAnyExtLoad())
12202cab237bSDimitry Andric       PrintFatalError(
12212cab237bSDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
12222cab237bSDimitry Andric           "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
12232cab237bSDimitry Andric     if (isSignExtLoad())
12242cab237bSDimitry Andric       PrintFatalError(
12252cab237bSDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
12262cab237bSDimitry Andric           "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
12272cab237bSDimitry Andric     if (isZeroExtLoad())
12282cab237bSDimitry Andric       PrintFatalError(
12292cab237bSDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
12302cab237bSDimitry Andric           "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
12312cab237bSDimitry Andric     if (isNonTruncStore())
12322cab237bSDimitry Andric       PrintFatalError(
12332cab237bSDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
12342cab237bSDimitry Andric           "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
12352cab237bSDimitry Andric     if (isTruncStore())
12362cab237bSDimitry Andric       PrintFatalError(
12372cab237bSDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
12382cab237bSDimitry Andric           "IsTruncStore cannot be used with ImmLeaf or its subclasses");
12392cab237bSDimitry Andric     if (getMemoryVT())
12402cab237bSDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
12412cab237bSDimitry Andric                       "MemoryVT cannot be used with ImmLeaf or its subclasses");
12422cab237bSDimitry Andric     if (getScalarMemoryVT())
12432cab237bSDimitry Andric       PrintFatalError(
12442cab237bSDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
12452cab237bSDimitry Andric           "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
12462cab237bSDimitry Andric 
12472cab237bSDimitry Andric     std::string Result = ("    " + getImmType() + " Imm = ").str();
12482cab237bSDimitry Andric     if (immCodeUsesAPFloat())
12492cab237bSDimitry Andric       Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
12502cab237bSDimitry Andric     else if (immCodeUsesAPInt())
12512cab237bSDimitry Andric       Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
12522cab237bSDimitry Andric     else
12532cab237bSDimitry Andric       Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
12543b0f4066SDimitry Andric     return Result + ImmCode;
12553b0f4066SDimitry Andric   }
12563b0f4066SDimitry Andric 
12573b0f4066SDimitry Andric   // Handle arbitrary node predicates.
12582cab237bSDimitry Andric   assert(hasPredCode() && "Don't have any predicate code!");
12592cab237bSDimitry Andric   StringRef ClassName;
12603b0f4066SDimitry Andric   if (PatFragRec->getOnlyTree()->isLeaf())
12613b0f4066SDimitry Andric     ClassName = "SDNode";
12623b0f4066SDimitry Andric   else {
12633b0f4066SDimitry Andric     Record *Op = PatFragRec->getOnlyTree()->getOperator();
12643b0f4066SDimitry Andric     ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
12653b0f4066SDimitry Andric   }
12663b0f4066SDimitry Andric   std::string Result;
12673b0f4066SDimitry Andric   if (ClassName == "SDNode")
12683b0f4066SDimitry Andric     Result = "    SDNode *N = Node;\n";
12693b0f4066SDimitry Andric   else
12702cab237bSDimitry Andric     Result = "    auto *N = cast<" + ClassName.str() + ">(Node);\n";
12713b0f4066SDimitry Andric 
1272*b5893f02SDimitry Andric   return (Twine(Result) + "    (void)N;\n" + getPredCode()).str();
1273f22ef01cSRoman Divacky }
1274f22ef01cSRoman Divacky 
1275f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1276f22ef01cSRoman Divacky // PatternToMatch implementation
1277f22ef01cSRoman Divacky //
1278f22ef01cSRoman Divacky 
1279f22ef01cSRoman Divacky /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1280f22ef01cSRoman Divacky /// patterns before small ones.  This is used to determine the size of a
1281f22ef01cSRoman Divacky /// pattern.
getPatternSize(const TreePatternNode * P,const CodeGenDAGPatterns & CGP)1282f22ef01cSRoman Divacky static unsigned getPatternSize(const TreePatternNode *P,
1283f22ef01cSRoman Divacky                                const CodeGenDAGPatterns &CGP) {
1284f22ef01cSRoman Divacky   unsigned Size = 3;  // The node itself.
1285f22ef01cSRoman Divacky   // If the root node is a ConstantSDNode, increases its size.
1286f22ef01cSRoman Divacky   // e.g. (set R32:$dst, 0).
12873861d79fSDimitry Andric   if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
1288f22ef01cSRoman Divacky     Size += 2;
1289f22ef01cSRoman Divacky 
12902cab237bSDimitry Andric   if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
1291d88c1a5aSDimitry Andric     Size += AM->getComplexity();
129291bc56edSDimitry Andric     // We don't want to count any children twice, so return early.
129391bc56edSDimitry Andric     return Size;
129491bc56edSDimitry Andric   }
129591bc56edSDimitry Andric 
1296f22ef01cSRoman Divacky   // If this node has some predicate function that must match, it adds to the
1297f22ef01cSRoman Divacky   // complexity of this node.
1298*b5893f02SDimitry Andric   if (!P->getPredicateCalls().empty())
1299f22ef01cSRoman Divacky     ++Size;
1300f22ef01cSRoman Divacky 
1301f22ef01cSRoman Divacky   // Count children in the count if they are also nodes.
1302f22ef01cSRoman Divacky   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
13032cab237bSDimitry Andric     const TreePatternNode *Child = P->getChild(i);
13042cab237bSDimitry Andric     if (!Child->isLeaf() && Child->getNumTypes()) {
1305*b5893f02SDimitry Andric       const TypeSetByHwMode &T0 = Child->getExtType(0);
13062cab237bSDimitry Andric       // At this point, all variable type sets should be simple, i.e. only
13072cab237bSDimitry Andric       // have a default mode.
13082cab237bSDimitry Andric       if (T0.getMachineValueType() != MVT::Other) {
1309f22ef01cSRoman Divacky         Size += getPatternSize(Child, CGP);
13102cab237bSDimitry Andric         continue;
13112cab237bSDimitry Andric       }
13122cab237bSDimitry Andric     }
13132cab237bSDimitry Andric     if (Child->isLeaf()) {
13143861d79fSDimitry Andric       if (isa<IntInit>(Child->getLeafValue()))
1315f22ef01cSRoman Divacky         Size += 5;  // Matches a ConstantSDNode (+3) and a specific value (+2).
1316f22ef01cSRoman Divacky       else if (Child->getComplexPatternInfo(CGP))
1317f22ef01cSRoman Divacky         Size += getPatternSize(Child, CGP);
1318*b5893f02SDimitry Andric       else if (!Child->getPredicateCalls().empty())
1319f22ef01cSRoman Divacky         ++Size;
1320f22ef01cSRoman Divacky     }
1321f22ef01cSRoman Divacky   }
1322f22ef01cSRoman Divacky 
1323f22ef01cSRoman Divacky   return Size;
1324f22ef01cSRoman Divacky }
1325f22ef01cSRoman Divacky 
1326f22ef01cSRoman Divacky /// Compute the complexity metric for the input pattern.  This roughly
1327f22ef01cSRoman Divacky /// corresponds to the number of nodes that are covered.
132839d628a0SDimitry Andric int PatternToMatch::
getPatternComplexity(const CodeGenDAGPatterns & CGP) const1329f22ef01cSRoman Divacky getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1330f22ef01cSRoman Divacky   return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1331f22ef01cSRoman Divacky }
1332f22ef01cSRoman Divacky 
1333f22ef01cSRoman Divacky /// getPredicateCheck - Return a single string containing all of this
1334f22ef01cSRoman Divacky /// pattern's predicates concatenated with "&&" operators.
1335f22ef01cSRoman Divacky ///
getPredicateCheck() const1336f22ef01cSRoman Divacky std::string PatternToMatch::getPredicateCheck() const {
13372cab237bSDimitry Andric   SmallVector<const Predicate*,4> PredList;
13382cab237bSDimitry Andric   for (const Predicate &P : Predicates)
13392cab237bSDimitry Andric     PredList.push_back(&P);
1340*b5893f02SDimitry Andric   llvm::sort(PredList, deref<llvm::less>());
13417d523365SDimitry Andric 
13422cab237bSDimitry Andric   std::string Check;
13432cab237bSDimitry Andric   for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
13442cab237bSDimitry Andric     if (i != 0)
13452cab237bSDimitry Andric       Check += " && ";
13462cab237bSDimitry Andric     Check += '(' + PredList[i]->getCondString() + ')';
1347f22ef01cSRoman Divacky   }
13482cab237bSDimitry Andric   return Check;
1349f22ef01cSRoman Divacky }
1350f22ef01cSRoman Divacky 
1351f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1352f22ef01cSRoman Divacky // SDTypeConstraint implementation
1353f22ef01cSRoman Divacky //
1354f22ef01cSRoman Divacky 
SDTypeConstraint(Record * R,const CodeGenHwModes & CGH)13552cab237bSDimitry Andric SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
1356f22ef01cSRoman Divacky   OperandNo = R->getValueAsInt("OperandNum");
1357f22ef01cSRoman Divacky 
1358f22ef01cSRoman Divacky   if (R->isSubClassOf("SDTCisVT")) {
1359f22ef01cSRoman Divacky     ConstraintType = SDTCisVT;
13602cab237bSDimitry Andric     VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
13612cab237bSDimitry Andric     for (const auto &P : VVT)
13622cab237bSDimitry Andric       if (P.second == MVT::isVoid)
13633861d79fSDimitry Andric         PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
1364f22ef01cSRoman Divacky   } else if (R->isSubClassOf("SDTCisPtrTy")) {
1365f22ef01cSRoman Divacky     ConstraintType = SDTCisPtrTy;
1366f22ef01cSRoman Divacky   } else if (R->isSubClassOf("SDTCisInt")) {
1367f22ef01cSRoman Divacky     ConstraintType = SDTCisInt;
1368f22ef01cSRoman Divacky   } else if (R->isSubClassOf("SDTCisFP")) {
1369f22ef01cSRoman Divacky     ConstraintType = SDTCisFP;
1370f22ef01cSRoman Divacky   } else if (R->isSubClassOf("SDTCisVec")) {
1371f22ef01cSRoman Divacky     ConstraintType = SDTCisVec;
1372f22ef01cSRoman Divacky   } else if (R->isSubClassOf("SDTCisSameAs")) {
1373f22ef01cSRoman Divacky     ConstraintType = SDTCisSameAs;
1374f22ef01cSRoman Divacky     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1375f22ef01cSRoman Divacky   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1376f22ef01cSRoman Divacky     ConstraintType = SDTCisVTSmallerThanOp;
1377f22ef01cSRoman Divacky     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
1378f22ef01cSRoman Divacky       R->getValueAsInt("OtherOperandNum");
1379f22ef01cSRoman Divacky   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1380f22ef01cSRoman Divacky     ConstraintType = SDTCisOpSmallerThanOp;
1381f22ef01cSRoman Divacky     x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
1382f22ef01cSRoman Divacky       R->getValueAsInt("BigOperandNum");
1383f22ef01cSRoman Divacky   } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1384f22ef01cSRoman Divacky     ConstraintType = SDTCisEltOfVec;
1385f22ef01cSRoman Divacky     x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
13862754fe60SDimitry Andric   } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
13872754fe60SDimitry Andric     ConstraintType = SDTCisSubVecOfVec;
13882754fe60SDimitry Andric     x.SDTCisSubVecOfVec_Info.OtherOperandNum =
13892754fe60SDimitry Andric       R->getValueAsInt("OtherOpNum");
1390ff0cc061SDimitry Andric   } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1391ff0cc061SDimitry Andric     ConstraintType = SDTCVecEltisVT;
13922cab237bSDimitry Andric     VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
13932cab237bSDimitry Andric     for (const auto &P : VVT) {
13942cab237bSDimitry Andric       MVT T = P.second;
13952cab237bSDimitry Andric       if (T.isVector())
13962cab237bSDimitry Andric         PrintFatalError(R->getLoc(),
13972cab237bSDimitry Andric                         "Cannot use vector type as SDTCVecEltisVT");
13982cab237bSDimitry Andric       if (!T.isInteger() && !T.isFloatingPoint())
1399ff0cc061SDimitry Andric         PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1400ff0cc061SDimitry Andric                                      "as SDTCVecEltisVT");
14012cab237bSDimitry Andric     }
1402ff0cc061SDimitry Andric   } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1403ff0cc061SDimitry Andric     ConstraintType = SDTCisSameNumEltsAs;
1404ff0cc061SDimitry Andric     x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1405ff0cc061SDimitry Andric       R->getValueAsInt("OtherOperandNum");
14067d523365SDimitry Andric   } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
14077d523365SDimitry Andric     ConstraintType = SDTCisSameSizeAs;
14087d523365SDimitry Andric     x.SDTCisSameSizeAs_Info.OtherOperandNum =
14097d523365SDimitry Andric       R->getValueAsInt("OtherOperandNum");
1410f22ef01cSRoman Divacky   } else {
1411ff0cc061SDimitry Andric     PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
1412f22ef01cSRoman Divacky   }
1413f22ef01cSRoman Divacky }
1414f22ef01cSRoman Divacky 
1415f22ef01cSRoman Divacky /// getOperandNum - Return the node corresponding to operand #OpNo in tree
1416f22ef01cSRoman Divacky /// N, and the result number in ResNo.
getOperandNum(unsigned OpNo,TreePatternNode * N,const SDNodeInfo & NodeInfo,unsigned & ResNo)1417f22ef01cSRoman Divacky static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1418f22ef01cSRoman Divacky                                       const SDNodeInfo &NodeInfo,
1419f22ef01cSRoman Divacky                                       unsigned &ResNo) {
1420f22ef01cSRoman Divacky   unsigned NumResults = NodeInfo.getNumResults();
1421f22ef01cSRoman Divacky   if (OpNo < NumResults) {
1422f22ef01cSRoman Divacky     ResNo = OpNo;
1423f22ef01cSRoman Divacky     return N;
1424f22ef01cSRoman Divacky   }
1425f22ef01cSRoman Divacky 
1426f22ef01cSRoman Divacky   OpNo -= NumResults;
1427f22ef01cSRoman Divacky 
1428f22ef01cSRoman Divacky   if (OpNo >= N->getNumChildren()) {
1429ff0cc061SDimitry Andric     std::string S;
1430ff0cc061SDimitry Andric     raw_string_ostream OS(S);
1431ff0cc061SDimitry Andric     OS << "Invalid operand number in type constraint "
1432f22ef01cSRoman Divacky            << (OpNo+NumResults) << " ";
1433ff0cc061SDimitry Andric     N->print(OS);
1434ff0cc061SDimitry Andric     PrintFatalError(OS.str());
1435f22ef01cSRoman Divacky   }
1436f22ef01cSRoman Divacky 
1437f22ef01cSRoman Divacky   return N->getChild(OpNo);
1438f22ef01cSRoman Divacky }
1439f22ef01cSRoman Divacky 
1440f22ef01cSRoman Divacky /// ApplyTypeConstraint - Given a node in a pattern, apply this type
1441f22ef01cSRoman Divacky /// constraint to the nodes operands.  This returns true if it makes a
14423861d79fSDimitry Andric /// change, false otherwise.  If a type contradiction is found, flag an error.
ApplyTypeConstraint(TreePatternNode * N,const SDNodeInfo & NodeInfo,TreePattern & TP) const1443f22ef01cSRoman Divacky bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1444f22ef01cSRoman Divacky                                            const SDNodeInfo &NodeInfo,
1445f22ef01cSRoman Divacky                                            TreePattern &TP) const {
14463861d79fSDimitry Andric   if (TP.hasError())
14473861d79fSDimitry Andric     return false;
14483861d79fSDimitry Andric 
1449f22ef01cSRoman Divacky   unsigned ResNo = 0; // The result number being referenced.
1450f22ef01cSRoman Divacky   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
14512cab237bSDimitry Andric   TypeInfer &TI = TP.getInfer();
1452f22ef01cSRoman Divacky 
1453f22ef01cSRoman Divacky   switch (ConstraintType) {
1454f22ef01cSRoman Divacky   case SDTCisVT:
1455f22ef01cSRoman Divacky     // Operand must be a particular type.
14562cab237bSDimitry Andric     return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
1457f22ef01cSRoman Divacky   case SDTCisPtrTy:
1458f22ef01cSRoman Divacky     // Operand must be same as target pointer type.
1459f22ef01cSRoman Divacky     return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
1460f22ef01cSRoman Divacky   case SDTCisInt:
1461f22ef01cSRoman Divacky     // Require it to be one of the legal integer VTs.
14622cab237bSDimitry Andric      return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
1463f22ef01cSRoman Divacky   case SDTCisFP:
1464f22ef01cSRoman Divacky     // Require it to be one of the legal fp VTs.
14652cab237bSDimitry Andric     return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
1466f22ef01cSRoman Divacky   case SDTCisVec:
1467f22ef01cSRoman Divacky     // Require it to be one of the legal vector VTs.
14682cab237bSDimitry Andric     return TI.EnforceVector(NodeToApply->getExtType(ResNo));
1469f22ef01cSRoman Divacky   case SDTCisSameAs: {
1470f22ef01cSRoman Divacky     unsigned OResNo = 0;
1471f22ef01cSRoman Divacky     TreePatternNode *OtherNode =
1472f22ef01cSRoman Divacky       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1473ff0cc061SDimitry Andric     return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1474ff0cc061SDimitry Andric            OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
1475f22ef01cSRoman Divacky   }
1476f22ef01cSRoman Divacky   case SDTCisVTSmallerThanOp: {
1477f22ef01cSRoman Divacky     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
1478f22ef01cSRoman Divacky     // have an integer type that is smaller than the VT.
1479f22ef01cSRoman Divacky     if (!NodeToApply->isLeaf() ||
14803861d79fSDimitry Andric         !isa<DefInit>(NodeToApply->getLeafValue()) ||
1481f22ef01cSRoman Divacky         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
14823861d79fSDimitry Andric                ->isSubClassOf("ValueType")) {
1483f22ef01cSRoman Divacky       TP.error(N->getOperator()->getName() + " expects a VT operand!");
14843861d79fSDimitry Andric       return false;
14853861d79fSDimitry Andric     }
14862cab237bSDimitry Andric     DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
14872cab237bSDimitry Andric     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
14882cab237bSDimitry Andric     auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
14892cab237bSDimitry Andric     TypeSetByHwMode TypeListTmp(VVT);
1490f22ef01cSRoman Divacky 
1491f22ef01cSRoman Divacky     unsigned OResNo = 0;
1492f22ef01cSRoman Divacky     TreePatternNode *OtherNode =
1493f22ef01cSRoman Divacky       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1494f22ef01cSRoman Divacky                     OResNo);
1495f22ef01cSRoman Divacky 
14962cab237bSDimitry Andric     return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
1497f22ef01cSRoman Divacky   }
1498f22ef01cSRoman Divacky   case SDTCisOpSmallerThanOp: {
1499f22ef01cSRoman Divacky     unsigned BResNo = 0;
1500f22ef01cSRoman Divacky     TreePatternNode *BigOperand =
1501f22ef01cSRoman Divacky       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1502f22ef01cSRoman Divacky                     BResNo);
15032cab237bSDimitry Andric     return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
15042cab237bSDimitry Andric                                  BigOperand->getExtType(BResNo));
1505f22ef01cSRoman Divacky   }
1506f22ef01cSRoman Divacky   case SDTCisEltOfVec: {
1507f22ef01cSRoman Divacky     unsigned VResNo = 0;
1508f22ef01cSRoman Divacky     TreePatternNode *VecOperand =
1509f22ef01cSRoman Divacky       getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1510f22ef01cSRoman Divacky                     VResNo);
1511f22ef01cSRoman Divacky     // Filter vector types out of VecOperand that don't have the right element
1512f22ef01cSRoman Divacky     // type.
15132cab237bSDimitry Andric     return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
15142cab237bSDimitry Andric                                      NodeToApply->getExtType(ResNo));
1515f22ef01cSRoman Divacky   }
15162754fe60SDimitry Andric   case SDTCisSubVecOfVec: {
15172754fe60SDimitry Andric     unsigned VResNo = 0;
15182754fe60SDimitry Andric     TreePatternNode *BigVecOperand =
15192754fe60SDimitry Andric       getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
15202754fe60SDimitry Andric                     VResNo);
15212754fe60SDimitry Andric 
15222754fe60SDimitry Andric     // Filter vector types out of BigVecOperand that don't have the
15232754fe60SDimitry Andric     // right subvector type.
15242cab237bSDimitry Andric     return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
15252cab237bSDimitry Andric                                            NodeToApply->getExtType(ResNo));
15262754fe60SDimitry Andric   }
1527ff0cc061SDimitry Andric   case SDTCVecEltisVT: {
15282cab237bSDimitry Andric     return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
1529ff0cc061SDimitry Andric   }
1530ff0cc061SDimitry Andric   case SDTCisSameNumEltsAs: {
1531ff0cc061SDimitry Andric     unsigned OResNo = 0;
1532ff0cc061SDimitry Andric     TreePatternNode *OtherNode =
1533ff0cc061SDimitry Andric       getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1534ff0cc061SDimitry Andric                     N, NodeInfo, OResNo);
15352cab237bSDimitry Andric     return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
15362cab237bSDimitry Andric                                  NodeToApply->getExtType(ResNo));
1537ff0cc061SDimitry Andric   }
15387d523365SDimitry Andric   case SDTCisSameSizeAs: {
15397d523365SDimitry Andric     unsigned OResNo = 0;
15407d523365SDimitry Andric     TreePatternNode *OtherNode =
15417d523365SDimitry Andric       getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
15427d523365SDimitry Andric                     N, NodeInfo, OResNo);
15432cab237bSDimitry Andric     return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
15442cab237bSDimitry Andric                               NodeToApply->getExtType(ResNo));
15457d523365SDimitry Andric   }
1546f22ef01cSRoman Divacky   }
1547dff0c46cSDimitry Andric   llvm_unreachable("Invalid ConstraintType!");
1548f22ef01cSRoman Divacky }
1549f22ef01cSRoman Divacky 
1550139f7f9bSDimitry Andric // Update the node type to match an instruction operand or result as specified
1551139f7f9bSDimitry Andric // in the ins or outs lists on the instruction definition. Return true if the
1552139f7f9bSDimitry Andric // type was actually changed.
UpdateNodeTypeFromInst(unsigned ResNo,Record * Operand,TreePattern & TP)1553139f7f9bSDimitry Andric bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1554139f7f9bSDimitry Andric                                              Record *Operand,
1555139f7f9bSDimitry Andric                                              TreePattern &TP) {
1556139f7f9bSDimitry Andric   // The 'unknown' operand indicates that types should be inferred from the
1557139f7f9bSDimitry Andric   // context.
1558139f7f9bSDimitry Andric   if (Operand->isSubClassOf("unknown_class"))
1559139f7f9bSDimitry Andric     return false;
1560139f7f9bSDimitry Andric 
1561139f7f9bSDimitry Andric   // The Operand class specifies a type directly.
15622cab237bSDimitry Andric   if (Operand->isSubClassOf("Operand")) {
15632cab237bSDimitry Andric     Record *R = Operand->getValueAsDef("Type");
15642cab237bSDimitry Andric     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
15652cab237bSDimitry Andric     return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
15662cab237bSDimitry Andric   }
1567139f7f9bSDimitry Andric 
1568139f7f9bSDimitry Andric   // PointerLikeRegClass has a type that is determined at runtime.
1569139f7f9bSDimitry Andric   if (Operand->isSubClassOf("PointerLikeRegClass"))
1570139f7f9bSDimitry Andric     return UpdateNodeType(ResNo, MVT::iPTR, TP);
1571139f7f9bSDimitry Andric 
1572139f7f9bSDimitry Andric   // Both RegisterClass and RegisterOperand operands derive their types from a
1573139f7f9bSDimitry Andric   // register class def.
157491bc56edSDimitry Andric   Record *RC = nullptr;
1575139f7f9bSDimitry Andric   if (Operand->isSubClassOf("RegisterClass"))
1576139f7f9bSDimitry Andric     RC = Operand;
1577139f7f9bSDimitry Andric   else if (Operand->isSubClassOf("RegisterOperand"))
1578139f7f9bSDimitry Andric     RC = Operand->getValueAsDef("RegClass");
1579139f7f9bSDimitry Andric 
1580139f7f9bSDimitry Andric   assert(RC && "Unknown operand type");
1581139f7f9bSDimitry Andric   CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1582139f7f9bSDimitry Andric   return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1583139f7f9bSDimitry Andric }
1584139f7f9bSDimitry Andric 
ContainsUnresolvedType(TreePattern & TP) const15852cab237bSDimitry Andric bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
15862cab237bSDimitry Andric   for (unsigned i = 0, e = Types.size(); i != e; ++i)
15872cab237bSDimitry Andric     if (!TP.getInfer().isConcrete(Types[i], true))
15882cab237bSDimitry Andric       return true;
15892cab237bSDimitry Andric   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
15902cab237bSDimitry Andric     if (getChild(i)->ContainsUnresolvedType(TP))
15912cab237bSDimitry Andric       return true;
15922cab237bSDimitry Andric   return false;
15932cab237bSDimitry Andric }
15942cab237bSDimitry Andric 
hasProperTypeByHwMode() const15952cab237bSDimitry Andric bool TreePatternNode::hasProperTypeByHwMode() const {
15962cab237bSDimitry Andric   for (const TypeSetByHwMode &S : Types)
15972cab237bSDimitry Andric     if (!S.isDefaultOnly())
15982cab237bSDimitry Andric       return true;
15994ba319b5SDimitry Andric   for (const TreePatternNodePtr &C : Children)
16002cab237bSDimitry Andric     if (C->hasProperTypeByHwMode())
16012cab237bSDimitry Andric       return true;
16022cab237bSDimitry Andric   return false;
16032cab237bSDimitry Andric }
16042cab237bSDimitry Andric 
hasPossibleType() const16052cab237bSDimitry Andric bool TreePatternNode::hasPossibleType() const {
16062cab237bSDimitry Andric   for (const TypeSetByHwMode &S : Types)
16072cab237bSDimitry Andric     if (!S.isPossible())
16082cab237bSDimitry Andric       return false;
16094ba319b5SDimitry Andric   for (const TreePatternNodePtr &C : Children)
16102cab237bSDimitry Andric     if (!C->hasPossibleType())
16112cab237bSDimitry Andric       return false;
16122cab237bSDimitry Andric   return true;
16132cab237bSDimitry Andric }
16142cab237bSDimitry Andric 
setDefaultMode(unsigned Mode)16152cab237bSDimitry Andric bool TreePatternNode::setDefaultMode(unsigned Mode) {
16162cab237bSDimitry Andric   for (TypeSetByHwMode &S : Types) {
16172cab237bSDimitry Andric     S.makeSimple(Mode);
16182cab237bSDimitry Andric     // Check if the selected mode had a type conflict.
16192cab237bSDimitry Andric     if (S.get(DefaultMode).empty())
16202cab237bSDimitry Andric       return false;
16212cab237bSDimitry Andric   }
16224ba319b5SDimitry Andric   for (const TreePatternNodePtr &C : Children)
16232cab237bSDimitry Andric     if (!C->setDefaultMode(Mode))
16242cab237bSDimitry Andric       return false;
16252cab237bSDimitry Andric   return true;
16262cab237bSDimitry Andric }
1627139f7f9bSDimitry Andric 
1628f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1629f22ef01cSRoman Divacky // SDNodeInfo implementation
1630f22ef01cSRoman Divacky //
SDNodeInfo(Record * R,const CodeGenHwModes & CGH)16312cab237bSDimitry Andric SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
1632f22ef01cSRoman Divacky   EnumName    = R->getValueAsString("Opcode");
1633f22ef01cSRoman Divacky   SDClassName = R->getValueAsString("SDClass");
1634f22ef01cSRoman Divacky   Record *TypeProfile = R->getValueAsDef("TypeProfile");
1635f22ef01cSRoman Divacky   NumResults = TypeProfile->getValueAsInt("NumResults");
1636f22ef01cSRoman Divacky   NumOperands = TypeProfile->getValueAsInt("NumOperands");
1637f22ef01cSRoman Divacky 
1638f22ef01cSRoman Divacky   // Parse the properties.
1639da09e106SDimitry Andric   Properties = parseSDPatternOperatorProperties(R);
1640f22ef01cSRoman Divacky 
1641f22ef01cSRoman Divacky   // Parse the type constraints.
1642f22ef01cSRoman Divacky   std::vector<Record*> ConstraintList =
1643f22ef01cSRoman Divacky     TypeProfile->getValueAsListOfDefs("Constraints");
16442cab237bSDimitry Andric   for (Record *R : ConstraintList)
16452cab237bSDimitry Andric     TypeConstraints.emplace_back(R, CGH);
1646f22ef01cSRoman Divacky }
1647f22ef01cSRoman Divacky 
1648f22ef01cSRoman Divacky /// getKnownType - If the type constraints on this node imply a fixed type
1649f22ef01cSRoman Divacky /// (e.g. all stores return void, etc), then return it as an
1650f22ef01cSRoman Divacky /// MVT::SimpleValueType.  Otherwise, return EEVT::Other.
getKnownType(unsigned ResNo) const1651f22ef01cSRoman Divacky MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1652f22ef01cSRoman Divacky   unsigned NumResults = getNumResults();
1653f22ef01cSRoman Divacky   assert(NumResults <= 1 &&
1654f22ef01cSRoman Divacky          "We only work with nodes with zero or one result so far!");
1655f22ef01cSRoman Divacky   assert(ResNo == 0 && "Only handles single result nodes so far");
1656f22ef01cSRoman Divacky 
16577d523365SDimitry Andric   for (const SDTypeConstraint &Constraint : TypeConstraints) {
1658f22ef01cSRoman Divacky     // Make sure that this applies to the correct node result.
16597d523365SDimitry Andric     if (Constraint.OperandNo >= NumResults)  // FIXME: need value #
1660f22ef01cSRoman Divacky       continue;
1661f22ef01cSRoman Divacky 
16627d523365SDimitry Andric     switch (Constraint.ConstraintType) {
1663f22ef01cSRoman Divacky     default: break;
1664f22ef01cSRoman Divacky     case SDTypeConstraint::SDTCisVT:
16652cab237bSDimitry Andric       if (Constraint.VVT.isSimple())
16662cab237bSDimitry Andric         return Constraint.VVT.getSimple().SimpleTy;
16672cab237bSDimitry Andric       break;
1668f22ef01cSRoman Divacky     case SDTypeConstraint::SDTCisPtrTy:
1669f22ef01cSRoman Divacky       return MVT::iPTR;
1670f22ef01cSRoman Divacky     }
1671f22ef01cSRoman Divacky   }
1672f22ef01cSRoman Divacky   return MVT::Other;
1673f22ef01cSRoman Divacky }
1674f22ef01cSRoman Divacky 
1675f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1676f22ef01cSRoman Divacky // TreePatternNode implementation
1677f22ef01cSRoman Divacky //
1678f22ef01cSRoman Divacky 
GetNumNodeResults(Record * Operator,CodeGenDAGPatterns & CDP)1679f22ef01cSRoman Divacky static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1680f22ef01cSRoman Divacky   if (Operator->getName() == "set" ||
1681f22ef01cSRoman Divacky       Operator->getName() == "implicit")
1682f22ef01cSRoman Divacky     return 0;  // All return nothing.
1683f22ef01cSRoman Divacky 
1684f22ef01cSRoman Divacky   if (Operator->isSubClassOf("Intrinsic"))
1685f22ef01cSRoman Divacky     return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1686f22ef01cSRoman Divacky 
1687f22ef01cSRoman Divacky   if (Operator->isSubClassOf("SDNode"))
1688f22ef01cSRoman Divacky     return CDP.getSDNodeInfo(Operator).getNumResults();
1689f22ef01cSRoman Divacky 
16904ba319b5SDimitry Andric   if (Operator->isSubClassOf("PatFrags")) {
1691f22ef01cSRoman Divacky     // If we've already parsed this pattern fragment, get it.  Otherwise, handle
1692f22ef01cSRoman Divacky     // the forward reference case where one pattern fragment references another
1693f22ef01cSRoman Divacky     // before it is processed.
16944ba319b5SDimitry Andric     if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
16954ba319b5SDimitry Andric       // The number of results of a fragment with alternative records is the
16964ba319b5SDimitry Andric       // maximum number of results across all alternatives.
16974ba319b5SDimitry Andric       unsigned NumResults = 0;
16984ba319b5SDimitry Andric       for (auto T : PFRec->getTrees())
16994ba319b5SDimitry Andric         NumResults = std::max(NumResults, T->getNumTypes());
17004ba319b5SDimitry Andric       return NumResults;
17014ba319b5SDimitry Andric     }
1702f22ef01cSRoman Divacky 
17034ba319b5SDimitry Andric     ListInit *LI = Operator->getValueAsListInit("Fragments");
17044ba319b5SDimitry Andric     assert(LI && "Invalid Fragment");
17054ba319b5SDimitry Andric     unsigned NumResults = 0;
17064ba319b5SDimitry Andric     for (Init *I : LI->getValues()) {
170791bc56edSDimitry Andric       Record *Op = nullptr;
17084ba319b5SDimitry Andric       if (DagInit *Dag = dyn_cast<DagInit>(I))
17094ba319b5SDimitry Andric         if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
17103861d79fSDimitry Andric           Op = DI->getDef();
1711f22ef01cSRoman Divacky       assert(Op && "Invalid Fragment");
17124ba319b5SDimitry Andric       NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
17134ba319b5SDimitry Andric     }
17144ba319b5SDimitry Andric     return NumResults;
1715f22ef01cSRoman Divacky   }
1716f22ef01cSRoman Divacky 
1717f22ef01cSRoman Divacky   if (Operator->isSubClassOf("Instruction")) {
1718f22ef01cSRoman Divacky     CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1719f22ef01cSRoman Divacky 
1720ff0cc061SDimitry Andric     unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1721ff0cc061SDimitry Andric 
1722ff0cc061SDimitry Andric     // Subtract any defaulted outputs.
1723ff0cc061SDimitry Andric     for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1724ff0cc061SDimitry Andric       Record *OperandNode = InstInfo.Operands[i].Rec;
1725ff0cc061SDimitry Andric 
1726ff0cc061SDimitry Andric       if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1727ff0cc061SDimitry Andric           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1728ff0cc061SDimitry Andric         --NumDefsToAdd;
1729ff0cc061SDimitry Andric     }
1730f22ef01cSRoman Divacky 
1731f22ef01cSRoman Divacky     // Add on one implicit def if it has a resolvable type.
1732f22ef01cSRoman Divacky     if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1733f22ef01cSRoman Divacky       ++NumDefsToAdd;
1734f22ef01cSRoman Divacky     return NumDefsToAdd;
1735f22ef01cSRoman Divacky   }
1736f22ef01cSRoman Divacky 
1737f22ef01cSRoman Divacky   if (Operator->isSubClassOf("SDNodeXForm"))
1738f22ef01cSRoman Divacky     return 1;  // FIXME: Generalize SDNodeXForm
1739f22ef01cSRoman Divacky 
174091bc56edSDimitry Andric   if (Operator->isSubClassOf("ValueType"))
174191bc56edSDimitry Andric     return 1;  // A type-cast of one result.
174291bc56edSDimitry Andric 
174391bc56edSDimitry Andric   if (Operator->isSubClassOf("ComplexPattern"))
174491bc56edSDimitry Andric     return 1;
174591bc56edSDimitry Andric 
17467a7e6055SDimitry Andric   errs() << *Operator;
1747ff0cc061SDimitry Andric   PrintFatalError("Unhandled node in GetNumNodeResults");
1748f22ef01cSRoman Divacky }
1749f22ef01cSRoman Divacky 
print(raw_ostream & OS) const1750f22ef01cSRoman Divacky void TreePatternNode::print(raw_ostream &OS) const {
1751f22ef01cSRoman Divacky   if (isLeaf())
1752f22ef01cSRoman Divacky     OS << *getLeafValue();
1753f22ef01cSRoman Divacky   else
1754f22ef01cSRoman Divacky     OS << '(' << getOperator()->getName();
1755f22ef01cSRoman Divacky 
17562cab237bSDimitry Andric   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
17572cab237bSDimitry Andric     OS << ':';
17582cab237bSDimitry Andric     getExtType(i).writeToStream(OS);
17592cab237bSDimitry Andric   }
1760f22ef01cSRoman Divacky 
1761f22ef01cSRoman Divacky   if (!isLeaf()) {
1762f22ef01cSRoman Divacky     if (getNumChildren() != 0) {
1763f22ef01cSRoman Divacky       OS << " ";
1764f22ef01cSRoman Divacky       getChild(0)->print(OS);
1765f22ef01cSRoman Divacky       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1766f22ef01cSRoman Divacky         OS << ", ";
1767f22ef01cSRoman Divacky         getChild(i)->print(OS);
1768f22ef01cSRoman Divacky       }
1769f22ef01cSRoman Divacky     }
1770f22ef01cSRoman Divacky     OS << ")";
1771f22ef01cSRoman Divacky   }
1772f22ef01cSRoman Divacky 
1773*b5893f02SDimitry Andric   for (const TreePredicateCall &Pred : PredicateCalls) {
1774*b5893f02SDimitry Andric     OS << "<<P:";
1775*b5893f02SDimitry Andric     if (Pred.Scope)
1776*b5893f02SDimitry Andric       OS << Pred.Scope << ":";
1777*b5893f02SDimitry Andric     OS << Pred.Fn.getFnName() << ">>";
1778*b5893f02SDimitry Andric   }
1779f22ef01cSRoman Divacky   if (TransformFn)
1780f22ef01cSRoman Divacky     OS << "<<X:" << TransformFn->getName() << ">>";
1781f22ef01cSRoman Divacky   if (!getName().empty())
1782f22ef01cSRoman Divacky     OS << ":$" << getName();
1783f22ef01cSRoman Divacky 
1784*b5893f02SDimitry Andric   for (const ScopedName &Name : NamesAsPredicateArg)
1785*b5893f02SDimitry Andric     OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
1786f22ef01cSRoman Divacky }
dump() const1787f22ef01cSRoman Divacky void TreePatternNode::dump() const {
1788f22ef01cSRoman Divacky   print(errs());
1789f22ef01cSRoman Divacky }
1790f22ef01cSRoman Divacky 
1791f22ef01cSRoman Divacky /// isIsomorphicTo - Return true if this node is recursively
1792f22ef01cSRoman Divacky /// isomorphic to the specified node.  For this comparison, the node's
1793f22ef01cSRoman Divacky /// entire state is considered. The assigned name is ignored, since
1794f22ef01cSRoman Divacky /// nodes with differing names are considered isomorphic. However, if
1795f22ef01cSRoman Divacky /// the assigned name is present in the dependent variable set, then
1796f22ef01cSRoman Divacky /// the assigned name is considered significant and the node is
1797f22ef01cSRoman Divacky /// isomorphic if the names match.
isIsomorphicTo(const TreePatternNode * N,const MultipleUseVarSet & DepVars) const1798f22ef01cSRoman Divacky bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1799f22ef01cSRoman Divacky                                      const MultipleUseVarSet &DepVars) const {
1800f22ef01cSRoman Divacky   if (N == this) return true;
1801f22ef01cSRoman Divacky   if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1802*b5893f02SDimitry Andric       getPredicateCalls() != N->getPredicateCalls() ||
1803f22ef01cSRoman Divacky       getTransformFn() != N->getTransformFn())
1804f22ef01cSRoman Divacky     return false;
1805f22ef01cSRoman Divacky 
1806f22ef01cSRoman Divacky   if (isLeaf()) {
18073861d79fSDimitry Andric     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
18083861d79fSDimitry Andric       if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1809f22ef01cSRoman Divacky         return ((DI->getDef() == NDI->getDef())
1810f22ef01cSRoman Divacky                 && (DepVars.find(getName()) == DepVars.end()
1811f22ef01cSRoman Divacky                     || getName() == N->getName()));
1812f22ef01cSRoman Divacky       }
1813f22ef01cSRoman Divacky     }
1814f22ef01cSRoman Divacky     return getLeafValue() == N->getLeafValue();
1815f22ef01cSRoman Divacky   }
1816f22ef01cSRoman Divacky 
1817f22ef01cSRoman Divacky   if (N->getOperator() != getOperator() ||
1818f22ef01cSRoman Divacky       N->getNumChildren() != getNumChildren()) return false;
1819f22ef01cSRoman Divacky   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1820f22ef01cSRoman Divacky     if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1821f22ef01cSRoman Divacky       return false;
1822f22ef01cSRoman Divacky   return true;
1823f22ef01cSRoman Divacky }
1824f22ef01cSRoman Divacky 
1825f22ef01cSRoman Divacky /// clone - Make a copy of this tree and all of its children.
1826f22ef01cSRoman Divacky ///
clone() const18274ba319b5SDimitry Andric TreePatternNodePtr TreePatternNode::clone() const {
18284ba319b5SDimitry Andric   TreePatternNodePtr New;
1829f22ef01cSRoman Divacky   if (isLeaf()) {
18304ba319b5SDimitry Andric     New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
1831f22ef01cSRoman Divacky   } else {
18324ba319b5SDimitry Andric     std::vector<TreePatternNodePtr> CChildren;
1833f22ef01cSRoman Divacky     CChildren.reserve(Children.size());
1834f22ef01cSRoman Divacky     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1835f22ef01cSRoman Divacky       CChildren.push_back(getChild(i)->clone());
18364ba319b5SDimitry Andric     New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
18374ba319b5SDimitry Andric                                             getNumTypes());
1838f22ef01cSRoman Divacky   }
1839f22ef01cSRoman Divacky   New->setName(getName());
1840*b5893f02SDimitry Andric   New->setNamesAsPredicateArg(getNamesAsPredicateArg());
1841f22ef01cSRoman Divacky   New->Types = Types;
1842*b5893f02SDimitry Andric   New->setPredicateCalls(getPredicateCalls());
1843f22ef01cSRoman Divacky   New->setTransformFn(getTransformFn());
1844f22ef01cSRoman Divacky   return New;
1845f22ef01cSRoman Divacky }
1846f22ef01cSRoman Divacky 
1847f22ef01cSRoman Divacky /// RemoveAllTypes - Recursively strip all the types of this tree.
RemoveAllTypes()1848f22ef01cSRoman Divacky void TreePatternNode::RemoveAllTypes() {
18497d523365SDimitry Andric   // Reset to unknown type.
18502cab237bSDimitry Andric   std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
1851f22ef01cSRoman Divacky   if (isLeaf()) return;
1852f22ef01cSRoman Divacky   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1853f22ef01cSRoman Divacky     getChild(i)->RemoveAllTypes();
1854f22ef01cSRoman Divacky }
1855f22ef01cSRoman Divacky 
1856f22ef01cSRoman Divacky 
1857f22ef01cSRoman Divacky /// SubstituteFormalArguments - Replace the formal arguments in this tree
1858f22ef01cSRoman Divacky /// with actual values specified by ArgMap.
SubstituteFormalArguments(std::map<std::string,TreePatternNodePtr> & ArgMap)18594ba319b5SDimitry Andric void TreePatternNode::SubstituteFormalArguments(
18604ba319b5SDimitry Andric     std::map<std::string, TreePatternNodePtr> &ArgMap) {
1861f22ef01cSRoman Divacky   if (isLeaf()) return;
1862f22ef01cSRoman Divacky 
1863f22ef01cSRoman Divacky   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1864f22ef01cSRoman Divacky     TreePatternNode *Child = getChild(i);
1865f22ef01cSRoman Divacky     if (Child->isLeaf()) {
1866f22ef01cSRoman Divacky       Init *Val = Child->getLeafValue();
186791bc56edSDimitry Andric       // Note that, when substituting into an output pattern, Val might be an
186891bc56edSDimitry Andric       // UnsetInit.
186991bc56edSDimitry Andric       if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
187091bc56edSDimitry Andric           cast<DefInit>(Val)->getDef()->getName() == "node")) {
1871f22ef01cSRoman Divacky         // We found a use of a formal argument, replace it with its value.
18724ba319b5SDimitry Andric         TreePatternNodePtr NewChild = ArgMap[Child->getName()];
1873f22ef01cSRoman Divacky         assert(NewChild && "Couldn't find formal argument!");
1874*b5893f02SDimitry Andric         assert((Child->getPredicateCalls().empty() ||
1875*b5893f02SDimitry Andric                 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
1876f22ef01cSRoman Divacky                "Non-empty child predicate clobbered!");
18774ba319b5SDimitry Andric         setChild(i, std::move(NewChild));
1878f22ef01cSRoman Divacky       }
1879f22ef01cSRoman Divacky     } else {
1880f22ef01cSRoman Divacky       getChild(i)->SubstituteFormalArguments(ArgMap);
1881f22ef01cSRoman Divacky     }
1882f22ef01cSRoman Divacky   }
1883f22ef01cSRoman Divacky }
1884f22ef01cSRoman Divacky 
1885f22ef01cSRoman Divacky 
1886f22ef01cSRoman Divacky /// InlinePatternFragments - If this pattern refers to any pattern
18874ba319b5SDimitry Andric /// fragments, return the set of inlined versions (this can be more than
18884ba319b5SDimitry Andric /// one if a PatFrags record has multiple alternatives).
InlinePatternFragments(TreePatternNodePtr T,TreePattern & TP,std::vector<TreePatternNodePtr> & OutAlternatives)18894ba319b5SDimitry Andric void TreePatternNode::InlinePatternFragments(
18904ba319b5SDimitry Andric   TreePatternNodePtr T, TreePattern &TP,
18914ba319b5SDimitry Andric   std::vector<TreePatternNodePtr> &OutAlternatives) {
18923861d79fSDimitry Andric 
18934ba319b5SDimitry Andric   if (TP.hasError())
18944ba319b5SDimitry Andric     return;
18954ba319b5SDimitry Andric 
18964ba319b5SDimitry Andric   if (isLeaf()) {
18974ba319b5SDimitry Andric     OutAlternatives.push_back(T);  // nothing to do.
18984ba319b5SDimitry Andric     return;
18994ba319b5SDimitry Andric   }
19004ba319b5SDimitry Andric 
1901f22ef01cSRoman Divacky   Record *Op = getOperator();
1902f22ef01cSRoman Divacky 
19034ba319b5SDimitry Andric   if (!Op->isSubClassOf("PatFrags")) {
19044ba319b5SDimitry Andric     if (getNumChildren() == 0) {
19054ba319b5SDimitry Andric       OutAlternatives.push_back(T);
19064ba319b5SDimitry Andric       return;
19074ba319b5SDimitry Andric     }
1908f22ef01cSRoman Divacky 
19094ba319b5SDimitry Andric     // Recursively inline children nodes.
19104ba319b5SDimitry Andric     std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
19114ba319b5SDimitry Andric     ChildAlternatives.resize(getNumChildren());
19124ba319b5SDimitry Andric     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
19134ba319b5SDimitry Andric       TreePatternNodePtr Child = getChildShared(i);
19144ba319b5SDimitry Andric       Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
19154ba319b5SDimitry Andric       // If there are no alternatives for any child, there are no
19164ba319b5SDimitry Andric       // alternatives for this expression as whole.
19174ba319b5SDimitry Andric       if (ChildAlternatives[i].empty())
19184ba319b5SDimitry Andric         return;
19194ba319b5SDimitry Andric 
19204ba319b5SDimitry Andric       for (auto NewChild : ChildAlternatives[i])
1921*b5893f02SDimitry Andric         assert((Child->getPredicateCalls().empty() ||
1922*b5893f02SDimitry Andric                 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
1923f22ef01cSRoman Divacky                "Non-empty child predicate clobbered!");
1924f22ef01cSRoman Divacky     }
19254ba319b5SDimitry Andric 
19264ba319b5SDimitry Andric     // The end result is an all-pairs construction of the resultant pattern.
19274ba319b5SDimitry Andric     std::vector<unsigned> Idxs;
19284ba319b5SDimitry Andric     Idxs.resize(ChildAlternatives.size());
19294ba319b5SDimitry Andric     bool NotDone;
19304ba319b5SDimitry Andric     do {
19314ba319b5SDimitry Andric       // Create the variant and add it to the output list.
19324ba319b5SDimitry Andric       std::vector<TreePatternNodePtr> NewChildren;
19334ba319b5SDimitry Andric       for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
19344ba319b5SDimitry Andric         NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
19354ba319b5SDimitry Andric       TreePatternNodePtr R = std::make_shared<TreePatternNode>(
19364ba319b5SDimitry Andric           getOperator(), std::move(NewChildren), getNumTypes());
19374ba319b5SDimitry Andric 
19384ba319b5SDimitry Andric       // Copy over properties.
19394ba319b5SDimitry Andric       R->setName(getName());
1940*b5893f02SDimitry Andric       R->setNamesAsPredicateArg(getNamesAsPredicateArg());
1941*b5893f02SDimitry Andric       R->setPredicateCalls(getPredicateCalls());
19424ba319b5SDimitry Andric       R->setTransformFn(getTransformFn());
19434ba319b5SDimitry Andric       for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
19444ba319b5SDimitry Andric         R->setType(i, getExtType(i));
1945*b5893f02SDimitry Andric       for (unsigned i = 0, e = getNumResults(); i != e; ++i)
1946*b5893f02SDimitry Andric         R->setResultIndex(i, getResultIndex(i));
19474ba319b5SDimitry Andric 
19484ba319b5SDimitry Andric       // Register alternative.
19494ba319b5SDimitry Andric       OutAlternatives.push_back(R);
19504ba319b5SDimitry Andric 
19514ba319b5SDimitry Andric       // Increment indices to the next permutation by incrementing the
19524ba319b5SDimitry Andric       // indices from last index backward, e.g., generate the sequence
19534ba319b5SDimitry Andric       // [0, 0], [0, 1], [1, 0], [1, 1].
19544ba319b5SDimitry Andric       int IdxsIdx;
19554ba319b5SDimitry Andric       for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
19564ba319b5SDimitry Andric         if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
19574ba319b5SDimitry Andric           Idxs[IdxsIdx] = 0;
19584ba319b5SDimitry Andric         else
19594ba319b5SDimitry Andric           break;
19604ba319b5SDimitry Andric       }
19614ba319b5SDimitry Andric       NotDone = (IdxsIdx >= 0);
19624ba319b5SDimitry Andric     } while (NotDone);
19634ba319b5SDimitry Andric 
19644ba319b5SDimitry Andric     return;
1965f22ef01cSRoman Divacky   }
1966f22ef01cSRoman Divacky 
1967f22ef01cSRoman Divacky   // Otherwise, we found a reference to a fragment.  First, look up its
1968f22ef01cSRoman Divacky   // TreePattern record.
1969f22ef01cSRoman Divacky   TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1970f22ef01cSRoman Divacky 
1971f22ef01cSRoman Divacky   // Verify that we are passing the right number of operands.
19723861d79fSDimitry Andric   if (Frag->getNumArgs() != Children.size()) {
1973f22ef01cSRoman Divacky     TP.error("'" + Op->getName() + "' fragment requires " +
1974fe4fed2eSDimitry Andric              Twine(Frag->getNumArgs()) + " operands!");
19754ba319b5SDimitry Andric     return;
19763861d79fSDimitry Andric   }
1977f22ef01cSRoman Divacky 
1978*b5893f02SDimitry Andric   TreePredicateFn PredFn(Frag);
1979*b5893f02SDimitry Andric   unsigned Scope = 0;
1980*b5893f02SDimitry Andric   if (TreePredicateFn(Frag).usesOperands())
1981*b5893f02SDimitry Andric     Scope = TP.getDAGPatterns().allocateScope();
1982*b5893f02SDimitry Andric 
19834ba319b5SDimitry Andric   // Compute the map of formal to actual arguments.
19844ba319b5SDimitry Andric   std::map<std::string, TreePatternNodePtr> ArgMap;
19854ba319b5SDimitry Andric   for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
1986*b5893f02SDimitry Andric     TreePatternNodePtr Child = getChildShared(i);
1987*b5893f02SDimitry Andric     if (Scope != 0) {
1988*b5893f02SDimitry Andric       Child = Child->clone();
1989*b5893f02SDimitry Andric       Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
1990*b5893f02SDimitry Andric     }
19914ba319b5SDimitry Andric     ArgMap[Frag->getArgName(i)] = Child;
19924ba319b5SDimitry Andric   }
19934ba319b5SDimitry Andric 
19944ba319b5SDimitry Andric   // Loop over all fragment alternatives.
19954ba319b5SDimitry Andric   for (auto Alternative : Frag->getTrees()) {
19964ba319b5SDimitry Andric     TreePatternNodePtr FragTree = Alternative->clone();
1997f22ef01cSRoman Divacky 
19983b0f4066SDimitry Andric     if (!PredFn.isAlwaysTrue())
1999*b5893f02SDimitry Andric       FragTree->addPredicateCall(PredFn, Scope);
2000f22ef01cSRoman Divacky 
2001f22ef01cSRoman Divacky     // Resolve formal arguments to their actual value.
20024ba319b5SDimitry Andric     if (Frag->getNumArgs())
2003f22ef01cSRoman Divacky       FragTree->SubstituteFormalArguments(ArgMap);
2004f22ef01cSRoman Divacky 
20054ba319b5SDimitry Andric     // Transfer types.  Note that the resolved alternative may have fewer
20064ba319b5SDimitry Andric     // (but not more) results than the PatFrags node.
2007f22ef01cSRoman Divacky     FragTree->setName(getName());
20084ba319b5SDimitry Andric     for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2009f22ef01cSRoman Divacky       FragTree->UpdateNodeType(i, getExtType(i), TP);
2010f22ef01cSRoman Divacky 
2011f22ef01cSRoman Divacky     // Transfer in the old predicates.
2012*b5893f02SDimitry Andric     for (const TreePredicateCall &Pred : getPredicateCalls())
2013*b5893f02SDimitry Andric       FragTree->addPredicateCall(Pred);
2014f22ef01cSRoman Divacky 
2015f22ef01cSRoman Divacky     // The fragment we inlined could have recursive inlining that is needed.  See
2016f22ef01cSRoman Divacky     // if there are any pattern fragments in it and inline them as needed.
20174ba319b5SDimitry Andric     FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
20184ba319b5SDimitry Andric   }
2019f22ef01cSRoman Divacky }
2020f22ef01cSRoman Divacky 
2021f22ef01cSRoman Divacky /// getImplicitType - Check to see if the specified record has an implicit
2022f22ef01cSRoman Divacky /// type which should be applied to it.  This will infer the type of register
2023f22ef01cSRoman Divacky /// references from the register file information, for example.
2024f22ef01cSRoman Divacky ///
2025139f7f9bSDimitry Andric /// When Unnamed is set, return the type of a DAG operand with no name, such as
2026139f7f9bSDimitry Andric /// the F8RC register class argument in:
2027139f7f9bSDimitry Andric ///
2028139f7f9bSDimitry Andric ///   (COPY_TO_REGCLASS GPR:$src, F8RC)
2029139f7f9bSDimitry Andric ///
2030139f7f9bSDimitry Andric /// When Unnamed is false, return the type of a named DAG operand such as the
2031139f7f9bSDimitry Andric /// GPR:$src operand above.
2032139f7f9bSDimitry Andric ///
getImplicitType(Record * R,unsigned ResNo,bool NotRegisters,bool Unnamed,TreePattern & TP)20332cab237bSDimitry Andric static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2034139f7f9bSDimitry Andric                                        bool NotRegisters,
2035139f7f9bSDimitry Andric                                        bool Unnamed,
2036139f7f9bSDimitry Andric                                        TreePattern &TP) {
20372cab237bSDimitry Andric   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
20382cab237bSDimitry Andric 
203917a519f9SDimitry Andric   // Check to see if this is a register operand.
204017a519f9SDimitry Andric   if (R->isSubClassOf("RegisterOperand")) {
204117a519f9SDimitry Andric     assert(ResNo == 0 && "Regoperand ref only has one result!");
204217a519f9SDimitry Andric     if (NotRegisters)
20432cab237bSDimitry Andric       return TypeSetByHwMode(); // Unknown.
204417a519f9SDimitry Andric     Record *RegClass = R->getValueAsDef("RegClass");
204517a519f9SDimitry Andric     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
20462cab237bSDimitry Andric     return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
204717a519f9SDimitry Andric   }
204817a519f9SDimitry Andric 
2049f22ef01cSRoman Divacky   // Check to see if this is a register or a register class.
2050f22ef01cSRoman Divacky   if (R->isSubClassOf("RegisterClass")) {
2051f22ef01cSRoman Divacky     assert(ResNo == 0 && "Regclass ref only has one result!");
2052139f7f9bSDimitry Andric     // An unnamed register class represents itself as an i32 immediate, for
2053139f7f9bSDimitry Andric     // example on a COPY_TO_REGCLASS instruction.
2054139f7f9bSDimitry Andric     if (Unnamed)
20552cab237bSDimitry Andric       return TypeSetByHwMode(MVT::i32);
2056139f7f9bSDimitry Andric 
2057139f7f9bSDimitry Andric     // In a named operand, the register class provides the possible set of
2058139f7f9bSDimitry Andric     // types.
2059f22ef01cSRoman Divacky     if (NotRegisters)
20602cab237bSDimitry Andric       return TypeSetByHwMode(); // Unknown.
2061f22ef01cSRoman Divacky     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
20622cab237bSDimitry Andric     return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
2063f22ef01cSRoman Divacky   }
2064f22ef01cSRoman Divacky 
20654ba319b5SDimitry Andric   if (R->isSubClassOf("PatFrags")) {
2066f22ef01cSRoman Divacky     assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
2067f22ef01cSRoman Divacky     // Pattern fragment types will be resolved when they are inlined.
20682cab237bSDimitry Andric     return TypeSetByHwMode(); // Unknown.
2069f22ef01cSRoman Divacky   }
2070f22ef01cSRoman Divacky 
2071f22ef01cSRoman Divacky   if (R->isSubClassOf("Register")) {
2072f22ef01cSRoman Divacky     assert(ResNo == 0 && "Registers only produce one result!");
2073f22ef01cSRoman Divacky     if (NotRegisters)
20742cab237bSDimitry Andric       return TypeSetByHwMode(); // Unknown.
2075f22ef01cSRoman Divacky     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
20762cab237bSDimitry Andric     return TypeSetByHwMode(T.getRegisterVTs(R));
2077f22ef01cSRoman Divacky   }
2078f22ef01cSRoman Divacky 
2079f22ef01cSRoman Divacky   if (R->isSubClassOf("SubRegIndex")) {
2080f22ef01cSRoman Divacky     assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
20812cab237bSDimitry Andric     return TypeSetByHwMode(MVT::i32);
2082f22ef01cSRoman Divacky   }
2083f22ef01cSRoman Divacky 
2084139f7f9bSDimitry Andric   if (R->isSubClassOf("ValueType")) {
2085f22ef01cSRoman Divacky     assert(ResNo == 0 && "This node only has one result!");
2086139f7f9bSDimitry Andric     // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2087139f7f9bSDimitry Andric     //
2088139f7f9bSDimitry Andric     //   (sext_inreg GPR:$src, i16)
2089139f7f9bSDimitry Andric     //                         ~~~
2090139f7f9bSDimitry Andric     if (Unnamed)
20912cab237bSDimitry Andric       return TypeSetByHwMode(MVT::Other);
2092139f7f9bSDimitry Andric     // With a name, the ValueType simply provides the type of the named
2093139f7f9bSDimitry Andric     // variable.
2094139f7f9bSDimitry Andric     //
2095139f7f9bSDimitry Andric     //   (sext_inreg i32:$src, i16)
2096139f7f9bSDimitry Andric     //               ~~~~~~~~
2097139f7f9bSDimitry Andric     if (NotRegisters)
20982cab237bSDimitry Andric       return TypeSetByHwMode(); // Unknown.
20992cab237bSDimitry Andric     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
21002cab237bSDimitry Andric     return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
2101139f7f9bSDimitry Andric   }
2102139f7f9bSDimitry Andric 
2103139f7f9bSDimitry Andric   if (R->isSubClassOf("CondCode")) {
2104139f7f9bSDimitry Andric     assert(ResNo == 0 && "This node only has one result!");
2105139f7f9bSDimitry Andric     // Using a CondCodeSDNode.
21062cab237bSDimitry Andric     return TypeSetByHwMode(MVT::Other);
2107f22ef01cSRoman Divacky   }
2108f22ef01cSRoman Divacky 
2109f22ef01cSRoman Divacky   if (R->isSubClassOf("ComplexPattern")) {
2110f22ef01cSRoman Divacky     assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
2111f22ef01cSRoman Divacky     if (NotRegisters)
21122cab237bSDimitry Andric       return TypeSetByHwMode(); // Unknown.
21132cab237bSDimitry Andric     return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
2114f22ef01cSRoman Divacky   }
2115f22ef01cSRoman Divacky   if (R->isSubClassOf("PointerLikeRegClass")) {
2116f22ef01cSRoman Divacky     assert(ResNo == 0 && "Regclass can only have one result!");
21172cab237bSDimitry Andric     TypeSetByHwMode VTS(MVT::iPTR);
21182cab237bSDimitry Andric     TP.getInfer().expandOverloads(VTS);
21192cab237bSDimitry Andric     return VTS;
2120f22ef01cSRoman Divacky   }
2121f22ef01cSRoman Divacky 
2122f22ef01cSRoman Divacky   if (R->getName() == "node" || R->getName() == "srcvalue" ||
2123f22ef01cSRoman Divacky       R->getName() == "zero_reg") {
2124f22ef01cSRoman Divacky     // Placeholder.
21252cab237bSDimitry Andric     return TypeSetByHwMode(); // Unknown.
2126f22ef01cSRoman Divacky   }
2127f22ef01cSRoman Divacky 
21282cab237bSDimitry Andric   if (R->isSubClassOf("Operand")) {
21292cab237bSDimitry Andric     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
21302cab237bSDimitry Andric     Record *T = R->getValueAsDef("Type");
21312cab237bSDimitry Andric     return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
21322cab237bSDimitry Andric   }
213391bc56edSDimitry Andric 
2134f22ef01cSRoman Divacky   TP.error("Unknown node flavor used in pattern: " + R->getName());
21352cab237bSDimitry Andric   return TypeSetByHwMode(MVT::Other);
2136f22ef01cSRoman Divacky }
2137f22ef01cSRoman Divacky 
2138f22ef01cSRoman Divacky 
2139f22ef01cSRoman Divacky /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2140f22ef01cSRoman Divacky /// CodeGenIntrinsic information for it, otherwise return a null pointer.
2141f22ef01cSRoman Divacky const CodeGenIntrinsic *TreePatternNode::
getIntrinsicInfo(const CodeGenDAGPatterns & CDP) const2142f22ef01cSRoman Divacky getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2143f22ef01cSRoman Divacky   if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2144f22ef01cSRoman Divacky       getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2145f22ef01cSRoman Divacky       getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
214691bc56edSDimitry Andric     return nullptr;
2147f22ef01cSRoman Divacky 
21483861d79fSDimitry Andric   unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
2149f22ef01cSRoman Divacky   return &CDP.getIntrinsicInfo(IID);
2150f22ef01cSRoman Divacky }
2151f22ef01cSRoman Divacky 
2152f22ef01cSRoman Divacky /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2153f22ef01cSRoman Divacky /// return the ComplexPattern information, otherwise return null.
2154f22ef01cSRoman Divacky const ComplexPattern *
getComplexPatternInfo(const CodeGenDAGPatterns & CGP) const2155f22ef01cSRoman Divacky TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
215691bc56edSDimitry Andric   Record *Rec;
215791bc56edSDimitry Andric   if (isLeaf()) {
21583861d79fSDimitry Andric     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
215991bc56edSDimitry Andric     if (!DI)
216091bc56edSDimitry Andric       return nullptr;
216191bc56edSDimitry Andric     Rec = DI->getDef();
216291bc56edSDimitry Andric   } else
216391bc56edSDimitry Andric     Rec = getOperator();
216491bc56edSDimitry Andric 
216591bc56edSDimitry Andric   if (!Rec->isSubClassOf("ComplexPattern"))
216691bc56edSDimitry Andric     return nullptr;
216791bc56edSDimitry Andric   return &CGP.getComplexPattern(Rec);
216891bc56edSDimitry Andric }
216991bc56edSDimitry Andric 
getNumMIResults(const CodeGenDAGPatterns & CGP) const217091bc56edSDimitry Andric unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
217191bc56edSDimitry Andric   // A ComplexPattern specifically declares how many results it fills in.
217291bc56edSDimitry Andric   if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
217391bc56edSDimitry Andric     return CP->getNumOperands();
217491bc56edSDimitry Andric 
217591bc56edSDimitry Andric   // If MIOperandInfo is specified, that gives the count.
217691bc56edSDimitry Andric   if (isLeaf()) {
217791bc56edSDimitry Andric     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
217891bc56edSDimitry Andric     if (DI && DI->getDef()->isSubClassOf("Operand")) {
217991bc56edSDimitry Andric       DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
218091bc56edSDimitry Andric       if (MIOps->getNumArgs())
218191bc56edSDimitry Andric         return MIOps->getNumArgs();
218291bc56edSDimitry Andric     }
218391bc56edSDimitry Andric   }
218491bc56edSDimitry Andric 
218591bc56edSDimitry Andric   // Otherwise there is just one result.
218691bc56edSDimitry Andric   return 1;
2187f22ef01cSRoman Divacky }
2188f22ef01cSRoman Divacky 
2189f22ef01cSRoman Divacky /// NodeHasProperty - Return true if this node has the specified property.
NodeHasProperty(SDNP Property,const CodeGenDAGPatterns & CGP) const2190f22ef01cSRoman Divacky bool TreePatternNode::NodeHasProperty(SDNP Property,
2191f22ef01cSRoman Divacky                                       const CodeGenDAGPatterns &CGP) const {
2192f22ef01cSRoman Divacky   if (isLeaf()) {
2193f22ef01cSRoman Divacky     if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2194f22ef01cSRoman Divacky       return CP->hasProperty(Property);
2195da09e106SDimitry Andric 
2196f22ef01cSRoman Divacky     return false;
2197f22ef01cSRoman Divacky   }
2198f22ef01cSRoman Divacky 
2199da09e106SDimitry Andric   if (Property != SDNPHasChain) {
2200da09e106SDimitry Andric     // The chain proprety is already present on the different intrinsic node
2201da09e106SDimitry Andric     // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2202da09e106SDimitry Andric     // on the intrinsic. Anything else is specific to the individual intrinsic.
2203da09e106SDimitry Andric     if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2204da09e106SDimitry Andric       return Int->hasProperty(Property);
2205da09e106SDimitry Andric   }
2206da09e106SDimitry Andric 
2207da09e106SDimitry Andric   if (!Operator->isSubClassOf("SDPatternOperator"))
2208da09e106SDimitry Andric     return false;
2209f22ef01cSRoman Divacky 
2210f22ef01cSRoman Divacky   return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2211f22ef01cSRoman Divacky }
2212f22ef01cSRoman Divacky 
2213f22ef01cSRoman Divacky 
2214f22ef01cSRoman Divacky 
2215f22ef01cSRoman Divacky 
2216f22ef01cSRoman Divacky /// TreeHasProperty - Return true if any node in this tree has the specified
2217f22ef01cSRoman Divacky /// property.
TreeHasProperty(SDNP Property,const CodeGenDAGPatterns & CGP) const2218f22ef01cSRoman Divacky bool TreePatternNode::TreeHasProperty(SDNP Property,
2219f22ef01cSRoman Divacky                                       const CodeGenDAGPatterns &CGP) const {
2220f22ef01cSRoman Divacky   if (NodeHasProperty(Property, CGP))
2221f22ef01cSRoman Divacky     return true;
2222f22ef01cSRoman Divacky   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2223f22ef01cSRoman Divacky     if (getChild(i)->TreeHasProperty(Property, CGP))
2224f22ef01cSRoman Divacky       return true;
2225f22ef01cSRoman Divacky   return false;
2226f22ef01cSRoman Divacky }
2227f22ef01cSRoman Divacky 
2228f22ef01cSRoman Divacky /// isCommutativeIntrinsic - Return true if the node corresponds to a
2229f22ef01cSRoman Divacky /// commutative intrinsic.
2230f22ef01cSRoman Divacky bool
isCommutativeIntrinsic(const CodeGenDAGPatterns & CDP) const2231f22ef01cSRoman Divacky TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2232f22ef01cSRoman Divacky   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2233f22ef01cSRoman Divacky     return Int->isCommutative;
2234f22ef01cSRoman Divacky   return false;
2235f22ef01cSRoman Divacky }
2236f22ef01cSRoman Divacky 
isOperandClass(const TreePatternNode * N,StringRef Class)223739d628a0SDimitry Andric static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
223839d628a0SDimitry Andric   if (!N->isLeaf())
223939d628a0SDimitry Andric     return N->getOperator()->isSubClassOf(Class);
224039d628a0SDimitry Andric 
224139d628a0SDimitry Andric   DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
224239d628a0SDimitry Andric   if (DI && DI->getDef()->isSubClassOf(Class))
224339d628a0SDimitry Andric     return true;
224439d628a0SDimitry Andric 
224539d628a0SDimitry Andric   return false;
224639d628a0SDimitry Andric }
224739d628a0SDimitry Andric 
emitTooManyOperandsError(TreePattern & TP,StringRef InstName,unsigned Expected,unsigned Actual)224839d628a0SDimitry Andric static void emitTooManyOperandsError(TreePattern &TP,
224939d628a0SDimitry Andric                                      StringRef InstName,
225039d628a0SDimitry Andric                                      unsigned Expected,
225139d628a0SDimitry Andric                                      unsigned Actual) {
225239d628a0SDimitry Andric   TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
225339d628a0SDimitry Andric            " operands but expected only " + Twine(Expected) + "!");
225439d628a0SDimitry Andric }
225539d628a0SDimitry Andric 
emitTooFewOperandsError(TreePattern & TP,StringRef InstName,unsigned Actual)225639d628a0SDimitry Andric static void emitTooFewOperandsError(TreePattern &TP,
225739d628a0SDimitry Andric                                     StringRef InstName,
225839d628a0SDimitry Andric                                     unsigned Actual) {
225939d628a0SDimitry Andric   TP.error("Instruction '" + InstName +
226039d628a0SDimitry Andric            "' expects more than the provided " + Twine(Actual) + " operands!");
226139d628a0SDimitry Andric }
2262f22ef01cSRoman Divacky 
2263f22ef01cSRoman Divacky /// ApplyTypeConstraints - Apply all of the type constraints relevant to
2264f22ef01cSRoman Divacky /// this node and its children in the tree.  This returns true if it makes a
22653861d79fSDimitry Andric /// change, false otherwise.  If a type contradiction is found, flag an error.
ApplyTypeConstraints(TreePattern & TP,bool NotRegisters)2266f22ef01cSRoman Divacky bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
22673861d79fSDimitry Andric   if (TP.hasError())
22683861d79fSDimitry Andric     return false;
22693861d79fSDimitry Andric 
2270f22ef01cSRoman Divacky   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2271f22ef01cSRoman Divacky   if (isLeaf()) {
22723861d79fSDimitry Andric     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
2273f22ef01cSRoman Divacky       // If it's a regclass or something else known, include the type.
2274f22ef01cSRoman Divacky       bool MadeChange = false;
2275f22ef01cSRoman Divacky       for (unsigned i = 0, e = Types.size(); i != e; ++i)
2276f22ef01cSRoman Divacky         MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
2277139f7f9bSDimitry Andric                                                         NotRegisters,
2278139f7f9bSDimitry Andric                                                         !hasName(), TP), TP);
2279f22ef01cSRoman Divacky       return MadeChange;
2280f22ef01cSRoman Divacky     }
2281f22ef01cSRoman Divacky 
22823861d79fSDimitry Andric     if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
2283f22ef01cSRoman Divacky       assert(Types.size() == 1 && "Invalid IntInit");
2284f22ef01cSRoman Divacky 
2285f22ef01cSRoman Divacky       // Int inits are always integers. :)
22862cab237bSDimitry Andric       bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
2287f22ef01cSRoman Divacky 
22882cab237bSDimitry Andric       if (!TP.getInfer().isConcrete(Types[0], false))
2289f22ef01cSRoman Divacky         return MadeChange;
2290f22ef01cSRoman Divacky 
22912cab237bSDimitry Andric       ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
22922cab237bSDimitry Andric       for (auto &P : VVT) {
22932cab237bSDimitry Andric         MVT::SimpleValueType VT = P.second.SimpleTy;
2294f22ef01cSRoman Divacky         if (VT == MVT::iPTR || VT == MVT::iPTRAny)
22952cab237bSDimitry Andric           continue;
2296f785676fSDimitry Andric         unsigned Size = MVT(VT).getSizeInBits();
2297f22ef01cSRoman Divacky         // Make sure that the value is representable for this type.
22982cab237bSDimitry Andric         if (Size >= 32)
22992cab237bSDimitry Andric           continue;
23002cab237bSDimitry Andric         // Check that the value doesn't use more bits than we have. It must
23012cab237bSDimitry Andric         // either be a sign- or zero-extended equivalent of the original.
23023861d79fSDimitry Andric         int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
23032cab237bSDimitry Andric         if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
23042cab237bSDimitry Andric             SignBitAndAbove == 1)
23052cab237bSDimitry Andric           continue;
2306f22ef01cSRoman Divacky 
2307fe4fed2eSDimitry Andric         TP.error("Integer value '" + Twine(II->getValue()) +
23082cab237bSDimitry Andric                  "' is out of range for type '" + getEnumName(VT) + "'!");
23092cab237bSDimitry Andric         break;
2310f22ef01cSRoman Divacky       }
23112cab237bSDimitry Andric       return MadeChange;
23122cab237bSDimitry Andric     }
23132cab237bSDimitry Andric 
2314f22ef01cSRoman Divacky     return false;
2315f22ef01cSRoman Divacky   }
2316f22ef01cSRoman Divacky 
2317f22ef01cSRoman Divacky   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
2318f22ef01cSRoman Divacky     bool MadeChange = false;
2319f22ef01cSRoman Divacky 
2320f22ef01cSRoman Divacky     // Apply the result type to the node.
2321f22ef01cSRoman Divacky     unsigned NumRetVTs = Int->IS.RetVTs.size();
2322f22ef01cSRoman Divacky     unsigned NumParamVTs = Int->IS.ParamVTs.size();
2323f22ef01cSRoman Divacky 
2324f22ef01cSRoman Divacky     for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
2325f22ef01cSRoman Divacky       MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
2326f22ef01cSRoman Divacky 
23273861d79fSDimitry Andric     if (getNumChildren() != NumParamVTs + 1) {
2328fe4fed2eSDimitry Andric       TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2329fe4fed2eSDimitry Andric                " operands, not " + Twine(getNumChildren() - 1) + " operands!");
23303861d79fSDimitry Andric       return false;
23313861d79fSDimitry Andric     }
2332f22ef01cSRoman Divacky 
2333f22ef01cSRoman Divacky     // Apply type info to the intrinsic ID.
2334f22ef01cSRoman Divacky     MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
2335f22ef01cSRoman Divacky 
2336f22ef01cSRoman Divacky     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
2337f22ef01cSRoman Divacky       MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
2338f22ef01cSRoman Divacky 
2339f22ef01cSRoman Divacky       MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
2340f22ef01cSRoman Divacky       assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2341f22ef01cSRoman Divacky       MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
2342f22ef01cSRoman Divacky     }
2343f22ef01cSRoman Divacky     return MadeChange;
2344f22ef01cSRoman Divacky   }
2345f22ef01cSRoman Divacky 
2346f22ef01cSRoman Divacky   if (getOperator()->isSubClassOf("SDNode")) {
2347f22ef01cSRoman Divacky     const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
2348f22ef01cSRoman Divacky 
2349f22ef01cSRoman Divacky     // Check that the number of operands is sane.  Negative operands -> varargs.
2350f22ef01cSRoman Divacky     if (NI.getNumOperands() >= 0 &&
23513861d79fSDimitry Andric         getNumChildren() != (unsigned)NI.getNumOperands()) {
2352f22ef01cSRoman Divacky       TP.error(getOperator()->getName() + " node requires exactly " +
2353fe4fed2eSDimitry Andric                Twine(NI.getNumOperands()) + " operands!");
23543861d79fSDimitry Andric       return false;
23553861d79fSDimitry Andric     }
2356f22ef01cSRoman Divacky 
23572cab237bSDimitry Andric     bool MadeChange = false;
2358f22ef01cSRoman Divacky     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2359f22ef01cSRoman Divacky       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
23602cab237bSDimitry Andric     MadeChange |= NI.ApplyTypeConstraints(this, TP);
2361f22ef01cSRoman Divacky     return MadeChange;
2362f22ef01cSRoman Divacky   }
2363f22ef01cSRoman Divacky 
2364f22ef01cSRoman Divacky   if (getOperator()->isSubClassOf("Instruction")) {
2365f22ef01cSRoman Divacky     const DAGInstruction &Inst = CDP.getInstruction(getOperator());
2366f22ef01cSRoman Divacky     CodeGenInstruction &InstInfo =
2367f22ef01cSRoman Divacky       CDP.getTargetInfo().getInstruction(getOperator());
2368f22ef01cSRoman Divacky 
2369f22ef01cSRoman Divacky     bool MadeChange = false;
2370f22ef01cSRoman Divacky 
2371f22ef01cSRoman Divacky     // Apply the result types to the node, these come from the things in the
2372f22ef01cSRoman Divacky     // (outs) list of the instruction.
2373ff0cc061SDimitry Andric     unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2374ff0cc061SDimitry Andric                                         Inst.getNumResults());
2375139f7f9bSDimitry Andric     for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2376139f7f9bSDimitry Andric       MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
2377f22ef01cSRoman Divacky 
2378f22ef01cSRoman Divacky     // If the instruction has implicit defs, we apply the first one as a result.
2379f22ef01cSRoman Divacky     // FIXME: This sucks, it should apply all implicit defs.
2380f22ef01cSRoman Divacky     if (!InstInfo.ImplicitDefs.empty()) {
2381f22ef01cSRoman Divacky       unsigned ResNo = NumResultsToAdd;
2382f22ef01cSRoman Divacky 
2383f22ef01cSRoman Divacky       // FIXME: Generalize to multiple possible types and multiple possible
2384f22ef01cSRoman Divacky       // ImplicitDefs.
2385f22ef01cSRoman Divacky       MVT::SimpleValueType VT =
2386f22ef01cSRoman Divacky         InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
2387f22ef01cSRoman Divacky 
2388f22ef01cSRoman Divacky       if (VT != MVT::Other)
2389f22ef01cSRoman Divacky         MadeChange |= UpdateNodeType(ResNo, VT, TP);
2390f22ef01cSRoman Divacky     }
2391f22ef01cSRoman Divacky 
2392f22ef01cSRoman Divacky     // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2393f22ef01cSRoman Divacky     // be the same.
2394f22ef01cSRoman Divacky     if (getOperator()->getName() == "INSERT_SUBREG") {
2395f22ef01cSRoman Divacky       assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2396f22ef01cSRoman Divacky       MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2397f22ef01cSRoman Divacky       MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
239839d628a0SDimitry Andric     } else if (getOperator()->getName() == "REG_SEQUENCE") {
239939d628a0SDimitry Andric       // We need to do extra, custom typechecking for REG_SEQUENCE since it is
240039d628a0SDimitry Andric       // variadic.
240139d628a0SDimitry Andric 
240239d628a0SDimitry Andric       unsigned NChild = getNumChildren();
240339d628a0SDimitry Andric       if (NChild < 3) {
240439d628a0SDimitry Andric         TP.error("REG_SEQUENCE requires at least 3 operands!");
240539d628a0SDimitry Andric         return false;
240639d628a0SDimitry Andric       }
240739d628a0SDimitry Andric 
240839d628a0SDimitry Andric       if (NChild % 2 == 0) {
240939d628a0SDimitry Andric         TP.error("REG_SEQUENCE requires an odd number of operands!");
241039d628a0SDimitry Andric         return false;
241139d628a0SDimitry Andric       }
241239d628a0SDimitry Andric 
241339d628a0SDimitry Andric       if (!isOperandClass(getChild(0), "RegisterClass")) {
241439d628a0SDimitry Andric         TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
241539d628a0SDimitry Andric         return false;
241639d628a0SDimitry Andric       }
241739d628a0SDimitry Andric 
241839d628a0SDimitry Andric       for (unsigned I = 1; I < NChild; I += 2) {
241939d628a0SDimitry Andric         TreePatternNode *SubIdxChild = getChild(I + 1);
242039d628a0SDimitry Andric         if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
242139d628a0SDimitry Andric           TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2422fe4fed2eSDimitry Andric                    Twine(I + 1) + "!");
242339d628a0SDimitry Andric           return false;
242439d628a0SDimitry Andric         }
242539d628a0SDimitry Andric       }
2426f22ef01cSRoman Divacky     }
2427f22ef01cSRoman Divacky 
2428f22ef01cSRoman Divacky     unsigned ChildNo = 0;
2429f22ef01cSRoman Divacky     for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2430f22ef01cSRoman Divacky       Record *OperandNode = Inst.getOperand(i);
2431f22ef01cSRoman Divacky 
2432f22ef01cSRoman Divacky       // If the instruction expects a predicate or optional def operand, we
2433f22ef01cSRoman Divacky       // codegen this by setting the operand to it's default value if it has a
2434f22ef01cSRoman Divacky       // non-empty DefaultOps field.
24353861d79fSDimitry Andric       if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
2436f22ef01cSRoman Divacky           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2437f22ef01cSRoman Divacky         continue;
2438f22ef01cSRoman Divacky 
2439f22ef01cSRoman Divacky       // Verify that we didn't run out of provided operands.
24403861d79fSDimitry Andric       if (ChildNo >= getNumChildren()) {
244139d628a0SDimitry Andric         emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
24423861d79fSDimitry Andric         return false;
24433861d79fSDimitry Andric       }
2444f22ef01cSRoman Divacky 
2445f22ef01cSRoman Divacky       TreePatternNode *Child = getChild(ChildNo++);
2446f22ef01cSRoman Divacky       unsigned ChildResNo = 0;  // Instructions always use res #0 of their op.
2447f22ef01cSRoman Divacky 
2448139f7f9bSDimitry Andric       // If the operand has sub-operands, they may be provided by distinct
2449139f7f9bSDimitry Andric       // child patterns, so attempt to match each sub-operand separately.
2450139f7f9bSDimitry Andric       if (OperandNode->isSubClassOf("Operand")) {
2451139f7f9bSDimitry Andric         DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2452139f7f9bSDimitry Andric         if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2453139f7f9bSDimitry Andric           // But don't do that if the whole operand is being provided by
245491bc56edSDimitry Andric           // a single ComplexPattern-related Operand.
245591bc56edSDimitry Andric 
245691bc56edSDimitry Andric           if (Child->getNumMIResults(CDP) < NumArgs) {
2457139f7f9bSDimitry Andric             // Match first sub-operand against the child we already have.
2458139f7f9bSDimitry Andric             Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2459139f7f9bSDimitry Andric             MadeChange |=
2460139f7f9bSDimitry Andric               Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2461dff0c46cSDimitry Andric 
2462139f7f9bSDimitry Andric             // And the remaining sub-operands against subsequent children.
2463139f7f9bSDimitry Andric             for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2464139f7f9bSDimitry Andric               if (ChildNo >= getNumChildren()) {
246539d628a0SDimitry Andric                 emitTooFewOperandsError(TP, getOperator()->getName(),
246639d628a0SDimitry Andric                                         getNumChildren());
2467139f7f9bSDimitry Andric                 return false;
2468139f7f9bSDimitry Andric               }
2469139f7f9bSDimitry Andric               Child = getChild(ChildNo++);
2470139f7f9bSDimitry Andric 
2471139f7f9bSDimitry Andric               SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2472139f7f9bSDimitry Andric               MadeChange |=
2473139f7f9bSDimitry Andric                 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2474139f7f9bSDimitry Andric             }
2475139f7f9bSDimitry Andric             continue;
2476139f7f9bSDimitry Andric           }
2477139f7f9bSDimitry Andric         }
2478139f7f9bSDimitry Andric       }
2479139f7f9bSDimitry Andric 
2480139f7f9bSDimitry Andric       // If we didn't match by pieces above, attempt to match the whole
2481139f7f9bSDimitry Andric       // operand now.
2482139f7f9bSDimitry Andric       MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
2483f22ef01cSRoman Divacky     }
2484f22ef01cSRoman Divacky 
248539d628a0SDimitry Andric     if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
248639d628a0SDimitry Andric       emitTooManyOperandsError(TP, getOperator()->getName(),
248739d628a0SDimitry Andric                                ChildNo, getNumChildren());
24883861d79fSDimitry Andric       return false;
24893861d79fSDimitry Andric     }
2490f22ef01cSRoman Divacky 
2491139f7f9bSDimitry Andric     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2492139f7f9bSDimitry Andric       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2493f22ef01cSRoman Divacky     return MadeChange;
2494f22ef01cSRoman Divacky   }
2495f22ef01cSRoman Divacky 
249691bc56edSDimitry Andric   if (getOperator()->isSubClassOf("ComplexPattern")) {
249791bc56edSDimitry Andric     bool MadeChange = false;
249891bc56edSDimitry Andric 
249991bc56edSDimitry Andric     for (unsigned i = 0; i < getNumChildren(); ++i)
250091bc56edSDimitry Andric       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
250191bc56edSDimitry Andric 
250291bc56edSDimitry Andric     return MadeChange;
250391bc56edSDimitry Andric   }
250491bc56edSDimitry Andric 
2505f22ef01cSRoman Divacky   assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
2506f22ef01cSRoman Divacky 
2507f22ef01cSRoman Divacky   // Node transforms always take one operand.
25083861d79fSDimitry Andric   if (getNumChildren() != 1) {
2509f22ef01cSRoman Divacky     TP.error("Node transform '" + getOperator()->getName() +
2510f22ef01cSRoman Divacky              "' requires one operand!");
25113861d79fSDimitry Andric     return false;
25123861d79fSDimitry Andric   }
2513f22ef01cSRoman Divacky 
2514f22ef01cSRoman Divacky   bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
2515f22ef01cSRoman Divacky   return MadeChange;
2516f22ef01cSRoman Divacky }
2517f22ef01cSRoman Divacky 
2518f22ef01cSRoman Divacky /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2519f22ef01cSRoman Divacky /// RHS of a commutative operation, not the on LHS.
OnlyOnRHSOfCommutative(TreePatternNode * N)2520f22ef01cSRoman Divacky static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2521f22ef01cSRoman Divacky   if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2522f22ef01cSRoman Divacky     return true;
25233861d79fSDimitry Andric   if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
2524f22ef01cSRoman Divacky     return true;
2525f22ef01cSRoman Divacky   return false;
2526f22ef01cSRoman Divacky }
2527f22ef01cSRoman Divacky 
2528f22ef01cSRoman Divacky 
2529f22ef01cSRoman Divacky /// canPatternMatch - If it is impossible for this pattern to match on this
2530f22ef01cSRoman Divacky /// target, fill in Reason and return false.  Otherwise, return true.  This is
2531f22ef01cSRoman Divacky /// used as a sanity check for .td files (to prevent people from writing stuff
2532f22ef01cSRoman Divacky /// that can never possibly work), and to prevent the pattern permuter from
2533f22ef01cSRoman Divacky /// generating stuff that is useless.
canPatternMatch(std::string & Reason,const CodeGenDAGPatterns & CDP)2534f22ef01cSRoman Divacky bool TreePatternNode::canPatternMatch(std::string &Reason,
2535f22ef01cSRoman Divacky                                       const CodeGenDAGPatterns &CDP) {
2536f22ef01cSRoman Divacky   if (isLeaf()) return true;
2537f22ef01cSRoman Divacky 
2538f22ef01cSRoman Divacky   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2539f22ef01cSRoman Divacky     if (!getChild(i)->canPatternMatch(Reason, CDP))
2540f22ef01cSRoman Divacky       return false;
2541f22ef01cSRoman Divacky 
2542f22ef01cSRoman Divacky   // If this is an intrinsic, handle cases that would make it not match.  For
2543f22ef01cSRoman Divacky   // example, if an operand is required to be an immediate.
2544f22ef01cSRoman Divacky   if (getOperator()->isSubClassOf("Intrinsic")) {
2545f22ef01cSRoman Divacky     // TODO:
2546f22ef01cSRoman Divacky     return true;
2547f22ef01cSRoman Divacky   }
2548f22ef01cSRoman Divacky 
254991bc56edSDimitry Andric   if (getOperator()->isSubClassOf("ComplexPattern"))
255091bc56edSDimitry Andric     return true;
255191bc56edSDimitry Andric 
2552f22ef01cSRoman Divacky   // If this node is a commutative operator, check that the LHS isn't an
2553f22ef01cSRoman Divacky   // immediate.
2554f22ef01cSRoman Divacky   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2555f22ef01cSRoman Divacky   bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2556f22ef01cSRoman Divacky   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2557f22ef01cSRoman Divacky     // Scan all of the operands of the node and make sure that only the last one
2558f22ef01cSRoman Divacky     // is a constant node, unless the RHS also is.
2559f22ef01cSRoman Divacky     if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2560d88c1a5aSDimitry Andric       unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2561f22ef01cSRoman Divacky       for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
2562f22ef01cSRoman Divacky         if (OnlyOnRHSOfCommutative(getChild(i))) {
2563f22ef01cSRoman Divacky           Reason="Immediate value must be on the RHS of commutative operators!";
2564f22ef01cSRoman Divacky           return false;
2565f22ef01cSRoman Divacky         }
2566f22ef01cSRoman Divacky     }
2567f22ef01cSRoman Divacky   }
2568f22ef01cSRoman Divacky 
2569f22ef01cSRoman Divacky   return true;
2570f22ef01cSRoman Divacky }
2571f22ef01cSRoman Divacky 
2572f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
2573f22ef01cSRoman Divacky // TreePattern implementation
2574f22ef01cSRoman Divacky //
2575f22ef01cSRoman Divacky 
TreePattern(Record * TheRec,ListInit * RawPat,bool isInput,CodeGenDAGPatterns & cdp)2576f22ef01cSRoman Divacky TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
25773861d79fSDimitry Andric                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
25782cab237bSDimitry Andric                          isInputPattern(isInput), HasError(false),
25792cab237bSDimitry Andric                          Infer(*this) {
258097bc6c73SDimitry Andric   for (Init *I : RawPat->getValues())
258197bc6c73SDimitry Andric     Trees.push_back(ParseTreePattern(I, ""));
2582f22ef01cSRoman Divacky }
2583f22ef01cSRoman Divacky 
TreePattern(Record * TheRec,DagInit * Pat,bool isInput,CodeGenDAGPatterns & cdp)2584f22ef01cSRoman Divacky TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
25853861d79fSDimitry Andric                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
25862cab237bSDimitry Andric                          isInputPattern(isInput), HasError(false),
25872cab237bSDimitry Andric                          Infer(*this) {
2588f22ef01cSRoman Divacky   Trees.push_back(ParseTreePattern(Pat, ""));
2589f22ef01cSRoman Divacky }
2590f22ef01cSRoman Divacky 
TreePattern(Record * TheRec,TreePatternNodePtr Pat,bool isInput,CodeGenDAGPatterns & cdp)25914ba319b5SDimitry Andric TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
25924ba319b5SDimitry Andric                          CodeGenDAGPatterns &cdp)
25934ba319b5SDimitry Andric     : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
25942cab237bSDimitry Andric       Infer(*this) {
2595f22ef01cSRoman Divacky   Trees.push_back(Pat);
2596f22ef01cSRoman Divacky }
2597f22ef01cSRoman Divacky 
error(const Twine & Msg)259839d628a0SDimitry Andric void TreePattern::error(const Twine &Msg) {
25993861d79fSDimitry Andric   if (HasError)
26003861d79fSDimitry Andric     return;
2601f22ef01cSRoman Divacky   dump();
26023861d79fSDimitry Andric   PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
26033861d79fSDimitry Andric   HasError = true;
2604f22ef01cSRoman Divacky }
2605f22ef01cSRoman Divacky 
ComputeNamedNodes()2606f22ef01cSRoman Divacky void TreePattern::ComputeNamedNodes() {
26074ba319b5SDimitry Andric   for (TreePatternNodePtr &Tree : Trees)
26084ba319b5SDimitry Andric     ComputeNamedNodes(Tree.get());
2609f22ef01cSRoman Divacky }
2610f22ef01cSRoman Divacky 
ComputeNamedNodes(TreePatternNode * N)2611f22ef01cSRoman Divacky void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2612f22ef01cSRoman Divacky   if (!N->getName().empty())
2613f22ef01cSRoman Divacky     NamedNodes[N->getName()].push_back(N);
2614f22ef01cSRoman Divacky 
2615f22ef01cSRoman Divacky   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2616f22ef01cSRoman Divacky     ComputeNamedNodes(N->getChild(i));
2617f22ef01cSRoman Divacky }
2618f22ef01cSRoman Divacky 
ParseTreePattern(Init * TheInit,StringRef OpName)26194ba319b5SDimitry Andric TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
26204ba319b5SDimitry Andric                                                  StringRef OpName) {
26213861d79fSDimitry Andric   if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2622f22ef01cSRoman Divacky     Record *R = DI->getDef();
2623f22ef01cSRoman Divacky 
2624f22ef01cSRoman Divacky     // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
262517a519f9SDimitry Andric     // TreePatternNode of its own.  For example:
2626f22ef01cSRoman Divacky     ///   (foo GPR, imm) -> (foo GPR, (imm))
26274ba319b5SDimitry Andric     if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
26286122f3e6SDimitry Andric       return ParseTreePattern(
2629d88c1a5aSDimitry Andric         DagInit::get(DI, nullptr,
2630d88c1a5aSDimitry Andric                      std::vector<std::pair<Init*, StringInit*> >()),
2631f22ef01cSRoman Divacky         OpName);
2632f22ef01cSRoman Divacky 
2633f22ef01cSRoman Divacky     // Input argument?
26344ba319b5SDimitry Andric     TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
2635f22ef01cSRoman Divacky     if (R->getName() == "node" && !OpName.empty()) {
2636f22ef01cSRoman Divacky       if (OpName.empty())
2637f22ef01cSRoman Divacky         error("'node' argument requires a name to match with operand list");
2638f22ef01cSRoman Divacky       Args.push_back(OpName);
2639f22ef01cSRoman Divacky     }
2640f22ef01cSRoman Divacky 
2641f22ef01cSRoman Divacky     Res->setName(OpName);
2642f22ef01cSRoman Divacky     return Res;
2643f22ef01cSRoman Divacky   }
2644f22ef01cSRoman Divacky 
2645139f7f9bSDimitry Andric   // ?:$name or just $name.
2646ff0cc061SDimitry Andric   if (isa<UnsetInit>(TheInit)) {
2647139f7f9bSDimitry Andric     if (OpName.empty())
2648139f7f9bSDimitry Andric       error("'?' argument requires a name to match with operand list");
26494ba319b5SDimitry Andric     TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
2650139f7f9bSDimitry Andric     Args.push_back(OpName);
2651139f7f9bSDimitry Andric     Res->setName(OpName);
2652139f7f9bSDimitry Andric     return Res;
2653139f7f9bSDimitry Andric   }
2654139f7f9bSDimitry Andric 
26554ba319b5SDimitry Andric   if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
2656f22ef01cSRoman Divacky     if (!OpName.empty())
26574ba319b5SDimitry Andric       error("Constant int or bit argument should not have a name!");
26584ba319b5SDimitry Andric     if (isa<BitInit>(TheInit))
26594ba319b5SDimitry Andric       TheInit = TheInit->convertInitializerTo(IntRecTy::get());
26604ba319b5SDimitry Andric     return std::make_shared<TreePatternNode>(TheInit, 1);
2661f22ef01cSRoman Divacky   }
2662f22ef01cSRoman Divacky 
26633861d79fSDimitry Andric   if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2664f22ef01cSRoman Divacky     // Turn this into an IntInit.
26656122f3e6SDimitry Andric     Init *II = BI->convertInitializerTo(IntRecTy::get());
266691bc56edSDimitry Andric     if (!II || !isa<IntInit>(II))
2667f22ef01cSRoman Divacky       error("Bits value must be constants!");
2668f22ef01cSRoman Divacky     return ParseTreePattern(II, OpName);
2669f22ef01cSRoman Divacky   }
2670f22ef01cSRoman Divacky 
26713861d79fSDimitry Andric   DagInit *Dag = dyn_cast<DagInit>(TheInit);
2672f22ef01cSRoman Divacky   if (!Dag) {
26737a7e6055SDimitry Andric     TheInit->print(errs());
2674f22ef01cSRoman Divacky     error("Pattern has unexpected init kind!");
2675f22ef01cSRoman Divacky   }
26763861d79fSDimitry Andric   DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2677f22ef01cSRoman Divacky   if (!OpDef) error("Pattern has unexpected operator type!");
2678f22ef01cSRoman Divacky   Record *Operator = OpDef->getDef();
2679f22ef01cSRoman Divacky 
2680f22ef01cSRoman Divacky   if (Operator->isSubClassOf("ValueType")) {
2681f22ef01cSRoman Divacky     // If the operator is a ValueType, then this must be "type cast" of a leaf
2682f22ef01cSRoman Divacky     // node.
2683f22ef01cSRoman Divacky     if (Dag->getNumArgs() != 1)
2684f22ef01cSRoman Divacky       error("Type cast only takes one operand!");
2685f22ef01cSRoman Divacky 
26864ba319b5SDimitry Andric     TreePatternNodePtr New =
26874ba319b5SDimitry Andric         ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
2688f22ef01cSRoman Divacky 
2689f22ef01cSRoman Divacky     // Apply the type cast.
2690f22ef01cSRoman Divacky     assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
26912cab237bSDimitry Andric     const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
26922cab237bSDimitry Andric     New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
2693f22ef01cSRoman Divacky 
2694f22ef01cSRoman Divacky     if (!OpName.empty())
2695f22ef01cSRoman Divacky       error("ValueType cast should not have a name!");
2696f22ef01cSRoman Divacky     return New;
2697f22ef01cSRoman Divacky   }
2698f22ef01cSRoman Divacky 
2699f22ef01cSRoman Divacky   // Verify that this is something that makes sense for an operator.
27004ba319b5SDimitry Andric   if (!Operator->isSubClassOf("PatFrags") &&
2701f22ef01cSRoman Divacky       !Operator->isSubClassOf("SDNode") &&
2702f22ef01cSRoman Divacky       !Operator->isSubClassOf("Instruction") &&
2703f22ef01cSRoman Divacky       !Operator->isSubClassOf("SDNodeXForm") &&
2704f22ef01cSRoman Divacky       !Operator->isSubClassOf("Intrinsic") &&
270591bc56edSDimitry Andric       !Operator->isSubClassOf("ComplexPattern") &&
2706f22ef01cSRoman Divacky       Operator->getName() != "set" &&
2707f22ef01cSRoman Divacky       Operator->getName() != "implicit")
2708f22ef01cSRoman Divacky     error("Unrecognized node '" + Operator->getName() + "'!");
2709f22ef01cSRoman Divacky 
2710f22ef01cSRoman Divacky   //  Check to see if this is something that is illegal in an input pattern.
2711f22ef01cSRoman Divacky   if (isInputPattern) {
2712f22ef01cSRoman Divacky     if (Operator->isSubClassOf("Instruction") ||
2713f22ef01cSRoman Divacky         Operator->isSubClassOf("SDNodeXForm"))
2714f22ef01cSRoman Divacky       error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2715f22ef01cSRoman Divacky   } else {
2716f22ef01cSRoman Divacky     if (Operator->isSubClassOf("Intrinsic"))
2717f22ef01cSRoman Divacky       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2718f22ef01cSRoman Divacky 
2719f22ef01cSRoman Divacky     if (Operator->isSubClassOf("SDNode") &&
2720f22ef01cSRoman Divacky         Operator->getName() != "imm" &&
2721f22ef01cSRoman Divacky         Operator->getName() != "fpimm" &&
2722f22ef01cSRoman Divacky         Operator->getName() != "tglobaltlsaddr" &&
2723f22ef01cSRoman Divacky         Operator->getName() != "tconstpool" &&
2724f22ef01cSRoman Divacky         Operator->getName() != "tjumptable" &&
2725f22ef01cSRoman Divacky         Operator->getName() != "tframeindex" &&
2726f22ef01cSRoman Divacky         Operator->getName() != "texternalsym" &&
2727f22ef01cSRoman Divacky         Operator->getName() != "tblockaddress" &&
2728f22ef01cSRoman Divacky         Operator->getName() != "tglobaladdr" &&
2729f22ef01cSRoman Divacky         Operator->getName() != "bb" &&
27303dac3a9bSDimitry Andric         Operator->getName() != "vt" &&
27313dac3a9bSDimitry Andric         Operator->getName() != "mcsym")
2732f22ef01cSRoman Divacky       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2733f22ef01cSRoman Divacky   }
2734f22ef01cSRoman Divacky 
27354ba319b5SDimitry Andric   std::vector<TreePatternNodePtr> Children;
2736f22ef01cSRoman Divacky 
2737f22ef01cSRoman Divacky   // Parse all the operands.
2738f22ef01cSRoman Divacky   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2739d88c1a5aSDimitry Andric     Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
2740f22ef01cSRoman Divacky 
274130785c0eSDimitry Andric   // Get the actual number of results before Operator is converted to an intrinsic
274230785c0eSDimitry Andric   // node (which is hard-coded to have either zero or one result).
274330785c0eSDimitry Andric   unsigned NumResults = GetNumNodeResults(Operator, CDP);
274430785c0eSDimitry Andric 
27454ba319b5SDimitry Andric   // If the operator is an intrinsic, then this is just syntactic sugar for
2746f22ef01cSRoman Divacky   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and
2747f22ef01cSRoman Divacky   // convert the intrinsic name to a number.
2748f22ef01cSRoman Divacky   if (Operator->isSubClassOf("Intrinsic")) {
2749f22ef01cSRoman Divacky     const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2750f22ef01cSRoman Divacky     unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2751f22ef01cSRoman Divacky 
2752f22ef01cSRoman Divacky     // If this intrinsic returns void, it must have side-effects and thus a
2753f22ef01cSRoman Divacky     // chain.
2754f22ef01cSRoman Divacky     if (Int.IS.RetVTs.empty())
2755f22ef01cSRoman Divacky       Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2756f22ef01cSRoman Divacky     else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2757f22ef01cSRoman Divacky       // Has side-effects, requires chain.
2758f22ef01cSRoman Divacky       Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2759f22ef01cSRoman Divacky     else // Otherwise, no chain.
2760f22ef01cSRoman Divacky       Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2761f22ef01cSRoman Divacky 
27624ba319b5SDimitry Andric     Children.insert(Children.begin(),
27634ba319b5SDimitry Andric                     std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
2764f22ef01cSRoman Divacky   }
2765f22ef01cSRoman Divacky 
276691bc56edSDimitry Andric   if (Operator->isSubClassOf("ComplexPattern")) {
276791bc56edSDimitry Andric     for (unsigned i = 0; i < Children.size(); ++i) {
27684ba319b5SDimitry Andric       TreePatternNodePtr Child = Children[i];
276991bc56edSDimitry Andric 
277091bc56edSDimitry Andric       if (Child->getName().empty())
277191bc56edSDimitry Andric         error("All arguments to a ComplexPattern must be named");
277291bc56edSDimitry Andric 
277391bc56edSDimitry Andric       // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
277491bc56edSDimitry Andric       // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
277591bc56edSDimitry Andric       // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
277691bc56edSDimitry Andric       auto OperandId = std::make_pair(Operator, i);
277791bc56edSDimitry Andric       auto PrevOp = ComplexPatternOperands.find(Child->getName());
277891bc56edSDimitry Andric       if (PrevOp != ComplexPatternOperands.end()) {
277991bc56edSDimitry Andric         if (PrevOp->getValue() != OperandId)
278091bc56edSDimitry Andric           error("All ComplexPattern operands must appear consistently: "
278191bc56edSDimitry Andric                 "in the same order in just one ComplexPattern instance.");
278291bc56edSDimitry Andric       } else
278391bc56edSDimitry Andric         ComplexPatternOperands[Child->getName()] = OperandId;
278491bc56edSDimitry Andric     }
278591bc56edSDimitry Andric   }
278691bc56edSDimitry Andric 
27874ba319b5SDimitry Andric   TreePatternNodePtr Result =
27884ba319b5SDimitry Andric       std::make_shared<TreePatternNode>(Operator, std::move(Children),
27894ba319b5SDimitry Andric                                         NumResults);
2790f22ef01cSRoman Divacky   Result->setName(OpName);
2791f22ef01cSRoman Divacky 
2792d88c1a5aSDimitry Andric   if (Dag->getName()) {
2793f22ef01cSRoman Divacky     assert(Result->getName().empty());
2794d88c1a5aSDimitry Andric     Result->setName(Dag->getNameStr());
2795f22ef01cSRoman Divacky   }
2796f22ef01cSRoman Divacky   return Result;
2797f22ef01cSRoman Divacky }
2798f22ef01cSRoman Divacky 
2799f22ef01cSRoman Divacky /// SimplifyTree - See if we can simplify this tree to eliminate something that
2800f22ef01cSRoman Divacky /// will never match in favor of something obvious that will.  This is here
2801f22ef01cSRoman Divacky /// strictly as a convenience to target authors because it allows them to write
2802f22ef01cSRoman Divacky /// more type generic things and have useless type casts fold away.
2803f22ef01cSRoman Divacky ///
2804f22ef01cSRoman Divacky /// This returns true if any change is made.
SimplifyTree(TreePatternNodePtr & N)28054ba319b5SDimitry Andric static bool SimplifyTree(TreePatternNodePtr &N) {
2806f22ef01cSRoman Divacky   if (N->isLeaf())
2807f22ef01cSRoman Divacky     return false;
2808f22ef01cSRoman Divacky 
2809f22ef01cSRoman Divacky   // If we have a bitconvert with a resolved type and if the source and
2810f22ef01cSRoman Divacky   // destination types are the same, then the bitconvert is useless, remove it.
2811f22ef01cSRoman Divacky   if (N->getOperator()->getName() == "bitconvert" &&
28122cab237bSDimitry Andric       N->getExtType(0).isValueTypeByHwMode(false) &&
2813f22ef01cSRoman Divacky       N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2814f22ef01cSRoman Divacky       N->getName().empty()) {
28154ba319b5SDimitry Andric     N = N->getChildShared(0);
2816f22ef01cSRoman Divacky     SimplifyTree(N);
2817f22ef01cSRoman Divacky     return true;
2818f22ef01cSRoman Divacky   }
2819f22ef01cSRoman Divacky 
2820f22ef01cSRoman Divacky   // Walk all children.
2821f22ef01cSRoman Divacky   bool MadeChange = false;
2822f22ef01cSRoman Divacky   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
28234ba319b5SDimitry Andric     TreePatternNodePtr Child = N->getChildShared(i);
2824f22ef01cSRoman Divacky     MadeChange |= SimplifyTree(Child);
28254ba319b5SDimitry Andric     N->setChild(i, std::move(Child));
2826f22ef01cSRoman Divacky   }
2827f22ef01cSRoman Divacky   return MadeChange;
2828f22ef01cSRoman Divacky }
2829f22ef01cSRoman Divacky 
2830f22ef01cSRoman Divacky 
2831f22ef01cSRoman Divacky 
2832f22ef01cSRoman Divacky /// InferAllTypes - Infer/propagate as many types throughout the expression
2833f22ef01cSRoman Divacky /// patterns as possible.  Return true if all types are inferred, false
28343861d79fSDimitry Andric /// otherwise.  Flags an error if a type contradiction is found.
2835f22ef01cSRoman Divacky bool TreePattern::
InferAllTypes(const StringMap<SmallVector<TreePatternNode *,1>> * InNamedTypes)2836f22ef01cSRoman Divacky InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2837f22ef01cSRoman Divacky   if (NamedNodes.empty())
2838f22ef01cSRoman Divacky     ComputeNamedNodes();
2839f22ef01cSRoman Divacky 
2840f22ef01cSRoman Divacky   bool MadeChange = true;
2841f22ef01cSRoman Divacky   while (MadeChange) {
2842f22ef01cSRoman Divacky     MadeChange = false;
28434ba319b5SDimitry Andric     for (TreePatternNodePtr &Tree : Trees) {
28447d523365SDimitry Andric       MadeChange |= Tree->ApplyTypeConstraints(*this, false);
28457d523365SDimitry Andric       MadeChange |= SimplifyTree(Tree);
2846f22ef01cSRoman Divacky     }
2847f22ef01cSRoman Divacky 
2848f22ef01cSRoman Divacky     // If there are constraints on our named nodes, apply them.
28497d523365SDimitry Andric     for (auto &Entry : NamedNodes) {
28507d523365SDimitry Andric       SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2851f22ef01cSRoman Divacky 
2852f22ef01cSRoman Divacky       // If we have input named node types, propagate their types to the named
2853f22ef01cSRoman Divacky       // values here.
2854f22ef01cSRoman Divacky       if (InNamedTypes) {
28557d523365SDimitry Andric         if (!InNamedTypes->count(Entry.getKey())) {
28567d523365SDimitry Andric           error("Node '" + std::string(Entry.getKey()) +
285791bc56edSDimitry Andric                 "' in output pattern but not input pattern");
285891bc56edSDimitry Andric           return true;
285991bc56edSDimitry Andric         }
2860f22ef01cSRoman Divacky 
2861f22ef01cSRoman Divacky         const SmallVectorImpl<TreePatternNode*> &InNodes =
28627d523365SDimitry Andric           InNamedTypes->find(Entry.getKey())->second;
2863f22ef01cSRoman Divacky 
2864f22ef01cSRoman Divacky         // The input types should be fully resolved by now.
28657d523365SDimitry Andric         for (TreePatternNode *Node : Nodes) {
2866f22ef01cSRoman Divacky           // If this node is a register class, and it is the root of the pattern
2867f22ef01cSRoman Divacky           // then we're mapping something onto an input register.  We allow
2868f22ef01cSRoman Divacky           // changing the type of the input register in this case.  This allows
2869f22ef01cSRoman Divacky           // us to match things like:
2870f22ef01cSRoman Divacky           //  def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
28714ba319b5SDimitry Andric           if (Node == Trees[0].get() && Node->isLeaf()) {
28727d523365SDimitry Andric             DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
287317a519f9SDimitry Andric             if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
287417a519f9SDimitry Andric                        DI->getDef()->isSubClassOf("RegisterOperand")))
2875f22ef01cSRoman Divacky               continue;
2876f22ef01cSRoman Divacky           }
2877f22ef01cSRoman Divacky 
28787d523365SDimitry Andric           assert(Node->getNumTypes() == 1 &&
2879f22ef01cSRoman Divacky                  InNodes[0]->getNumTypes() == 1 &&
2880f22ef01cSRoman Divacky                  "FIXME: cannot name multiple result nodes yet");
28817d523365SDimitry Andric           MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2882f22ef01cSRoman Divacky                                              *this);
2883f22ef01cSRoman Divacky         }
2884f22ef01cSRoman Divacky       }
2885f22ef01cSRoman Divacky 
2886f22ef01cSRoman Divacky       // If there are multiple nodes with the same name, they must all have the
2887f22ef01cSRoman Divacky       // same type.
28887d523365SDimitry Andric       if (Entry.second.size() > 1) {
2889f22ef01cSRoman Divacky         for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2890f22ef01cSRoman Divacky           TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2891f22ef01cSRoman Divacky           assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2892f22ef01cSRoman Divacky                  "FIXME: cannot name multiple result nodes yet");
2893f22ef01cSRoman Divacky 
2894f22ef01cSRoman Divacky           MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2895f22ef01cSRoman Divacky           MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2896f22ef01cSRoman Divacky         }
2897f22ef01cSRoman Divacky       }
2898f22ef01cSRoman Divacky     }
2899f22ef01cSRoman Divacky   }
2900f22ef01cSRoman Divacky 
2901f22ef01cSRoman Divacky   bool HasUnresolvedTypes = false;
29024ba319b5SDimitry Andric   for (const TreePatternNodePtr &Tree : Trees)
29032cab237bSDimitry Andric     HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
2904f22ef01cSRoman Divacky   return !HasUnresolvedTypes;
2905f22ef01cSRoman Divacky }
2906f22ef01cSRoman Divacky 
print(raw_ostream & OS) const2907f22ef01cSRoman Divacky void TreePattern::print(raw_ostream &OS) const {
2908f22ef01cSRoman Divacky   OS << getRecord()->getName();
2909f22ef01cSRoman Divacky   if (!Args.empty()) {
2910f22ef01cSRoman Divacky     OS << "(" << Args[0];
2911f22ef01cSRoman Divacky     for (unsigned i = 1, e = Args.size(); i != e; ++i)
2912f22ef01cSRoman Divacky       OS << ", " << Args[i];
2913f22ef01cSRoman Divacky     OS << ")";
2914f22ef01cSRoman Divacky   }
2915f22ef01cSRoman Divacky   OS << ": ";
2916f22ef01cSRoman Divacky 
2917f22ef01cSRoman Divacky   if (Trees.size() > 1)
2918f22ef01cSRoman Divacky     OS << "[\n";
29194ba319b5SDimitry Andric   for (const TreePatternNodePtr &Tree : Trees) {
2920f22ef01cSRoman Divacky     OS << "\t";
29217d523365SDimitry Andric     Tree->print(OS);
2922f22ef01cSRoman Divacky     OS << "\n";
2923f22ef01cSRoman Divacky   }
2924f22ef01cSRoman Divacky 
2925f22ef01cSRoman Divacky   if (Trees.size() > 1)
2926f22ef01cSRoman Divacky     OS << "]\n";
2927f22ef01cSRoman Divacky }
2928f22ef01cSRoman Divacky 
dump() const2929f22ef01cSRoman Divacky void TreePattern::dump() const { print(errs()); }
2930f22ef01cSRoman Divacky 
2931f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
2932f22ef01cSRoman Divacky // CodeGenDAGPatterns implementation
2933f22ef01cSRoman Divacky //
2934f22ef01cSRoman Divacky 
CodeGenDAGPatterns(RecordKeeper & R,PatternRewriterFn PatternRewriter)29352cab237bSDimitry Andric CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
29362cab237bSDimitry Andric                                        PatternRewriterFn PatternRewriter)
29372cab237bSDimitry Andric     : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
29382cab237bSDimitry Andric       PatternRewriter(PatternRewriter) {
29392754fe60SDimitry Andric 
29403ca95b02SDimitry Andric   Intrinsics = CodeGenIntrinsicTable(Records, false);
29413ca95b02SDimitry Andric   TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
2942f22ef01cSRoman Divacky   ParseNodeInfo();
2943f22ef01cSRoman Divacky   ParseNodeTransforms();
2944f22ef01cSRoman Divacky   ParseComplexPatterns();
2945f22ef01cSRoman Divacky   ParsePatternFragments();
2946f22ef01cSRoman Divacky   ParseDefaultOperands();
2947f22ef01cSRoman Divacky   ParseInstructions();
294891bc56edSDimitry Andric   ParsePatternFragments(/*OutFrags*/true);
2949f22ef01cSRoman Divacky   ParsePatterns();
2950f22ef01cSRoman Divacky 
29512cab237bSDimitry Andric   // Break patterns with parameterized types into a series of patterns,
29522cab237bSDimitry Andric   // where each one has a fixed type and is predicated on the conditions
29532cab237bSDimitry Andric   // of the associated HW mode.
29542cab237bSDimitry Andric   ExpandHwModeBasedTypes();
29552cab237bSDimitry Andric 
2956f22ef01cSRoman Divacky   // Generate variants.  For example, commutative patterns can match
2957f22ef01cSRoman Divacky   // multiple ways.  Add them to PatternsToMatch as well.
2958f22ef01cSRoman Divacky   GenerateVariants();
2959f22ef01cSRoman Divacky 
2960f22ef01cSRoman Divacky   // Infer instruction flags.  For example, we can detect loads,
2961f22ef01cSRoman Divacky   // stores, and side effects in many cases by examining an
2962f22ef01cSRoman Divacky   // instruction's pattern.
2963f22ef01cSRoman Divacky   InferInstructionFlags();
29643861d79fSDimitry Andric 
29653861d79fSDimitry Andric   // Verify that instruction flags match the patterns.
29663861d79fSDimitry Andric   VerifyInstructionFlags();
2967f22ef01cSRoman Divacky }
2968f22ef01cSRoman Divacky 
getSDNodeNamed(const std::string & Name) const2969f22ef01cSRoman Divacky Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2970f22ef01cSRoman Divacky   Record *N = Records.getDef(Name);
2971ff0cc061SDimitry Andric   if (!N || !N->isSubClassOf("SDNode"))
2972ff0cc061SDimitry Andric     PrintFatalError("Error getting SDNode '" + Name + "'!");
2973ff0cc061SDimitry Andric 
2974f22ef01cSRoman Divacky   return N;
2975f22ef01cSRoman Divacky }
2976f22ef01cSRoman Divacky 
2977f22ef01cSRoman Divacky // Parse all of the SDNode definitions for the target, populating SDNodes.
ParseNodeInfo()2978f22ef01cSRoman Divacky void CodeGenDAGPatterns::ParseNodeInfo() {
2979f22ef01cSRoman Divacky   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
29802cab237bSDimitry Andric   const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
29812cab237bSDimitry Andric 
2982f22ef01cSRoman Divacky   while (!Nodes.empty()) {
29832cab237bSDimitry Andric     Record *R = Nodes.back();
29842cab237bSDimitry Andric     SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
2985f22ef01cSRoman Divacky     Nodes.pop_back();
2986f22ef01cSRoman Divacky   }
2987f22ef01cSRoman Divacky 
2988f22ef01cSRoman Divacky   // Get the builtin intrinsic nodes.
2989f22ef01cSRoman Divacky   intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
2990f22ef01cSRoman Divacky   intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
2991f22ef01cSRoman Divacky   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2992f22ef01cSRoman Divacky }
2993f22ef01cSRoman Divacky 
2994f22ef01cSRoman Divacky /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2995f22ef01cSRoman Divacky /// map, and emit them to the file as functions.
ParseNodeTransforms()2996f22ef01cSRoman Divacky void CodeGenDAGPatterns::ParseNodeTransforms() {
2997f22ef01cSRoman Divacky   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2998f22ef01cSRoman Divacky   while (!Xforms.empty()) {
2999f22ef01cSRoman Divacky     Record *XFormNode = Xforms.back();
3000f22ef01cSRoman Divacky     Record *SDNode = XFormNode->getValueAsDef("Opcode");
3001f9448bf3SDimitry Andric     StringRef Code = XFormNode->getValueAsString("XFormFunction");
3002f22ef01cSRoman Divacky     SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
3003f22ef01cSRoman Divacky 
3004f22ef01cSRoman Divacky     Xforms.pop_back();
3005f22ef01cSRoman Divacky   }
3006f22ef01cSRoman Divacky }
3007f22ef01cSRoman Divacky 
ParseComplexPatterns()3008f22ef01cSRoman Divacky void CodeGenDAGPatterns::ParseComplexPatterns() {
3009f22ef01cSRoman Divacky   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
3010f22ef01cSRoman Divacky   while (!AMs.empty()) {
3011f22ef01cSRoman Divacky     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
3012f22ef01cSRoman Divacky     AMs.pop_back();
3013f22ef01cSRoman Divacky   }
3014f22ef01cSRoman Divacky }
3015f22ef01cSRoman Divacky 
3016f22ef01cSRoman Divacky 
3017f22ef01cSRoman Divacky /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3018f22ef01cSRoman Divacky /// file, building up the PatternFragments map.  After we've collected them all,
3019f22ef01cSRoman Divacky /// inline fragments together as necessary, so that there are no references left
3020f22ef01cSRoman Divacky /// inside a pattern fragment to a pattern fragment.
3021f22ef01cSRoman Divacky ///
ParsePatternFragments(bool OutFrags)302291bc56edSDimitry Andric void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
30234ba319b5SDimitry Andric   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
3024f22ef01cSRoman Divacky 
3025f22ef01cSRoman Divacky   // First step, parse all of the fragments.
30267d523365SDimitry Andric   for (Record *Frag : Fragments) {
30277d523365SDimitry Andric     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
302891bc56edSDimitry Andric       continue;
302991bc56edSDimitry Andric 
30304ba319b5SDimitry Andric     ListInit *LI = Frag->getValueAsListInit("Fragments");
303191bc56edSDimitry Andric     TreePattern *P =
30327d523365SDimitry Andric         (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
30334ba319b5SDimitry Andric              Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
303439d628a0SDimitry Andric              *this)).get();
3035f22ef01cSRoman Divacky 
3036f22ef01cSRoman Divacky     // Validate the argument list, converting it to set, to discard duplicates.
3037f22ef01cSRoman Divacky     std::vector<std::string> &Args = P->getArgList();
30382cab237bSDimitry Andric     // Copy the args so we can take StringRefs to them.
30392cab237bSDimitry Andric     auto ArgsCopy = Args;
30402cab237bSDimitry Andric     SmallDenseSet<StringRef, 4> OperandsSet;
30412cab237bSDimitry Andric     OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
3042f22ef01cSRoman Divacky 
3043f22ef01cSRoman Divacky     if (OperandsSet.count(""))
3044f22ef01cSRoman Divacky       P->error("Cannot have unnamed 'node' values in pattern fragment!");
3045f22ef01cSRoman Divacky 
3046f22ef01cSRoman Divacky     // Parse the operands list.
30477d523365SDimitry Andric     DagInit *OpsList = Frag->getValueAsDag("Operands");
30483861d79fSDimitry Andric     DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
3049f22ef01cSRoman Divacky     // Special cases: ops == outs == ins. Different names are used to
3050f22ef01cSRoman Divacky     // improve readability.
3051f22ef01cSRoman Divacky     if (!OpsOp ||
3052f22ef01cSRoman Divacky         (OpsOp->getDef()->getName() != "ops" &&
3053f22ef01cSRoman Divacky          OpsOp->getDef()->getName() != "outs" &&
3054f22ef01cSRoman Divacky          OpsOp->getDef()->getName() != "ins"))
3055f22ef01cSRoman Divacky       P->error("Operands list should start with '(ops ... '!");
3056f22ef01cSRoman Divacky 
3057f22ef01cSRoman Divacky     // Copy over the arguments.
3058f22ef01cSRoman Divacky     Args.clear();
3059f22ef01cSRoman Divacky     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
30603861d79fSDimitry Andric       if (!isa<DefInit>(OpsList->getArg(j)) ||
30613861d79fSDimitry Andric           cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
3062f22ef01cSRoman Divacky         P->error("Operands list should all be 'node' values.");
3063d88c1a5aSDimitry Andric       if (!OpsList->getArgName(j))
3064f22ef01cSRoman Divacky         P->error("Operands list should have names for each operand!");
3065d88c1a5aSDimitry Andric       StringRef ArgNameStr = OpsList->getArgNameStr(j);
3066d88c1a5aSDimitry Andric       if (!OperandsSet.count(ArgNameStr))
3067d88c1a5aSDimitry Andric         P->error("'" + ArgNameStr +
3068f22ef01cSRoman Divacky                  "' does not occur in pattern or was multiply specified!");
3069d88c1a5aSDimitry Andric       OperandsSet.erase(ArgNameStr);
3070d88c1a5aSDimitry Andric       Args.push_back(ArgNameStr);
3071f22ef01cSRoman Divacky     }
3072f22ef01cSRoman Divacky 
3073f22ef01cSRoman Divacky     if (!OperandsSet.empty())
3074f22ef01cSRoman Divacky       P->error("Operands list does not contain an entry for operand '" +
3075f22ef01cSRoman Divacky                *OperandsSet.begin() + "'!");
3076f22ef01cSRoman Divacky 
3077f22ef01cSRoman Divacky     // If there is a node transformation corresponding to this, keep track of
3078f22ef01cSRoman Divacky     // it.
30797d523365SDimitry Andric     Record *Transform = Frag->getValueAsDef("OperandTransform");
3080f22ef01cSRoman Divacky     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
30814ba319b5SDimitry Andric       for (auto T : P->getTrees())
30824ba319b5SDimitry Andric         T->setTransformFn(Transform);
3083f22ef01cSRoman Divacky   }
3084f22ef01cSRoman Divacky 
3085f22ef01cSRoman Divacky   // Now that we've parsed all of the tree fragments, do a closure on them so
3086f22ef01cSRoman Divacky   // that there are not references to PatFrags left inside of them.
30877d523365SDimitry Andric   for (Record *Frag : Fragments) {
30887d523365SDimitry Andric     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
308991bc56edSDimitry Andric       continue;
309091bc56edSDimitry Andric 
30917d523365SDimitry Andric     TreePattern &ThePat = *PatternFragments[Frag];
309239d628a0SDimitry Andric     ThePat.InlinePatternFragments();
3093f22ef01cSRoman Divacky 
3094f22ef01cSRoman Divacky     // Infer as many types as possible.  Don't worry about it if we don't infer
30954ba319b5SDimitry Andric     // all of them, some may depend on the inputs of the pattern.  Also, don't
30964ba319b5SDimitry Andric     // validate type sets; validation may cause spurious failures e.g. if a
30974ba319b5SDimitry Andric     // fragment needs floating-point types but the current target does not have
30984ba319b5SDimitry Andric     // any (this is only an error if that fragment is ever used!).
30994ba319b5SDimitry Andric     {
31004ba319b5SDimitry Andric       TypeInfer::SuppressValidation SV(ThePat.getInfer());
310139d628a0SDimitry Andric       ThePat.InferAllTypes();
310239d628a0SDimitry Andric       ThePat.resetError();
31034ba319b5SDimitry Andric     }
3104f22ef01cSRoman Divacky 
3105f22ef01cSRoman Divacky     // If debugging, print out the pattern fragment result.
31064ba319b5SDimitry Andric     LLVM_DEBUG(ThePat.dump());
3107f22ef01cSRoman Divacky   }
3108f22ef01cSRoman Divacky }
3109f22ef01cSRoman Divacky 
ParseDefaultOperands()3110f22ef01cSRoman Divacky void CodeGenDAGPatterns::ParseDefaultOperands() {
31113861d79fSDimitry Andric   std::vector<Record*> DefaultOps;
31123861d79fSDimitry Andric   DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
3113f22ef01cSRoman Divacky 
3114f22ef01cSRoman Divacky   // Find some SDNode.
3115f22ef01cSRoman Divacky   assert(!SDNodes.empty() && "No SDNodes parsed?");
31166122f3e6SDimitry Andric   Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
3117f22ef01cSRoman Divacky 
31183861d79fSDimitry Andric   for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
31193861d79fSDimitry Andric     DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
3120f22ef01cSRoman Divacky 
3121f22ef01cSRoman Divacky     // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3122f22ef01cSRoman Divacky     // SomeSDnode so that we can parse this.
3123d88c1a5aSDimitry Andric     std::vector<std::pair<Init*, StringInit*> > Ops;
3124f22ef01cSRoman Divacky     for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3125f22ef01cSRoman Divacky       Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3126f22ef01cSRoman Divacky                                    DefaultInfo->getArgName(op)));
3127d88c1a5aSDimitry Andric     DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
3128f22ef01cSRoman Divacky 
3129f22ef01cSRoman Divacky     // Create a TreePattern to parse this.
31303861d79fSDimitry Andric     TreePattern P(DefaultOps[i], DI, false, *this);
3131f22ef01cSRoman Divacky     assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
3132f22ef01cSRoman Divacky 
3133f22ef01cSRoman Divacky     // Copy the operands over into a DAGDefaultOperand.
3134f22ef01cSRoman Divacky     DAGDefaultOperand DefaultOpInfo;
3135f22ef01cSRoman Divacky 
31364ba319b5SDimitry Andric     const TreePatternNodePtr &T = P.getTree(0);
3137f22ef01cSRoman Divacky     for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
31384ba319b5SDimitry Andric       TreePatternNodePtr TPN = T->getChildShared(op);
3139f22ef01cSRoman Divacky       while (TPN->ApplyTypeConstraints(P, false))
3140f22ef01cSRoman Divacky         /* Resolve all types */;
3141f22ef01cSRoman Divacky 
31422cab237bSDimitry Andric       if (TPN->ContainsUnresolvedType(P)) {
314391bc56edSDimitry Andric         PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
314491bc56edSDimitry Andric                         DefaultOps[i]->getName() +
314591bc56edSDimitry Andric                         "' doesn't have a concrete type!");
3146f22ef01cSRoman Divacky       }
31474ba319b5SDimitry Andric       DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
3148f22ef01cSRoman Divacky     }
3149f22ef01cSRoman Divacky 
3150f22ef01cSRoman Divacky     // Insert it into the DefaultOperands map so we can find it later.
31513861d79fSDimitry Andric     DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3152f22ef01cSRoman Divacky   }
3153f22ef01cSRoman Divacky }
3154f22ef01cSRoman Divacky 
3155f22ef01cSRoman Divacky /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3156f22ef01cSRoman Divacky /// instruction input.  Return true if this is a real use.
HandleUse(TreePattern & I,TreePatternNodePtr Pat,std::map<std::string,TreePatternNodePtr> & InstInputs)31574ba319b5SDimitry Andric static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
31584ba319b5SDimitry Andric                       std::map<std::string, TreePatternNodePtr> &InstInputs) {
3159f22ef01cSRoman Divacky   // No name -> not interesting.
3160f22ef01cSRoman Divacky   if (Pat->getName().empty()) {
3161f22ef01cSRoman Divacky     if (Pat->isLeaf()) {
31623861d79fSDimitry Andric       DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
316317a519f9SDimitry Andric       if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
316417a519f9SDimitry Andric                  DI->getDef()->isSubClassOf("RegisterOperand")))
31654ba319b5SDimitry Andric         I.error("Input " + DI->getDef()->getName() + " must be named!");
3166f22ef01cSRoman Divacky     }
3167f22ef01cSRoman Divacky     return false;
3168f22ef01cSRoman Divacky   }
3169f22ef01cSRoman Divacky 
3170f22ef01cSRoman Divacky   Record *Rec;
3171f22ef01cSRoman Divacky   if (Pat->isLeaf()) {
31723861d79fSDimitry Andric     DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
31734ba319b5SDimitry Andric     if (!DI)
31744ba319b5SDimitry Andric       I.error("Input $" + Pat->getName() + " must be an identifier!");
3175f22ef01cSRoman Divacky     Rec = DI->getDef();
3176f22ef01cSRoman Divacky   } else {
3177f22ef01cSRoman Divacky     Rec = Pat->getOperator();
3178f22ef01cSRoman Divacky   }
3179f22ef01cSRoman Divacky 
3180f22ef01cSRoman Divacky   // SRCVALUE nodes are ignored.
3181f22ef01cSRoman Divacky   if (Rec->getName() == "srcvalue")
3182f22ef01cSRoman Divacky     return false;
3183f22ef01cSRoman Divacky 
31844ba319b5SDimitry Andric   TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
3185f22ef01cSRoman Divacky   if (!Slot) {
3186f22ef01cSRoman Divacky     Slot = Pat;
3187f22ef01cSRoman Divacky     return true;
3188f22ef01cSRoman Divacky   }
3189f22ef01cSRoman Divacky   Record *SlotRec;
3190f22ef01cSRoman Divacky   if (Slot->isLeaf()) {
31913861d79fSDimitry Andric     SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
3192f22ef01cSRoman Divacky   } else {
3193f22ef01cSRoman Divacky     assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3194f22ef01cSRoman Divacky     SlotRec = Slot->getOperator();
3195f22ef01cSRoman Divacky   }
3196f22ef01cSRoman Divacky 
3197f22ef01cSRoman Divacky   // Ensure that the inputs agree if we've already seen this input.
3198f22ef01cSRoman Divacky   if (Rec != SlotRec)
31994ba319b5SDimitry Andric     I.error("All $" + Pat->getName() + " inputs must agree with each other");
32004ba319b5SDimitry Andric   // Ensure that the types can agree as well.
32014ba319b5SDimitry Andric   Slot->UpdateNodeType(0, Pat->getExtType(0), I);
32024ba319b5SDimitry Andric   Pat->UpdateNodeType(0, Slot->getExtType(0), I);
3203f22ef01cSRoman Divacky   if (Slot->getExtTypes() != Pat->getExtTypes())
32044ba319b5SDimitry Andric     I.error("All $" + Pat->getName() + " inputs must agree with each other");
3205f22ef01cSRoman Divacky   return true;
3206f22ef01cSRoman Divacky }
3207f22ef01cSRoman Divacky 
3208f22ef01cSRoman Divacky /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3209f22ef01cSRoman Divacky /// part of "I", the instruction), computing the set of inputs and outputs of
3210f22ef01cSRoman Divacky /// the pattern.  Report errors if we see anything naughty.
FindPatternInputsAndOutputs(TreePattern & I,TreePatternNodePtr Pat,std::map<std::string,TreePatternNodePtr> & InstInputs,MapVector<std::string,TreePatternNodePtr,std::map<std::string,unsigned>> & InstResults,std::vector<Record * > & InstImpResults)32114ba319b5SDimitry Andric void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
32124ba319b5SDimitry Andric     TreePattern &I, TreePatternNodePtr Pat,
32134ba319b5SDimitry Andric     std::map<std::string, TreePatternNodePtr> &InstInputs,
3214*b5893f02SDimitry Andric     MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3215*b5893f02SDimitry Andric         &InstResults,
3216f22ef01cSRoman Divacky     std::vector<Record *> &InstImpResults) {
32174ba319b5SDimitry Andric 
32184ba319b5SDimitry Andric   // The instruction pattern still has unresolved fragments.  For *named*
32194ba319b5SDimitry Andric   // nodes we must resolve those here.  This may not result in multiple
32204ba319b5SDimitry Andric   // alternatives.
32214ba319b5SDimitry Andric   if (!Pat->getName().empty()) {
32224ba319b5SDimitry Andric     TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
32234ba319b5SDimitry Andric     SrcPattern.InlinePatternFragments();
32244ba319b5SDimitry Andric     SrcPattern.InferAllTypes();
32254ba319b5SDimitry Andric     Pat = SrcPattern.getOnlyTree();
32264ba319b5SDimitry Andric   }
32274ba319b5SDimitry Andric 
3228f22ef01cSRoman Divacky   if (Pat->isLeaf()) {
3229f22ef01cSRoman Divacky     bool isUse = HandleUse(I, Pat, InstInputs);
3230f22ef01cSRoman Divacky     if (!isUse && Pat->getTransformFn())
32314ba319b5SDimitry Andric       I.error("Cannot specify a transform function for a non-input value!");
3232f22ef01cSRoman Divacky     return;
3233f22ef01cSRoman Divacky   }
3234f22ef01cSRoman Divacky 
3235f22ef01cSRoman Divacky   if (Pat->getOperator()->getName() == "implicit") {
3236f22ef01cSRoman Divacky     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3237f22ef01cSRoman Divacky       TreePatternNode *Dest = Pat->getChild(i);
3238f22ef01cSRoman Divacky       if (!Dest->isLeaf())
32394ba319b5SDimitry Andric         I.error("implicitly defined value should be a register!");
3240f22ef01cSRoman Divacky 
32413861d79fSDimitry Andric       DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
3242f22ef01cSRoman Divacky       if (!Val || !Val->getDef()->isSubClassOf("Register"))
32434ba319b5SDimitry Andric         I.error("implicitly defined value should be a register!");
3244f22ef01cSRoman Divacky       InstImpResults.push_back(Val->getDef());
3245f22ef01cSRoman Divacky     }
3246f22ef01cSRoman Divacky     return;
3247f22ef01cSRoman Divacky   }
3248f22ef01cSRoman Divacky 
3249f22ef01cSRoman Divacky   if (Pat->getOperator()->getName() != "set") {
3250f22ef01cSRoman Divacky     // If this is not a set, verify that the children nodes are not void typed,
3251f22ef01cSRoman Divacky     // and recurse.
3252f22ef01cSRoman Divacky     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3253f22ef01cSRoman Divacky       if (Pat->getChild(i)->getNumTypes() == 0)
32544ba319b5SDimitry Andric         I.error("Cannot have void nodes inside of patterns!");
32554ba319b5SDimitry Andric       FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
32564ba319b5SDimitry Andric                                   InstResults, InstImpResults);
3257f22ef01cSRoman Divacky     }
3258f22ef01cSRoman Divacky 
3259f22ef01cSRoman Divacky     // If this is a non-leaf node with no children, treat it basically as if
3260f22ef01cSRoman Divacky     // it were a leaf.  This handles nodes like (imm).
3261f22ef01cSRoman Divacky     bool isUse = HandleUse(I, Pat, InstInputs);
3262f22ef01cSRoman Divacky 
3263f22ef01cSRoman Divacky     if (!isUse && Pat->getTransformFn())
32644ba319b5SDimitry Andric       I.error("Cannot specify a transform function for a non-input value!");
3265f22ef01cSRoman Divacky     return;
3266f22ef01cSRoman Divacky   }
3267f22ef01cSRoman Divacky 
3268f22ef01cSRoman Divacky   // Otherwise, this is a set, validate and collect instruction results.
3269f22ef01cSRoman Divacky   if (Pat->getNumChildren() == 0)
32704ba319b5SDimitry Andric     I.error("set requires operands!");
3271f22ef01cSRoman Divacky 
3272f22ef01cSRoman Divacky   if (Pat->getTransformFn())
32734ba319b5SDimitry Andric     I.error("Cannot specify a transform function on a set node!");
3274f22ef01cSRoman Divacky 
3275f22ef01cSRoman Divacky   // Check the set destinations.
3276f22ef01cSRoman Divacky   unsigned NumDests = Pat->getNumChildren()-1;
3277f22ef01cSRoman Divacky   for (unsigned i = 0; i != NumDests; ++i) {
32784ba319b5SDimitry Andric     TreePatternNodePtr Dest = Pat->getChildShared(i);
32794ba319b5SDimitry Andric     // For set destinations we also must resolve fragments here.
32804ba319b5SDimitry Andric     TreePattern DestPattern(I.getRecord(), Dest, false, *this);
32814ba319b5SDimitry Andric     DestPattern.InlinePatternFragments();
32824ba319b5SDimitry Andric     DestPattern.InferAllTypes();
32834ba319b5SDimitry Andric     Dest = DestPattern.getOnlyTree();
32844ba319b5SDimitry Andric 
3285f22ef01cSRoman Divacky     if (!Dest->isLeaf())
32864ba319b5SDimitry Andric       I.error("set destination should be a register!");
3287f22ef01cSRoman Divacky 
32883861d79fSDimitry Andric     DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
328939d628a0SDimitry Andric     if (!Val) {
32904ba319b5SDimitry Andric       I.error("set destination should be a register!");
329139d628a0SDimitry Andric       continue;
329239d628a0SDimitry Andric     }
3293f22ef01cSRoman Divacky 
3294f22ef01cSRoman Divacky     if (Val->getDef()->isSubClassOf("RegisterClass") ||
3295139f7f9bSDimitry Andric         Val->getDef()->isSubClassOf("ValueType") ||
329617a519f9SDimitry Andric         Val->getDef()->isSubClassOf("RegisterOperand") ||
3297f22ef01cSRoman Divacky         Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
3298f22ef01cSRoman Divacky       if (Dest->getName().empty())
32994ba319b5SDimitry Andric         I.error("set destination must have a name!");
3300f22ef01cSRoman Divacky       if (InstResults.count(Dest->getName()))
33014ba319b5SDimitry Andric         I.error("cannot set '" + Dest->getName() + "' multiple times");
3302f22ef01cSRoman Divacky       InstResults[Dest->getName()] = Dest;
3303f22ef01cSRoman Divacky     } else if (Val->getDef()->isSubClassOf("Register")) {
3304f22ef01cSRoman Divacky       InstImpResults.push_back(Val->getDef());
3305f22ef01cSRoman Divacky     } else {
33064ba319b5SDimitry Andric       I.error("set destination should be a register!");
3307f22ef01cSRoman Divacky     }
3308f22ef01cSRoman Divacky   }
3309f22ef01cSRoman Divacky 
3310f22ef01cSRoman Divacky   // Verify and collect info from the computation.
33114ba319b5SDimitry Andric   FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
33124ba319b5SDimitry Andric                               InstResults, InstImpResults);
3313f22ef01cSRoman Divacky }
3314f22ef01cSRoman Divacky 
3315f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
3316f22ef01cSRoman Divacky // Instruction Analysis
3317f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
3318f22ef01cSRoman Divacky 
3319f22ef01cSRoman Divacky class InstAnalyzer {
3320f22ef01cSRoman Divacky   const CodeGenDAGPatterns &CDP;
3321f22ef01cSRoman Divacky public:
33223861d79fSDimitry Andric   bool hasSideEffects;
33233861d79fSDimitry Andric   bool mayStore;
33243861d79fSDimitry Andric   bool mayLoad;
33253861d79fSDimitry Andric   bool isBitcast;
33263861d79fSDimitry Andric   bool isVariadic;
33274ba319b5SDimitry Andric   bool hasChain;
33283861d79fSDimitry Andric 
InstAnalyzer(const CodeGenDAGPatterns & cdp)33293861d79fSDimitry Andric   InstAnalyzer(const CodeGenDAGPatterns &cdp)
33303861d79fSDimitry Andric     : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
33314ba319b5SDimitry Andric       isBitcast(false), isVariadic(false), hasChain(false) {}
3332f22ef01cSRoman Divacky 
Analyze(const PatternToMatch & Pat)3333edd7eaddSDimitry Andric   void Analyze(const PatternToMatch &Pat) {
33344ba319b5SDimitry Andric     const TreePatternNode *N = Pat.getSrcPattern();
33354ba319b5SDimitry Andric     AnalyzeNode(N);
33364ba319b5SDimitry Andric     // These properties are detected only on the root node.
33374ba319b5SDimitry Andric     isBitcast = IsNodeBitcast(N);
3338f22ef01cSRoman Divacky   }
3339f22ef01cSRoman Divacky 
3340f22ef01cSRoman Divacky private:
IsNodeBitcast(const TreePatternNode * N) const33413b0f4066SDimitry Andric   bool IsNodeBitcast(const TreePatternNode *N) const {
33423861d79fSDimitry Andric     if (hasSideEffects || mayLoad || mayStore || isVariadic)
33433b0f4066SDimitry Andric       return false;
33443b0f4066SDimitry Andric 
33454ba319b5SDimitry Andric     if (N->isLeaf())
33464ba319b5SDimitry Andric       return false;
33474ba319b5SDimitry Andric     if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
33483b0f4066SDimitry Andric       return false;
33493b0f4066SDimitry Andric 
33504ba319b5SDimitry Andric     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
33513b0f4066SDimitry Andric     if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
33523b0f4066SDimitry Andric       return false;
33533b0f4066SDimitry Andric     return OpInfo.getEnumName() == "ISD::BITCAST";
33543b0f4066SDimitry Andric   }
33553b0f4066SDimitry Andric 
33563861d79fSDimitry Andric public:
AnalyzeNode(const TreePatternNode * N)3357f22ef01cSRoman Divacky   void AnalyzeNode(const TreePatternNode *N) {
3358f22ef01cSRoman Divacky     if (N->isLeaf()) {
33593861d79fSDimitry Andric       if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
3360f22ef01cSRoman Divacky         Record *LeafRec = DI->getDef();
3361f22ef01cSRoman Divacky         // Handle ComplexPattern leaves.
3362f22ef01cSRoman Divacky         if (LeafRec->isSubClassOf("ComplexPattern")) {
3363f22ef01cSRoman Divacky           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3364f22ef01cSRoman Divacky           if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3365f22ef01cSRoman Divacky           if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
33663861d79fSDimitry Andric           if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
3367f22ef01cSRoman Divacky         }
3368f22ef01cSRoman Divacky       }
3369f22ef01cSRoman Divacky       return;
3370f22ef01cSRoman Divacky     }
3371f22ef01cSRoman Divacky 
3372f22ef01cSRoman Divacky     // Analyze children.
3373f22ef01cSRoman Divacky     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3374f22ef01cSRoman Divacky       AnalyzeNode(N->getChild(i));
3375f22ef01cSRoman Divacky 
3376f22ef01cSRoman Divacky     // Notice properties of the node.
337791bc56edSDimitry Andric     if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
337891bc56edSDimitry Andric     if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
337991bc56edSDimitry Andric     if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
338091bc56edSDimitry Andric     if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
33814ba319b5SDimitry Andric     if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
3382f22ef01cSRoman Divacky 
3383f22ef01cSRoman Divacky     if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3384f22ef01cSRoman Divacky       // If this is an intrinsic, analyze it.
33853ca95b02SDimitry Andric       if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
3386f22ef01cSRoman Divacky         mayLoad = true;// These may load memory.
3387f22ef01cSRoman Divacky 
33883ca95b02SDimitry Andric       if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
3389f22ef01cSRoman Divacky         mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3390f22ef01cSRoman Divacky 
3391f37b6182SDimitry Andric       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3392f37b6182SDimitry Andric           IntInfo->hasSideEffects)
33933ca95b02SDimitry Andric         // ReadWriteMem intrinsics can have other strange effects.
33943861d79fSDimitry Andric         hasSideEffects = true;
3395f22ef01cSRoman Divacky     }
3396f22ef01cSRoman Divacky   }
3397f22ef01cSRoman Divacky 
3398f22ef01cSRoman Divacky };
3399f22ef01cSRoman Divacky 
InferFromPattern(CodeGenInstruction & InstInfo,const InstAnalyzer & PatInfo,Record * PatDef)34003861d79fSDimitry Andric static bool InferFromPattern(CodeGenInstruction &InstInfo,
34013861d79fSDimitry Andric                              const InstAnalyzer &PatInfo,
34023861d79fSDimitry Andric                              Record *PatDef) {
34033861d79fSDimitry Andric   bool Error = false;
3404f22ef01cSRoman Divacky 
34053861d79fSDimitry Andric   // Remember where InstInfo got its flags.
34063861d79fSDimitry Andric   if (InstInfo.hasUndefFlags())
34073861d79fSDimitry Andric       InstInfo.InferredFrom = PatDef;
3408f22ef01cSRoman Divacky 
34093861d79fSDimitry Andric   // Check explicitly set flags for consistency.
34103861d79fSDimitry Andric   if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
34113861d79fSDimitry Andric       !InstInfo.hasSideEffects_Unset) {
34123861d79fSDimitry Andric     // Allow explicitly setting hasSideEffects = 1 on instructions, even when
34133861d79fSDimitry Andric     // the pattern has no side effects. That could be useful for div/rem
34143861d79fSDimitry Andric     // instructions that may trap.
34153861d79fSDimitry Andric     if (!InstInfo.hasSideEffects) {
34163861d79fSDimitry Andric       Error = true;
34173861d79fSDimitry Andric       PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
34183861d79fSDimitry Andric                  Twine(InstInfo.hasSideEffects));
34193861d79fSDimitry Andric     }
3420f22ef01cSRoman Divacky   }
3421f22ef01cSRoman Divacky 
34223861d79fSDimitry Andric   if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
34233861d79fSDimitry Andric     Error = true;
34243861d79fSDimitry Andric     PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
34253861d79fSDimitry Andric                Twine(InstInfo.mayStore));
3426f22ef01cSRoman Divacky   }
3427f22ef01cSRoman Divacky 
34283861d79fSDimitry Andric   if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
34293861d79fSDimitry Andric     // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
34307d523365SDimitry Andric     // Some targets translate immediates to loads.
34313861d79fSDimitry Andric     if (!InstInfo.mayLoad) {
34323861d79fSDimitry Andric       Error = true;
34333861d79fSDimitry Andric       PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
34343861d79fSDimitry Andric                  Twine(InstInfo.mayLoad));
34353861d79fSDimitry Andric     }
3436f22ef01cSRoman Divacky   }
3437f22ef01cSRoman Divacky 
34383861d79fSDimitry Andric   // Transfer inferred flags.
34393861d79fSDimitry Andric   InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
34403861d79fSDimitry Andric   InstInfo.mayStore |= PatInfo.mayStore;
34413861d79fSDimitry Andric   InstInfo.mayLoad |= PatInfo.mayLoad;
3442f22ef01cSRoman Divacky 
34433861d79fSDimitry Andric   // These flags are silently added without any verification.
34444ba319b5SDimitry Andric   // FIXME: To match historical behavior of TableGen, for now add those flags
34454ba319b5SDimitry Andric   // only when we're inferring from the primary instruction pattern.
34464ba319b5SDimitry Andric   if (PatDef->isSubClassOf("Instruction")) {
34473861d79fSDimitry Andric     InstInfo.isBitcast |= PatInfo.isBitcast;
34484ba319b5SDimitry Andric     InstInfo.hasChain |= PatInfo.hasChain;
34494ba319b5SDimitry Andric     InstInfo.hasChain_Inferred = true;
34504ba319b5SDimitry Andric   }
34513861d79fSDimitry Andric 
34523861d79fSDimitry Andric   // Don't infer isVariadic. This flag means something different on SDNodes and
34533861d79fSDimitry Andric   // instructions. For example, a CALL SDNode is variadic because it has the
34543861d79fSDimitry Andric   // call arguments as operands, but a CALL instruction is not variadic - it
34553861d79fSDimitry Andric   // has argument registers as implicit, not explicit uses.
34563861d79fSDimitry Andric 
34573861d79fSDimitry Andric   return Error;
3458f22ef01cSRoman Divacky }
3459f22ef01cSRoman Divacky 
34607ae0e2c9SDimitry Andric /// hasNullFragReference - Return true if the DAG has any reference to the
34617ae0e2c9SDimitry Andric /// null_frag operator.
hasNullFragReference(DagInit * DI)34627ae0e2c9SDimitry Andric static bool hasNullFragReference(DagInit *DI) {
34633861d79fSDimitry Andric   DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
34647ae0e2c9SDimitry Andric   if (!OpDef) return false;
34657ae0e2c9SDimitry Andric   Record *Operator = OpDef->getDef();
34667ae0e2c9SDimitry Andric 
34677ae0e2c9SDimitry Andric   // If this is the null fragment, return true.
34687ae0e2c9SDimitry Andric   if (Operator->getName() == "null_frag") return true;
34697ae0e2c9SDimitry Andric   // If any of the arguments reference the null fragment, return true.
34707ae0e2c9SDimitry Andric   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
34713861d79fSDimitry Andric     DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
34727ae0e2c9SDimitry Andric     if (Arg && hasNullFragReference(Arg))
34737ae0e2c9SDimitry Andric       return true;
34747ae0e2c9SDimitry Andric   }
34757ae0e2c9SDimitry Andric 
34767ae0e2c9SDimitry Andric   return false;
34777ae0e2c9SDimitry Andric }
34787ae0e2c9SDimitry Andric 
34797ae0e2c9SDimitry Andric /// hasNullFragReference - Return true if any DAG in the list references
34807ae0e2c9SDimitry Andric /// the null_frag operator.
hasNullFragReference(ListInit * LI)34817ae0e2c9SDimitry Andric static bool hasNullFragReference(ListInit *LI) {
348297bc6c73SDimitry Andric   for (Init *I : LI->getValues()) {
348397bc6c73SDimitry Andric     DagInit *DI = dyn_cast<DagInit>(I);
34847ae0e2c9SDimitry Andric     assert(DI && "non-dag in an instruction Pattern list?!");
34857ae0e2c9SDimitry Andric     if (hasNullFragReference(DI))
34867ae0e2c9SDimitry Andric       return true;
34877ae0e2c9SDimitry Andric   }
34887ae0e2c9SDimitry Andric   return false;
34897ae0e2c9SDimitry Andric }
34907ae0e2c9SDimitry Andric 
34913861d79fSDimitry Andric /// Get all the instructions in a tree.
34923861d79fSDimitry Andric static void
getInstructionsInTree(TreePatternNode * Tree,SmallVectorImpl<Record * > & Instrs)34933861d79fSDimitry Andric getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
34943861d79fSDimitry Andric   if (Tree->isLeaf())
34953861d79fSDimitry Andric     return;
34963861d79fSDimitry Andric   if (Tree->getOperator()->isSubClassOf("Instruction"))
34973861d79fSDimitry Andric     Instrs.push_back(Tree->getOperator());
34983861d79fSDimitry Andric   for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
34993861d79fSDimitry Andric     getInstructionsInTree(Tree->getChild(i), Instrs);
35003861d79fSDimitry Andric }
35013861d79fSDimitry Andric 
3502139f7f9bSDimitry Andric /// Check the class of a pattern leaf node against the instruction operand it
3503139f7f9bSDimitry Andric /// represents.
checkOperandClass(CGIOperandList::OperandInfo & OI,Record * Leaf)3504139f7f9bSDimitry Andric static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3505139f7f9bSDimitry Andric                               Record *Leaf) {
3506139f7f9bSDimitry Andric   if (OI.Rec == Leaf)
3507139f7f9bSDimitry Andric     return true;
3508139f7f9bSDimitry Andric 
3509139f7f9bSDimitry Andric   // Allow direct value types to be used in instruction set patterns.
3510139f7f9bSDimitry Andric   // The type will be checked later.
3511139f7f9bSDimitry Andric   if (Leaf->isSubClassOf("ValueType"))
3512139f7f9bSDimitry Andric     return true;
3513139f7f9bSDimitry Andric 
3514139f7f9bSDimitry Andric   // Patterns can also be ComplexPattern instances.
3515139f7f9bSDimitry Andric   if (Leaf->isSubClassOf("ComplexPattern"))
3516139f7f9bSDimitry Andric     return true;
3517139f7f9bSDimitry Andric 
3518139f7f9bSDimitry Andric   return false;
3519139f7f9bSDimitry Andric }
3520139f7f9bSDimitry Andric 
parseInstructionPattern(CodeGenInstruction & CGI,ListInit * Pat,DAGInstMap & DAGInsts)35214ba319b5SDimitry Andric void CodeGenDAGPatterns::parseInstructionPattern(
3522f785676fSDimitry Andric     CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
3523f22ef01cSRoman Divacky 
3524f785676fSDimitry Andric   assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
3525f22ef01cSRoman Divacky 
3526f22ef01cSRoman Divacky   // Parse the instruction.
35274ba319b5SDimitry Andric   TreePattern I(CGI.TheDef, Pat, true, *this);
3528f22ef01cSRoman Divacky 
3529f22ef01cSRoman Divacky   // InstInputs - Keep track of all of the inputs of the instruction, along
3530f22ef01cSRoman Divacky   // with the record they are declared as.
35314ba319b5SDimitry Andric   std::map<std::string, TreePatternNodePtr> InstInputs;
3532f22ef01cSRoman Divacky 
3533f22ef01cSRoman Divacky   // InstResults - Keep track of all the virtual registers that are 'set'
3534f22ef01cSRoman Divacky   // in the instruction, including what reg class they are.
3535*b5893f02SDimitry Andric   MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3536*b5893f02SDimitry Andric       InstResults;
3537f22ef01cSRoman Divacky 
3538f22ef01cSRoman Divacky   std::vector<Record*> InstImpResults;
3539f22ef01cSRoman Divacky 
3540f22ef01cSRoman Divacky   // Verify that the top-level forms in the instruction are of void type, and
3541f22ef01cSRoman Divacky   // fill in the InstResults map.
35422cab237bSDimitry Andric   SmallString<32> TypesString;
35434ba319b5SDimitry Andric   for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
35442cab237bSDimitry Andric     TypesString.clear();
35454ba319b5SDimitry Andric     TreePatternNodePtr Pat = I.getTree(j);
35463ca95b02SDimitry Andric     if (Pat->getNumTypes() != 0) {
35472cab237bSDimitry Andric       raw_svector_ostream OS(TypesString);
35483ca95b02SDimitry Andric       for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
35493ca95b02SDimitry Andric         if (k > 0)
35502cab237bSDimitry Andric           OS << ", ";
35512cab237bSDimitry Andric         Pat->getExtType(k).writeToStream(OS);
35523ca95b02SDimitry Andric       }
35534ba319b5SDimitry Andric       I.error("Top-level forms in instruction pattern should have"
35542cab237bSDimitry Andric                " void types, has types " +
35552cab237bSDimitry Andric                OS.str());
35563ca95b02SDimitry Andric     }
3557f22ef01cSRoman Divacky 
3558f22ef01cSRoman Divacky     // Find inputs and outputs, and verify the structure of the uses/defs.
3559f22ef01cSRoman Divacky     FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3560f22ef01cSRoman Divacky                                 InstImpResults);
3561f22ef01cSRoman Divacky   }
3562f22ef01cSRoman Divacky 
3563f22ef01cSRoman Divacky   // Now that we have inputs and outputs of the pattern, inspect the operands
3564f22ef01cSRoman Divacky   // list for the instruction.  This determines the order that operands are
3565f22ef01cSRoman Divacky   // added to the machine instruction the node corresponds to.
3566f22ef01cSRoman Divacky   unsigned NumResults = InstResults.size();
3567f22ef01cSRoman Divacky 
3568f22ef01cSRoman Divacky   // Parse the operands list from the (ops) list, validating it.
35694ba319b5SDimitry Andric   assert(I.getArgList().empty() && "Args list should still be empty here!");
3570f22ef01cSRoman Divacky 
3571f22ef01cSRoman Divacky   // Check that all of the results occur first in the list.
3572f22ef01cSRoman Divacky   std::vector<Record*> Results;
3573*b5893f02SDimitry Andric   std::vector<unsigned> ResultIndices;
35744ba319b5SDimitry Andric   SmallVector<TreePatternNodePtr, 2> ResNodes;
3575f22ef01cSRoman Divacky   for (unsigned i = 0; i != NumResults; ++i) {
3576*b5893f02SDimitry Andric     if (i == CGI.Operands.size()) {
3577*b5893f02SDimitry Andric       const std::string &OpName =
3578*b5893f02SDimitry Andric           std::find_if(InstResults.begin(), InstResults.end(),
3579*b5893f02SDimitry Andric                        [](const std::pair<std::string, TreePatternNodePtr> &P) {
3580*b5893f02SDimitry Andric                          return P.second;
3581*b5893f02SDimitry Andric                        })
3582*b5893f02SDimitry Andric               ->first;
3583*b5893f02SDimitry Andric 
3584*b5893f02SDimitry Andric       I.error("'" + OpName + "' set but does not appear in operand list!");
3585*b5893f02SDimitry Andric     }
3586*b5893f02SDimitry Andric 
35872754fe60SDimitry Andric     const std::string &OpName = CGI.Operands[i].Name;
3588f22ef01cSRoman Divacky 
3589f22ef01cSRoman Divacky     // Check that it exists in InstResults.
3590*b5893f02SDimitry Andric     auto InstResultIter = InstResults.find(OpName);
3591*b5893f02SDimitry Andric     if (InstResultIter == InstResults.end() || !InstResultIter->second)
35924ba319b5SDimitry Andric       I.error("Operand $" + OpName + " does not exist in operand list!");
3593f22ef01cSRoman Divacky 
3594*b5893f02SDimitry Andric     TreePatternNodePtr RNode = InstResultIter->second;
35953861d79fSDimitry Andric     Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
35964ba319b5SDimitry Andric     ResNodes.push_back(std::move(RNode));
359791bc56edSDimitry Andric     if (!R)
35984ba319b5SDimitry Andric       I.error("Operand $" + OpName + " should be a set destination: all "
3599f22ef01cSRoman Divacky                "outputs must occur before inputs in operand list!");
3600f22ef01cSRoman Divacky 
3601139f7f9bSDimitry Andric     if (!checkOperandClass(CGI.Operands[i], R))
36024ba319b5SDimitry Andric       I.error("Operand $" + OpName + " class mismatch!");
3603f22ef01cSRoman Divacky 
3604f22ef01cSRoman Divacky     // Remember the return type.
36052754fe60SDimitry Andric     Results.push_back(CGI.Operands[i].Rec);
3606f22ef01cSRoman Divacky 
3607*b5893f02SDimitry Andric     // Remember the result index.
3608*b5893f02SDimitry Andric     ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
3609*b5893f02SDimitry Andric 
3610f22ef01cSRoman Divacky     // Okay, this one checks out.
3611*b5893f02SDimitry Andric     InstResultIter->second = nullptr;
3612f22ef01cSRoman Divacky   }
3613f22ef01cSRoman Divacky 
36144ba319b5SDimitry Andric   // Loop over the inputs next.
36154ba319b5SDimitry Andric   std::vector<TreePatternNodePtr> ResultNodeOperands;
3616f22ef01cSRoman Divacky   std::vector<Record*> Operands;
36172754fe60SDimitry Andric   for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
36182754fe60SDimitry Andric     CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3619f22ef01cSRoman Divacky     const std::string &OpName = Op.Name;
3620f22ef01cSRoman Divacky     if (OpName.empty())
36214ba319b5SDimitry Andric       I.error("Operand #" + Twine(i) + " in operands list has no name!");
3622f22ef01cSRoman Divacky 
36234ba319b5SDimitry Andric     if (!InstInputs.count(OpName)) {
36243861d79fSDimitry Andric       // If this is an operand with a DefaultOps set filled in, we can ignore
36253861d79fSDimitry Andric       // this.  When we codegen it, we will do so as always executed.
36263861d79fSDimitry Andric       if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3627f22ef01cSRoman Divacky         // Does it have a non-empty DefaultOps field?  If so, ignore this
3628f22ef01cSRoman Divacky         // operand.
3629f22ef01cSRoman Divacky         if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3630f22ef01cSRoman Divacky           continue;
3631f22ef01cSRoman Divacky       }
36324ba319b5SDimitry Andric       I.error("Operand $" + OpName +
3633f22ef01cSRoman Divacky                " does not appear in the instruction pattern");
3634f22ef01cSRoman Divacky     }
36354ba319b5SDimitry Andric     TreePatternNodePtr InVal = InstInputs[OpName];
36364ba319b5SDimitry Andric     InstInputs.erase(OpName);   // It occurred, remove from map.
3637f22ef01cSRoman Divacky 
36383861d79fSDimitry Andric     if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3639f22ef01cSRoman Divacky       Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3640139f7f9bSDimitry Andric       if (!checkOperandClass(Op, InRec))
36414ba319b5SDimitry Andric         I.error("Operand $" + OpName + "'s register class disagrees"
3642f22ef01cSRoman Divacky                  " between the operand and pattern");
3643f22ef01cSRoman Divacky     }
3644f22ef01cSRoman Divacky     Operands.push_back(Op.Rec);
3645f22ef01cSRoman Divacky 
3646f22ef01cSRoman Divacky     // Construct the result for the dest-pattern operand list.
36474ba319b5SDimitry Andric     TreePatternNodePtr OpNode = InVal->clone();
3648f22ef01cSRoman Divacky 
3649f22ef01cSRoman Divacky     // No predicate is useful on the result.
3650*b5893f02SDimitry Andric     OpNode->clearPredicateCalls();
3651f22ef01cSRoman Divacky 
3652f22ef01cSRoman Divacky     // Promote the xform function to be an explicit node if set.
3653f22ef01cSRoman Divacky     if (Record *Xform = OpNode->getTransformFn()) {
365491bc56edSDimitry Andric       OpNode->setTransformFn(nullptr);
36554ba319b5SDimitry Andric       std::vector<TreePatternNodePtr> Children;
3656f22ef01cSRoman Divacky       Children.push_back(OpNode);
36574ba319b5SDimitry Andric       OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
36584ba319b5SDimitry Andric                                                  OpNode->getNumTypes());
3659f22ef01cSRoman Divacky     }
3660f22ef01cSRoman Divacky 
36614ba319b5SDimitry Andric     ResultNodeOperands.push_back(std::move(OpNode));
3662f22ef01cSRoman Divacky   }
3663f22ef01cSRoman Divacky 
36644ba319b5SDimitry Andric   if (!InstInputs.empty())
36654ba319b5SDimitry Andric     I.error("Input operand $" + InstInputs.begin()->first +
3666f22ef01cSRoman Divacky             " occurs in pattern but not in operands list!");
3667f22ef01cSRoman Divacky 
36684ba319b5SDimitry Andric   TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
36694ba319b5SDimitry Andric       I.getRecord(), std::move(ResultNodeOperands),
36704ba319b5SDimitry Andric       GetNumNodeResults(I.getRecord(), *this));
3671ff0cc061SDimitry Andric   // Copy fully inferred output node types to instruction result pattern.
3672ff0cc061SDimitry Andric   for (unsigned i = 0; i != NumResults; ++i) {
3673ff0cc061SDimitry Andric     assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3674ff0cc061SDimitry Andric     ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3675*b5893f02SDimitry Andric     ResultPattern->setResultIndex(i, ResultIndices[i]);
3676ff0cc061SDimitry Andric   }
3677f22ef01cSRoman Divacky 
36784ba319b5SDimitry Andric   // FIXME: Assume only the first tree is the pattern. The others are clobber
36794ba319b5SDimitry Andric   // nodes.
36804ba319b5SDimitry Andric   TreePatternNodePtr Pattern = I.getTree(0);
36814ba319b5SDimitry Andric   TreePatternNodePtr SrcPattern;
36824ba319b5SDimitry Andric   if (Pattern->getOperator()->getName() == "set") {
36834ba319b5SDimitry Andric     SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
36844ba319b5SDimitry Andric   } else{
36854ba319b5SDimitry Andric     // Not a set (store or something?)
36864ba319b5SDimitry Andric     SrcPattern = Pattern;
36874ba319b5SDimitry Andric   }
36884ba319b5SDimitry Andric 
3689f22ef01cSRoman Divacky   // Create and insert the instruction.
3690f22ef01cSRoman Divacky   // FIXME: InstImpResults should not be part of DAGInstruction.
36914ba319b5SDimitry Andric   Record *R = I.getRecord();
36924ba319b5SDimitry Andric   DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
36934ba319b5SDimitry Andric                    std::forward_as_tuple(Results, Operands, InstImpResults,
36944ba319b5SDimitry Andric                                          SrcPattern, ResultPattern));
3695f22ef01cSRoman Divacky 
36964ba319b5SDimitry Andric   LLVM_DEBUG(I.dump());
3697f785676fSDimitry Andric }
3698f785676fSDimitry Andric 
3699f785676fSDimitry Andric /// ParseInstructions - Parse all of the instructions, inlining and resolving
3700f785676fSDimitry Andric /// any fragments involved.  This populates the Instructions list with fully
3701f785676fSDimitry Andric /// resolved instructions.
ParseInstructions()3702f785676fSDimitry Andric void CodeGenDAGPatterns::ParseInstructions() {
3703f785676fSDimitry Andric   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3704f785676fSDimitry Andric 
37057d523365SDimitry Andric   for (Record *Instr : Instrs) {
370691bc56edSDimitry Andric     ListInit *LI = nullptr;
3707f785676fSDimitry Andric 
37087d523365SDimitry Andric     if (isa<ListInit>(Instr->getValueInit("Pattern")))
37097d523365SDimitry Andric       LI = Instr->getValueAsListInit("Pattern");
3710f785676fSDimitry Andric 
3711f785676fSDimitry Andric     // If there is no pattern, only collect minimal information about the
3712f785676fSDimitry Andric     // instruction for its operand list.  We have to assume that there is one
3713f785676fSDimitry Andric     // result, as we have no detailed info. A pattern which references the
3714f785676fSDimitry Andric     // null_frag operator is as-if no pattern were specified. Normally this
3715f785676fSDimitry Andric     // is from a multiclass expansion w/ a SDPatternOperator passed in as
3716f785676fSDimitry Andric     // null_frag.
3717ff0cc061SDimitry Andric     if (!LI || LI->empty() || hasNullFragReference(LI)) {
3718f785676fSDimitry Andric       std::vector<Record*> Results;
3719f785676fSDimitry Andric       std::vector<Record*> Operands;
3720f785676fSDimitry Andric 
37217d523365SDimitry Andric       CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3722f785676fSDimitry Andric 
3723f785676fSDimitry Andric       if (InstInfo.Operands.size() != 0) {
3724ff0cc061SDimitry Andric         for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3725ff0cc061SDimitry Andric           Results.push_back(InstInfo.Operands[j].Rec);
3726f785676fSDimitry Andric 
3727f785676fSDimitry Andric         // The rest are inputs.
3728ff0cc061SDimitry Andric         for (unsigned j = InstInfo.Operands.NumDefs,
3729ff0cc061SDimitry Andric                e = InstInfo.Operands.size(); j < e; ++j)
3730f785676fSDimitry Andric           Operands.push_back(InstInfo.Operands[j].Rec);
3731f785676fSDimitry Andric       }
3732f785676fSDimitry Andric 
3733f785676fSDimitry Andric       // Create and insert the instruction.
3734f785676fSDimitry Andric       std::vector<Record*> ImpResults;
37357d523365SDimitry Andric       Instructions.insert(std::make_pair(Instr,
37364ba319b5SDimitry Andric                             DAGInstruction(Results, Operands, ImpResults)));
3737f785676fSDimitry Andric       continue;  // no pattern.
3738f785676fSDimitry Andric     }
3739f785676fSDimitry Andric 
37407d523365SDimitry Andric     CodeGenInstruction &CGI = Target.getInstruction(Instr);
37414ba319b5SDimitry Andric     parseInstructionPattern(CGI, LI, Instructions);
3742f22ef01cSRoman Divacky   }
3743f22ef01cSRoman Divacky 
3744f22ef01cSRoman Divacky   // If we can, convert the instructions to be patterns that are matched!
37457d523365SDimitry Andric   for (auto &Entry : Instructions) {
37467d523365SDimitry Andric     Record *Instr = Entry.first;
37474ba319b5SDimitry Andric     DAGInstruction &TheInst = Entry.second;
37484ba319b5SDimitry Andric     TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
37494ba319b5SDimitry Andric     TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
37504ba319b5SDimitry Andric 
37514ba319b5SDimitry Andric     if (SrcPattern && ResultPattern) {
37524ba319b5SDimitry Andric       TreePattern Pattern(Instr, SrcPattern, true, *this);
37534ba319b5SDimitry Andric       TreePattern Result(Instr, ResultPattern, false, *this);
37544ba319b5SDimitry Andric       ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
37554ba319b5SDimitry Andric     }
3756f22ef01cSRoman Divacky   }
3757f22ef01cSRoman Divacky }
3758f22ef01cSRoman Divacky 
37594ba319b5SDimitry Andric typedef std::pair<TreePatternNode *, unsigned> NameRecord;
3760f22ef01cSRoman Divacky 
FindNames(TreePatternNode * P,std::map<std::string,NameRecord> & Names,TreePattern * PatternTop)37614ba319b5SDimitry Andric static void FindNames(TreePatternNode *P,
3762f22ef01cSRoman Divacky                       std::map<std::string, NameRecord> &Names,
37633861d79fSDimitry Andric                       TreePattern *PatternTop) {
3764f22ef01cSRoman Divacky   if (!P->getName().empty()) {
3765f22ef01cSRoman Divacky     NameRecord &Rec = Names[P->getName()];
3766f22ef01cSRoman Divacky     // If this is the first instance of the name, remember the node.
3767f22ef01cSRoman Divacky     if (Rec.second++ == 0)
3768f22ef01cSRoman Divacky       Rec.first = P;
3769f22ef01cSRoman Divacky     else if (Rec.first->getExtTypes() != P->getExtTypes())
3770f22ef01cSRoman Divacky       PatternTop->error("repetition of value: $" + P->getName() +
3771f22ef01cSRoman Divacky                         " where different uses have different types!");
3772f22ef01cSRoman Divacky   }
3773f22ef01cSRoman Divacky 
3774f22ef01cSRoman Divacky   if (!P->isLeaf()) {
3775f22ef01cSRoman Divacky     for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3776f22ef01cSRoman Divacky       FindNames(P->getChild(i), Names, PatternTop);
3777f22ef01cSRoman Divacky   }
3778f22ef01cSRoman Divacky }
3779f22ef01cSRoman Divacky 
makePredList(ListInit * L)37802cab237bSDimitry Andric std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
37812cab237bSDimitry Andric   std::vector<Predicate> Preds;
37822cab237bSDimitry Andric   for (Init *I : L->getValues()) {
37832cab237bSDimitry Andric     if (DefInit *Pred = dyn_cast<DefInit>(I))
37842cab237bSDimitry Andric       Preds.push_back(Pred->getDef());
37852cab237bSDimitry Andric     else
37862cab237bSDimitry Andric       llvm_unreachable("Non-def on the list");
37872cab237bSDimitry Andric   }
37882cab237bSDimitry Andric 
37892cab237bSDimitry Andric   // Sort so that different orders get canonicalized to the same string.
3790*b5893f02SDimitry Andric   llvm::sort(Preds);
37912cab237bSDimitry Andric   return Preds;
37922cab237bSDimitry Andric }
37932cab237bSDimitry Andric 
AddPatternToMatch(TreePattern * Pattern,PatternToMatch && PTM)37943861d79fSDimitry Andric void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3795edd7eaddSDimitry Andric                                            PatternToMatch &&PTM) {
3796f22ef01cSRoman Divacky   // Do some sanity checking on the pattern we're about to match.
3797f22ef01cSRoman Divacky   std::string Reason;
37983861d79fSDimitry Andric   if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
37993861d79fSDimitry Andric     PrintWarning(Pattern->getRecord()->getLoc(),
38003861d79fSDimitry Andric       Twine("Pattern can never match: ") + Reason);
38013861d79fSDimitry Andric     return;
38023861d79fSDimitry Andric   }
3803f22ef01cSRoman Divacky 
3804f22ef01cSRoman Divacky   // If the source pattern's root is a complex pattern, that complex pattern
3805f22ef01cSRoman Divacky   // must specify the nodes it can potentially match.
3806f22ef01cSRoman Divacky   if (const ComplexPattern *CP =
3807f22ef01cSRoman Divacky         PTM.getSrcPattern()->getComplexPatternInfo(*this))
3808f22ef01cSRoman Divacky     if (CP->getRootNodes().empty())
3809f22ef01cSRoman Divacky       Pattern->error("ComplexPattern at root must specify list of opcodes it"
3810f22ef01cSRoman Divacky                      " could match");
3811f22ef01cSRoman Divacky 
3812f22ef01cSRoman Divacky 
3813f22ef01cSRoman Divacky   // Find all of the named values in the input and output, ensure they have the
3814f22ef01cSRoman Divacky   // same type.
3815f22ef01cSRoman Divacky   std::map<std::string, NameRecord> SrcNames, DstNames;
3816f22ef01cSRoman Divacky   FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3817f22ef01cSRoman Divacky   FindNames(PTM.getDstPattern(), DstNames, Pattern);
3818f22ef01cSRoman Divacky 
3819f22ef01cSRoman Divacky   // Scan all of the named values in the destination pattern, rejecting them if
3820f22ef01cSRoman Divacky   // they don't exist in the input pattern.
38217d523365SDimitry Andric   for (const auto &Entry : DstNames) {
38227d523365SDimitry Andric     if (SrcNames[Entry.first].first == nullptr)
3823f22ef01cSRoman Divacky       Pattern->error("Pattern has input without matching name in output: $" +
38247d523365SDimitry Andric                      Entry.first);
3825f22ef01cSRoman Divacky   }
3826f22ef01cSRoman Divacky 
3827f22ef01cSRoman Divacky   // Scan all of the named values in the source pattern, rejecting them if the
3828f22ef01cSRoman Divacky   // name isn't used in the dest, and isn't used to tie two values together.
38297d523365SDimitry Andric   for (const auto &Entry : SrcNames)
38307d523365SDimitry Andric     if (DstNames[Entry.first].first == nullptr &&
38317d523365SDimitry Andric         SrcNames[Entry.first].second == 1)
38327d523365SDimitry Andric       Pattern->error("Pattern has dead named input: $" + Entry.first);
3833f22ef01cSRoman Divacky 
38344ba319b5SDimitry Andric   PatternsToMatch.push_back(PTM);
3835f22ef01cSRoman Divacky }
3836f22ef01cSRoman Divacky 
InferInstructionFlags()3837f22ef01cSRoman Divacky void CodeGenDAGPatterns::InferInstructionFlags() {
38383ca95b02SDimitry Andric   ArrayRef<const CodeGenInstruction*> Instructions =
3839f22ef01cSRoman Divacky     Target.getInstructionsByEnumValue();
38403861d79fSDimitry Andric 
38413861d79fSDimitry Andric   unsigned Errors = 0;
38426122f3e6SDimitry Andric 
38434ba319b5SDimitry Andric   // Try to infer flags from all patterns in PatternToMatch.  These include
38444ba319b5SDimitry Andric   // both the primary instruction patterns (which always come first) and
38454ba319b5SDimitry Andric   // patterns defined outside the instruction.
3846edd7eaddSDimitry Andric   for (const PatternToMatch &PTM : ptms()) {
38473861d79fSDimitry Andric     // We can only infer from single-instruction patterns, otherwise we won't
38483861d79fSDimitry Andric     // know which instruction should get the flags.
38493861d79fSDimitry Andric     SmallVector<Record*, 8> PatInstrs;
38503861d79fSDimitry Andric     getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
38513861d79fSDimitry Andric     if (PatInstrs.size() != 1)
38523861d79fSDimitry Andric       continue;
38533861d79fSDimitry Andric 
38543861d79fSDimitry Andric     // Get the single instruction.
38553861d79fSDimitry Andric     CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
38563861d79fSDimitry Andric 
38573861d79fSDimitry Andric     // Only infer properties from the first pattern. We'll verify the others.
38583861d79fSDimitry Andric     if (InstInfo.InferredFrom)
38593861d79fSDimitry Andric       continue;
38603861d79fSDimitry Andric 
38613861d79fSDimitry Andric     InstAnalyzer PatInfo(*this);
3862edd7eaddSDimitry Andric     PatInfo.Analyze(PTM);
38633861d79fSDimitry Andric     Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
38643861d79fSDimitry Andric   }
38653861d79fSDimitry Andric 
38663861d79fSDimitry Andric   if (Errors)
38673861d79fSDimitry Andric     PrintFatalError("pattern conflicts");
38683861d79fSDimitry Andric 
38694ba319b5SDimitry Andric   // If requested by the target, guess any undefined properties.
38703861d79fSDimitry Andric   if (Target.guessInstructionProperties()) {
38714ba319b5SDimitry Andric     for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
38724ba319b5SDimitry Andric       CodeGenInstruction *InstInfo =
38734ba319b5SDimitry Andric         const_cast<CodeGenInstruction *>(Instructions[i]);
38747d523365SDimitry Andric       if (InstInfo->InferredFrom)
38753861d79fSDimitry Andric         continue;
38763861d79fSDimitry Andric       // The mayLoad and mayStore flags default to false.
38773861d79fSDimitry Andric       // Conservatively assume hasSideEffects if it wasn't explicit.
38787d523365SDimitry Andric       if (InstInfo->hasSideEffects_Unset)
38797d523365SDimitry Andric         InstInfo->hasSideEffects = true;
38803861d79fSDimitry Andric     }
38813861d79fSDimitry Andric     return;
38823861d79fSDimitry Andric   }
38833861d79fSDimitry Andric 
38843861d79fSDimitry Andric   // Complain about any flags that are still undefined.
38854ba319b5SDimitry Andric   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
38864ba319b5SDimitry Andric     CodeGenInstruction *InstInfo =
38874ba319b5SDimitry Andric       const_cast<CodeGenInstruction *>(Instructions[i]);
38887d523365SDimitry Andric     if (InstInfo->InferredFrom)
38893861d79fSDimitry Andric       continue;
38907d523365SDimitry Andric     if (InstInfo->hasSideEffects_Unset)
38917d523365SDimitry Andric       PrintError(InstInfo->TheDef->getLoc(),
38923861d79fSDimitry Andric                  "Can't infer hasSideEffects from patterns");
38937d523365SDimitry Andric     if (InstInfo->mayStore_Unset)
38947d523365SDimitry Andric       PrintError(InstInfo->TheDef->getLoc(),
38953861d79fSDimitry Andric                  "Can't infer mayStore from patterns");
38967d523365SDimitry Andric     if (InstInfo->mayLoad_Unset)
38977d523365SDimitry Andric       PrintError(InstInfo->TheDef->getLoc(),
38983861d79fSDimitry Andric                  "Can't infer mayLoad from patterns");
38993861d79fSDimitry Andric   }
39003861d79fSDimitry Andric }
39013861d79fSDimitry Andric 
39023861d79fSDimitry Andric 
39033861d79fSDimitry Andric /// Verify instruction flags against pattern node properties.
VerifyInstructionFlags()39043861d79fSDimitry Andric void CodeGenDAGPatterns::VerifyInstructionFlags() {
39053861d79fSDimitry Andric   unsigned Errors = 0;
39063861d79fSDimitry Andric   for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
39073861d79fSDimitry Andric     const PatternToMatch &PTM = *I;
39083861d79fSDimitry Andric     SmallVector<Record*, 8> Instrs;
39093861d79fSDimitry Andric     getInstructionsInTree(PTM.getDstPattern(), Instrs);
39103861d79fSDimitry Andric     if (Instrs.empty())
39113861d79fSDimitry Andric       continue;
39123861d79fSDimitry Andric 
39133861d79fSDimitry Andric     // Count the number of instructions with each flag set.
39143861d79fSDimitry Andric     unsigned NumSideEffects = 0;
39153861d79fSDimitry Andric     unsigned NumStores = 0;
39163861d79fSDimitry Andric     unsigned NumLoads = 0;
39177d523365SDimitry Andric     for (const Record *Instr : Instrs) {
39187d523365SDimitry Andric       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
39193861d79fSDimitry Andric       NumSideEffects += InstInfo.hasSideEffects;
39203861d79fSDimitry Andric       NumStores += InstInfo.mayStore;
39213861d79fSDimitry Andric       NumLoads += InstInfo.mayLoad;
39223861d79fSDimitry Andric     }
39233861d79fSDimitry Andric 
39243861d79fSDimitry Andric     // Analyze the source pattern.
39253861d79fSDimitry Andric     InstAnalyzer PatInfo(*this);
3926edd7eaddSDimitry Andric     PatInfo.Analyze(PTM);
39273861d79fSDimitry Andric 
39283861d79fSDimitry Andric     // Collect error messages.
39293861d79fSDimitry Andric     SmallVector<std::string, 4> Msgs;
39303861d79fSDimitry Andric 
39313861d79fSDimitry Andric     // Check for missing flags in the output.
39323861d79fSDimitry Andric     // Permit extra flags for now at least.
39333861d79fSDimitry Andric     if (PatInfo.hasSideEffects && !NumSideEffects)
39343861d79fSDimitry Andric       Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
39353861d79fSDimitry Andric 
39363861d79fSDimitry Andric     // Don't verify store flags on instructions with side effects. At least for
39373861d79fSDimitry Andric     // intrinsics, side effects implies mayStore.
39383861d79fSDimitry Andric     if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
39393861d79fSDimitry Andric       Msgs.push_back("pattern may store, but mayStore isn't set");
39403861d79fSDimitry Andric 
39413861d79fSDimitry Andric     // Similarly, mayStore implies mayLoad on intrinsics.
39423861d79fSDimitry Andric     if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
39433861d79fSDimitry Andric       Msgs.push_back("pattern may load, but mayLoad isn't set");
39443861d79fSDimitry Andric 
39453861d79fSDimitry Andric     // Print error messages.
39463861d79fSDimitry Andric     if (Msgs.empty())
39473861d79fSDimitry Andric       continue;
39483861d79fSDimitry Andric     ++Errors;
39493861d79fSDimitry Andric 
39507d523365SDimitry Andric     for (const std::string &Msg : Msgs)
39517d523365SDimitry Andric       PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
39523861d79fSDimitry Andric                  (Instrs.size() == 1 ?
39533861d79fSDimitry Andric                   "instruction" : "output instructions"));
39543861d79fSDimitry Andric     // Provide the location of the relevant instruction definitions.
39557d523365SDimitry Andric     for (const Record *Instr : Instrs) {
39567d523365SDimitry Andric       if (Instr != PTM.getSrcRecord())
39577d523365SDimitry Andric         PrintError(Instr->getLoc(), "defined here");
39587d523365SDimitry Andric       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
39593861d79fSDimitry Andric       if (InstInfo.InferredFrom &&
39603861d79fSDimitry Andric           InstInfo.InferredFrom != InstInfo.TheDef &&
39613861d79fSDimitry Andric           InstInfo.InferredFrom != PTM.getSrcRecord())
39627d523365SDimitry Andric         PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
39633861d79fSDimitry Andric     }
39643861d79fSDimitry Andric   }
39653861d79fSDimitry Andric   if (Errors)
39663861d79fSDimitry Andric     PrintFatalError("Errors in DAG patterns");
3967f22ef01cSRoman Divacky }
3968f22ef01cSRoman Divacky 
3969f22ef01cSRoman Divacky /// Given a pattern result with an unresolved type, see if we can find one
3970f22ef01cSRoman Divacky /// instruction with an unresolved result type.  Force this result type to an
3971f22ef01cSRoman Divacky /// arbitrary element if it's possible types to converge results.
ForceArbitraryInstResultType(TreePatternNode * N,TreePattern & TP)3972f22ef01cSRoman Divacky static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3973f22ef01cSRoman Divacky   if (N->isLeaf())
3974f22ef01cSRoman Divacky     return false;
3975f22ef01cSRoman Divacky 
3976f22ef01cSRoman Divacky   // Analyze children.
3977f22ef01cSRoman Divacky   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3978f22ef01cSRoman Divacky     if (ForceArbitraryInstResultType(N->getChild(i), TP))
3979f22ef01cSRoman Divacky       return true;
3980f22ef01cSRoman Divacky 
3981f22ef01cSRoman Divacky   if (!N->getOperator()->isSubClassOf("Instruction"))
3982f22ef01cSRoman Divacky     return false;
3983f22ef01cSRoman Divacky 
3984f22ef01cSRoman Divacky   // If this type is already concrete or completely unknown we can't do
3985f22ef01cSRoman Divacky   // anything.
39862cab237bSDimitry Andric   TypeInfer &TI = TP.getInfer();
3987f22ef01cSRoman Divacky   for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
39882cab237bSDimitry Andric     if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
3989f22ef01cSRoman Divacky       continue;
3990f22ef01cSRoman Divacky 
39912cab237bSDimitry Andric     // Otherwise, force its type to an arbitrary choice.
39922cab237bSDimitry Andric     if (TI.forceArbitrary(N->getExtType(i)))
3993f22ef01cSRoman Divacky       return true;
3994f22ef01cSRoman Divacky   }
3995f22ef01cSRoman Divacky 
3996f22ef01cSRoman Divacky   return false;
3997f22ef01cSRoman Divacky }
3998f22ef01cSRoman Divacky 
39994ba319b5SDimitry Andric // Promote xform function to be an explicit node wherever set.
PromoteXForms(TreePatternNodePtr N)40004ba319b5SDimitry Andric static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
40014ba319b5SDimitry Andric   if (Record *Xform = N->getTransformFn()) {
40024ba319b5SDimitry Andric       N->setTransformFn(nullptr);
40034ba319b5SDimitry Andric       std::vector<TreePatternNodePtr> Children;
40044ba319b5SDimitry Andric       Children.push_back(PromoteXForms(N));
40054ba319b5SDimitry Andric       return std::make_shared<TreePatternNode>(Xform, std::move(Children),
40064ba319b5SDimitry Andric                                                N->getNumTypes());
40074ba319b5SDimitry Andric   }
4008f22ef01cSRoman Divacky 
40094ba319b5SDimitry Andric   if (!N->isLeaf())
40104ba319b5SDimitry Andric     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
40114ba319b5SDimitry Andric       TreePatternNodePtr Child = N->getChildShared(i);
40124ba319b5SDimitry Andric       N->setChild(i, PromoteXForms(Child));
40134ba319b5SDimitry Andric     }
40144ba319b5SDimitry Andric   return N;
40154ba319b5SDimitry Andric }
40167ae0e2c9SDimitry Andric 
ParseOnePattern(Record * TheDef,TreePattern & Pattern,TreePattern & Result,const std::vector<Record * > & InstImpResults)40174ba319b5SDimitry Andric void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
40184ba319b5SDimitry Andric        TreePattern &Pattern, TreePattern &Result,
40194ba319b5SDimitry Andric        const std::vector<Record *> &InstImpResults) {
40207ae0e2c9SDimitry Andric 
40214ba319b5SDimitry Andric   // Inline pattern fragments and expand multiple alternatives.
40224ba319b5SDimitry Andric   Pattern.InlinePatternFragments();
402339d628a0SDimitry Andric   Result.InlinePatternFragments();
4024f22ef01cSRoman Divacky 
402539d628a0SDimitry Andric   if (Result.getNumTrees() != 1)
40264ba319b5SDimitry Andric     Result.error("Cannot use multi-alternative fragments in result pattern!");
4027f22ef01cSRoman Divacky 
40284ba319b5SDimitry Andric   // Infer types.
4029f22ef01cSRoman Divacky   bool IterateInference;
4030f22ef01cSRoman Divacky   bool InferredAllPatternTypes, InferredAllResultTypes;
4031f22ef01cSRoman Divacky   do {
4032f22ef01cSRoman Divacky     // Infer as many types as possible.  If we cannot infer all of them, we
4033f22ef01cSRoman Divacky     // can never do anything with this pattern: report it to the user.
4034f22ef01cSRoman Divacky     InferredAllPatternTypes =
40354ba319b5SDimitry Andric         Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
4036f22ef01cSRoman Divacky 
4037f22ef01cSRoman Divacky     // Infer as many types as possible.  If we cannot infer all of them, we
4038f22ef01cSRoman Divacky     // can never do anything with this pattern: report it to the user.
4039f22ef01cSRoman Divacky     InferredAllResultTypes =
40404ba319b5SDimitry Andric         Result.InferAllTypes(&Pattern.getNamedNodesMap());
4041f22ef01cSRoman Divacky 
4042f22ef01cSRoman Divacky     IterateInference = false;
4043f22ef01cSRoman Divacky 
4044f22ef01cSRoman Divacky     // Apply the type of the result to the source pattern.  This helps us
4045f22ef01cSRoman Divacky     // resolve cases where the input type is known to be a pointer type (which
4046f22ef01cSRoman Divacky     // is considered resolved), but the result knows it needs to be 32- or
4047f22ef01cSRoman Divacky     // 64-bits.  Infer the other way for good measure.
40484ba319b5SDimitry Andric     for (auto T : Pattern.getTrees())
40494ba319b5SDimitry Andric       for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
40504ba319b5SDimitry Andric                                         T->getNumTypes());
4051f22ef01cSRoman Divacky          i != e; ++i) {
40524ba319b5SDimitry Andric         IterateInference |= T->UpdateNodeType(
40534ba319b5SDimitry Andric             i, Result.getOnlyTree()->getExtType(i), Result);
40544ba319b5SDimitry Andric         IterateInference |= Result.getOnlyTree()->UpdateNodeType(
40554ba319b5SDimitry Andric             i, T->getExtType(i), Result);
4056f22ef01cSRoman Divacky       }
4057f22ef01cSRoman Divacky 
4058f22ef01cSRoman Divacky     // If our iteration has converged and the input pattern's types are fully
4059f22ef01cSRoman Divacky     // resolved but the result pattern is not fully resolved, we may have a
4060f22ef01cSRoman Divacky     // situation where we have two instructions in the result pattern and
4061f22ef01cSRoman Divacky     // the instructions require a common register class, but don't care about
4062f22ef01cSRoman Divacky     // what actual MVT is used.  This is actually a bug in our modelling:
4063f22ef01cSRoman Divacky     // output patterns should have register classes, not MVTs.
4064f22ef01cSRoman Divacky     //
4065f22ef01cSRoman Divacky     // In any case, to handle this, we just go through and disambiguate some
4066f22ef01cSRoman Divacky     // arbitrary types to the result pattern's nodes.
4067f22ef01cSRoman Divacky     if (!IterateInference && InferredAllPatternTypes &&
4068f22ef01cSRoman Divacky         !InferredAllResultTypes)
406939d628a0SDimitry Andric       IterateInference =
40704ba319b5SDimitry Andric           ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4071f22ef01cSRoman Divacky   } while (IterateInference);
4072f22ef01cSRoman Divacky 
4073f22ef01cSRoman Divacky   // Verify that we inferred enough types that we can do something with the
4074f22ef01cSRoman Divacky   // pattern and result.  If these fire the user has to add type casts.
4075f22ef01cSRoman Divacky   if (!InferredAllPatternTypes)
40764ba319b5SDimitry Andric     Pattern.error("Could not infer all types in pattern!");
4077f22ef01cSRoman Divacky   if (!InferredAllResultTypes) {
40784ba319b5SDimitry Andric     Pattern.dump();
407939d628a0SDimitry Andric     Result.error("Could not infer all types in pattern result!");
4080f22ef01cSRoman Divacky   }
4081f22ef01cSRoman Divacky 
40824ba319b5SDimitry Andric   // Promote xform function to be an explicit node wherever set.
40834ba319b5SDimitry Andric   TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
4084f22ef01cSRoman Divacky 
40854ba319b5SDimitry Andric   TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4086f22ef01cSRoman Divacky   Temp.InferAllTypes();
4087f22ef01cSRoman Divacky 
40884ba319b5SDimitry Andric   ListInit *Preds = TheDef->getValueAsListInit("Predicates");
40894ba319b5SDimitry Andric   int Complexity = TheDef->getValueAsInt("AddedComplexity");
40904ba319b5SDimitry Andric 
40914ba319b5SDimitry Andric   if (PatternRewriter)
40924ba319b5SDimitry Andric     PatternRewriter(&Pattern);
40934ba319b5SDimitry Andric 
40942cab237bSDimitry Andric   // A pattern may end up with an "impossible" type, i.e. a situation
40952cab237bSDimitry Andric   // where all types have been eliminated for some node in this pattern.
40962cab237bSDimitry Andric   // This could occur for intrinsics that only make sense for a specific
40972cab237bSDimitry Andric   // value type, and use a specific register class. If, for some mode,
40982cab237bSDimitry Andric   // that register class does not accept that type, the type inference
40992cab237bSDimitry Andric   // will lead to a contradiction, which is not an error however, but
41002cab237bSDimitry Andric   // a sign that this pattern will simply never match.
41014ba319b5SDimitry Andric   if (Temp.getOnlyTree()->hasPossibleType())
41024ba319b5SDimitry Andric     for (auto T : Pattern.getTrees())
41034ba319b5SDimitry Andric       if (T->hasPossibleType())
41044ba319b5SDimitry Andric         AddPatternToMatch(&Pattern,
41054ba319b5SDimitry Andric                           PatternToMatch(TheDef, makePredList(Preds),
41064ba319b5SDimitry Andric                                          T, Temp.getOnlyTree(),
41074ba319b5SDimitry Andric                                          InstImpResults, Complexity,
41084ba319b5SDimitry Andric                                          TheDef->getID()));
4109f22ef01cSRoman Divacky }
41104ba319b5SDimitry Andric 
ParsePatterns()41114ba319b5SDimitry Andric void CodeGenDAGPatterns::ParsePatterns() {
41124ba319b5SDimitry Andric   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
41134ba319b5SDimitry Andric 
41144ba319b5SDimitry Andric   for (Record *CurPattern : Patterns) {
41154ba319b5SDimitry Andric     DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
41164ba319b5SDimitry Andric 
41174ba319b5SDimitry Andric     // If the pattern references the null_frag, there's nothing to do.
41184ba319b5SDimitry Andric     if (hasNullFragReference(Tree))
41194ba319b5SDimitry Andric       continue;
41204ba319b5SDimitry Andric 
41214ba319b5SDimitry Andric     TreePattern Pattern(CurPattern, Tree, true, *this);
41224ba319b5SDimitry Andric 
41234ba319b5SDimitry Andric     ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
41244ba319b5SDimitry Andric     if (LI->empty()) continue;  // no pattern.
41254ba319b5SDimitry Andric 
41264ba319b5SDimitry Andric     // Parse the instruction.
41274ba319b5SDimitry Andric     TreePattern Result(CurPattern, LI, false, *this);
41284ba319b5SDimitry Andric 
41294ba319b5SDimitry Andric     if (Result.getNumTrees() != 1)
41304ba319b5SDimitry Andric       Result.error("Cannot handle instructions producing instructions "
41314ba319b5SDimitry Andric                    "with temporaries yet!");
41324ba319b5SDimitry Andric 
41334ba319b5SDimitry Andric     // Validate that the input pattern is correct.
41344ba319b5SDimitry Andric     std::map<std::string, TreePatternNodePtr> InstInputs;
4135*b5893f02SDimitry Andric     MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
4136*b5893f02SDimitry Andric         InstResults;
41374ba319b5SDimitry Andric     std::vector<Record*> InstImpResults;
41384ba319b5SDimitry Andric     for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
41394ba319b5SDimitry Andric       FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
41404ba319b5SDimitry Andric                                   InstResults, InstImpResults);
41414ba319b5SDimitry Andric 
41424ba319b5SDimitry Andric     ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
4143f22ef01cSRoman Divacky   }
41442cab237bSDimitry Andric }
41452cab237bSDimitry Andric 
collectModes(std::set<unsigned> & Modes,const TreePatternNode * N)41462cab237bSDimitry Andric static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
41472cab237bSDimitry Andric   for (const TypeSetByHwMode &VTS : N->getExtTypes())
41482cab237bSDimitry Andric     for (const auto &I : VTS)
41492cab237bSDimitry Andric       Modes.insert(I.first);
41502cab237bSDimitry Andric 
41512cab237bSDimitry Andric   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
41522cab237bSDimitry Andric     collectModes(Modes, N->getChild(i));
41532cab237bSDimitry Andric }
41542cab237bSDimitry Andric 
ExpandHwModeBasedTypes()41552cab237bSDimitry Andric void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
41562cab237bSDimitry Andric   const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
41572cab237bSDimitry Andric   std::map<unsigned,std::vector<Predicate>> ModeChecks;
41582cab237bSDimitry Andric   std::vector<PatternToMatch> Copy = PatternsToMatch;
41592cab237bSDimitry Andric   PatternsToMatch.clear();
41602cab237bSDimitry Andric 
41612cab237bSDimitry Andric   auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
41624ba319b5SDimitry Andric     TreePatternNodePtr NewSrc = P.SrcPattern->clone();
41634ba319b5SDimitry Andric     TreePatternNodePtr NewDst = P.DstPattern->clone();
41642cab237bSDimitry Andric     if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
41652cab237bSDimitry Andric       return;
41662cab237bSDimitry Andric     }
41672cab237bSDimitry Andric 
41682cab237bSDimitry Andric     std::vector<Predicate> Preds = P.Predicates;
41692cab237bSDimitry Andric     const std::vector<Predicate> &MC = ModeChecks[Mode];
41702cab237bSDimitry Andric     Preds.insert(Preds.end(), MC.begin(), MC.end());
41714ba319b5SDimitry Andric     PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
41724ba319b5SDimitry Andric                                  std::move(NewDst), P.getDstRegs(),
41734ba319b5SDimitry Andric                                  P.getAddedComplexity(), Record::getNewUID(),
41744ba319b5SDimitry Andric                                  Mode);
41752cab237bSDimitry Andric   };
41762cab237bSDimitry Andric 
41772cab237bSDimitry Andric   for (PatternToMatch &P : Copy) {
41784ba319b5SDimitry Andric     TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
41792cab237bSDimitry Andric     if (P.SrcPattern->hasProperTypeByHwMode())
41802cab237bSDimitry Andric       SrcP = P.SrcPattern;
41812cab237bSDimitry Andric     if (P.DstPattern->hasProperTypeByHwMode())
41822cab237bSDimitry Andric       DstP = P.DstPattern;
41832cab237bSDimitry Andric     if (!SrcP && !DstP) {
41842cab237bSDimitry Andric       PatternsToMatch.push_back(P);
41852cab237bSDimitry Andric       continue;
41862cab237bSDimitry Andric     }
41872cab237bSDimitry Andric 
41882cab237bSDimitry Andric     std::set<unsigned> Modes;
41892cab237bSDimitry Andric     if (SrcP)
41904ba319b5SDimitry Andric       collectModes(Modes, SrcP.get());
41912cab237bSDimitry Andric     if (DstP)
41924ba319b5SDimitry Andric       collectModes(Modes, DstP.get());
41932cab237bSDimitry Andric 
41942cab237bSDimitry Andric     // The predicate for the default mode needs to be constructed for each
41952cab237bSDimitry Andric     // pattern separately.
41962cab237bSDimitry Andric     // Since not all modes must be present in each pattern, if a mode m is
41972cab237bSDimitry Andric     // absent, then there is no point in constructing a check for m. If such
41982cab237bSDimitry Andric     // a check was created, it would be equivalent to checking the default
41992cab237bSDimitry Andric     // mode, except not all modes' predicates would be a part of the checking
42002cab237bSDimitry Andric     // code. The subsequently generated check for the default mode would then
42012cab237bSDimitry Andric     // have the exact same patterns, but a different predicate code. To avoid
42022cab237bSDimitry Andric     // duplicated patterns with different predicate checks, construct the
42032cab237bSDimitry Andric     // default check as a negation of all predicates that are actually present
42042cab237bSDimitry Andric     // in the source/destination patterns.
42052cab237bSDimitry Andric     std::vector<Predicate> DefaultPred;
42062cab237bSDimitry Andric 
42072cab237bSDimitry Andric     for (unsigned M : Modes) {
42082cab237bSDimitry Andric       if (M == DefaultMode)
42092cab237bSDimitry Andric         continue;
42102cab237bSDimitry Andric       if (ModeChecks.find(M) != ModeChecks.end())
42112cab237bSDimitry Andric         continue;
42122cab237bSDimitry Andric 
42132cab237bSDimitry Andric       // Fill the map entry for this mode.
42142cab237bSDimitry Andric       const HwMode &HM = CGH.getMode(M);
42152cab237bSDimitry Andric       ModeChecks[M].emplace_back(Predicate(HM.Features, true));
42162cab237bSDimitry Andric 
42172cab237bSDimitry Andric       // Add negations of the HM's predicates to the default predicate.
42182cab237bSDimitry Andric       DefaultPred.emplace_back(Predicate(HM.Features, false));
42192cab237bSDimitry Andric     }
42202cab237bSDimitry Andric 
42212cab237bSDimitry Andric     for (unsigned M : Modes) {
42222cab237bSDimitry Andric       if (M == DefaultMode)
42232cab237bSDimitry Andric         continue;
42242cab237bSDimitry Andric       AppendPattern(P, M);
42252cab237bSDimitry Andric     }
42262cab237bSDimitry Andric 
42272cab237bSDimitry Andric     bool HasDefault = Modes.count(DefaultMode);
42282cab237bSDimitry Andric     if (HasDefault)
42292cab237bSDimitry Andric       AppendPattern(P, DefaultMode);
42302cab237bSDimitry Andric   }
42312cab237bSDimitry Andric }
42322cab237bSDimitry Andric 
42332cab237bSDimitry Andric /// Dependent variable map for CodeGenDAGPattern variant generation
42342cab237bSDimitry Andric typedef StringMap<int> DepVarMap;
42352cab237bSDimitry Andric 
FindDepVarsOf(TreePatternNode * N,DepVarMap & DepMap)42362cab237bSDimitry Andric static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
42372cab237bSDimitry Andric   if (N->isLeaf()) {
42382cab237bSDimitry Andric     if (N->hasName() && isa<DefInit>(N->getLeafValue()))
42392cab237bSDimitry Andric       DepMap[N->getName()]++;
42402cab237bSDimitry Andric   } else {
42412cab237bSDimitry Andric     for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
42422cab237bSDimitry Andric       FindDepVarsOf(N->getChild(i), DepMap);
42432cab237bSDimitry Andric   }
42442cab237bSDimitry Andric }
42452cab237bSDimitry Andric 
42462cab237bSDimitry Andric /// Find dependent variables within child patterns
FindDepVars(TreePatternNode * N,MultipleUseVarSet & DepVars)42472cab237bSDimitry Andric static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
42482cab237bSDimitry Andric   DepVarMap depcounts;
42492cab237bSDimitry Andric   FindDepVarsOf(N, depcounts);
42502cab237bSDimitry Andric   for (const auto &Pair : depcounts) {
42512cab237bSDimitry Andric     if (Pair.getValue() > 1)
42522cab237bSDimitry Andric       DepVars.insert(Pair.getKey());
42532cab237bSDimitry Andric   }
42542cab237bSDimitry Andric }
42552cab237bSDimitry Andric 
42562cab237bSDimitry Andric #ifndef NDEBUG
42572cab237bSDimitry Andric /// Dump the dependent variable set:
DumpDepVars(MultipleUseVarSet & DepVars)42582cab237bSDimitry Andric static void DumpDepVars(MultipleUseVarSet &DepVars) {
42592cab237bSDimitry Andric   if (DepVars.empty()) {
42604ba319b5SDimitry Andric     LLVM_DEBUG(errs() << "<empty set>");
42612cab237bSDimitry Andric   } else {
42624ba319b5SDimitry Andric     LLVM_DEBUG(errs() << "[ ");
42632cab237bSDimitry Andric     for (const auto &DepVar : DepVars) {
42644ba319b5SDimitry Andric       LLVM_DEBUG(errs() << DepVar.getKey() << " ");
42652cab237bSDimitry Andric     }
42664ba319b5SDimitry Andric     LLVM_DEBUG(errs() << "]");
42672cab237bSDimitry Andric   }
42682cab237bSDimitry Andric }
42692cab237bSDimitry Andric #endif
42702cab237bSDimitry Andric 
4271f22ef01cSRoman Divacky 
4272f22ef01cSRoman Divacky /// CombineChildVariants - Given a bunch of permutations of each child of the
4273f22ef01cSRoman Divacky /// 'operator' node, put them together in all possible ways.
CombineChildVariants(TreePatternNodePtr Orig,const std::vector<std::vector<TreePatternNodePtr>> & ChildVariants,std::vector<TreePatternNodePtr> & OutVariants,CodeGenDAGPatterns & CDP,const MultipleUseVarSet & DepVars)42744ba319b5SDimitry Andric static void CombineChildVariants(
42754ba319b5SDimitry Andric     TreePatternNodePtr Orig,
42764ba319b5SDimitry Andric     const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
42774ba319b5SDimitry Andric     std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4278f22ef01cSRoman Divacky     const MultipleUseVarSet &DepVars) {
4279f22ef01cSRoman Divacky   // Make sure that each operand has at least one variant to choose from.
42807d523365SDimitry Andric   for (const auto &Variants : ChildVariants)
42817d523365SDimitry Andric     if (Variants.empty())
4282f22ef01cSRoman Divacky       return;
4283f22ef01cSRoman Divacky 
4284f22ef01cSRoman Divacky   // The end result is an all-pairs construction of the resultant pattern.
4285f22ef01cSRoman Divacky   std::vector<unsigned> Idxs;
4286f22ef01cSRoman Divacky   Idxs.resize(ChildVariants.size());
4287f22ef01cSRoman Divacky   bool NotDone;
4288f22ef01cSRoman Divacky   do {
4289f22ef01cSRoman Divacky #ifndef NDEBUG
42904ba319b5SDimitry Andric     LLVM_DEBUG(if (!Idxs.empty()) {
4291f22ef01cSRoman Divacky       errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
42927d523365SDimitry Andric       for (unsigned Idx : Idxs) {
42937d523365SDimitry Andric         errs() << Idx << " ";
4294f22ef01cSRoman Divacky       }
4295f22ef01cSRoman Divacky       errs() << "]\n";
4296f22ef01cSRoman Divacky     });
4297f22ef01cSRoman Divacky #endif
4298f22ef01cSRoman Divacky     // Create the variant and add it to the output list.
42994ba319b5SDimitry Andric     std::vector<TreePatternNodePtr> NewChildren;
4300f22ef01cSRoman Divacky     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4301f22ef01cSRoman Divacky       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
43024ba319b5SDimitry Andric     TreePatternNodePtr R = std::make_shared<TreePatternNode>(
43034ba319b5SDimitry Andric         Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
4304f22ef01cSRoman Divacky 
4305f22ef01cSRoman Divacky     // Copy over properties.
4306f22ef01cSRoman Divacky     R->setName(Orig->getName());
4307*b5893f02SDimitry Andric     R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4308*b5893f02SDimitry Andric     R->setPredicateCalls(Orig->getPredicateCalls());
4309f22ef01cSRoman Divacky     R->setTransformFn(Orig->getTransformFn());
4310f22ef01cSRoman Divacky     for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4311f22ef01cSRoman Divacky       R->setType(i, Orig->getExtType(i));
4312f22ef01cSRoman Divacky 
4313f22ef01cSRoman Divacky     // If this pattern cannot match, do not include it as a variant.
4314f22ef01cSRoman Divacky     std::string ErrString;
4315f22ef01cSRoman Divacky     // Scan to see if this pattern has already been emitted.  We can get
4316f22ef01cSRoman Divacky     // duplication due to things like commuting:
4317f22ef01cSRoman Divacky     //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4318f22ef01cSRoman Divacky     // which are the same pattern.  Ignore the dups.
43197d523365SDimitry Andric     if (R->canPatternMatch(ErrString, CDP) &&
43204ba319b5SDimitry Andric         none_of(OutVariants, [&](TreePatternNodePtr Variant) {
43214ba319b5SDimitry Andric           return R->isIsomorphicTo(Variant.get(), DepVars);
43227d523365SDimitry Andric         }))
43234ba319b5SDimitry Andric       OutVariants.push_back(R);
4324f22ef01cSRoman Divacky 
4325f22ef01cSRoman Divacky     // Increment indices to the next permutation by incrementing the
43267d523365SDimitry Andric     // indices from last index backward, e.g., generate the sequence
4327f22ef01cSRoman Divacky     // [0, 0], [0, 1], [1, 0], [1, 1].
4328f22ef01cSRoman Divacky     int IdxsIdx;
4329f22ef01cSRoman Divacky     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4330f22ef01cSRoman Divacky       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4331f22ef01cSRoman Divacky         Idxs[IdxsIdx] = 0;
4332f22ef01cSRoman Divacky       else
4333f22ef01cSRoman Divacky         break;
4334f22ef01cSRoman Divacky     }
4335f22ef01cSRoman Divacky     NotDone = (IdxsIdx >= 0);
4336f22ef01cSRoman Divacky   } while (NotDone);
4337f22ef01cSRoman Divacky }
4338f22ef01cSRoman Divacky 
4339f22ef01cSRoman Divacky /// CombineChildVariants - A helper function for binary operators.
4340f22ef01cSRoman Divacky ///
CombineChildVariants(TreePatternNodePtr Orig,const std::vector<TreePatternNodePtr> & LHS,const std::vector<TreePatternNodePtr> & RHS,std::vector<TreePatternNodePtr> & OutVariants,CodeGenDAGPatterns & CDP,const MultipleUseVarSet & DepVars)43414ba319b5SDimitry Andric static void CombineChildVariants(TreePatternNodePtr Orig,
43424ba319b5SDimitry Andric                                  const std::vector<TreePatternNodePtr> &LHS,
43434ba319b5SDimitry Andric                                  const std::vector<TreePatternNodePtr> &RHS,
43444ba319b5SDimitry Andric                                  std::vector<TreePatternNodePtr> &OutVariants,
4345f22ef01cSRoman Divacky                                  CodeGenDAGPatterns &CDP,
4346f22ef01cSRoman Divacky                                  const MultipleUseVarSet &DepVars) {
43474ba319b5SDimitry Andric   std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4348f22ef01cSRoman Divacky   ChildVariants.push_back(LHS);
4349f22ef01cSRoman Divacky   ChildVariants.push_back(RHS);
4350f22ef01cSRoman Divacky   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4351f22ef01cSRoman Divacky }
4352f22ef01cSRoman Divacky 
43534ba319b5SDimitry Andric static void
GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,std::vector<TreePatternNodePtr> & Children)43544ba319b5SDimitry Andric GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
43554ba319b5SDimitry Andric                                   std::vector<TreePatternNodePtr> &Children) {
4356f22ef01cSRoman Divacky   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4357f22ef01cSRoman Divacky   Record *Operator = N->getOperator();
4358f22ef01cSRoman Divacky 
4359f22ef01cSRoman Divacky   // Only permit raw nodes.
4360*b5893f02SDimitry Andric   if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
4361f22ef01cSRoman Divacky       N->getTransformFn()) {
4362f22ef01cSRoman Divacky     Children.push_back(N);
4363f22ef01cSRoman Divacky     return;
4364f22ef01cSRoman Divacky   }
4365f22ef01cSRoman Divacky 
4366f22ef01cSRoman Divacky   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
43674ba319b5SDimitry Andric     Children.push_back(N->getChildShared(0));
4368f22ef01cSRoman Divacky   else
43694ba319b5SDimitry Andric     GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
4370f22ef01cSRoman Divacky 
4371f22ef01cSRoman Divacky   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
43724ba319b5SDimitry Andric     Children.push_back(N->getChildShared(1));
4373f22ef01cSRoman Divacky   else
43744ba319b5SDimitry Andric     GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
4375f22ef01cSRoman Divacky }
4376f22ef01cSRoman Divacky 
4377f22ef01cSRoman Divacky /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4378f22ef01cSRoman Divacky /// the (potentially recursive) pattern by using algebraic laws.
4379f22ef01cSRoman Divacky ///
GenerateVariantsOf(TreePatternNodePtr N,std::vector<TreePatternNodePtr> & OutVariants,CodeGenDAGPatterns & CDP,const MultipleUseVarSet & DepVars)43804ba319b5SDimitry Andric static void GenerateVariantsOf(TreePatternNodePtr N,
43814ba319b5SDimitry Andric                                std::vector<TreePatternNodePtr> &OutVariants,
4382f22ef01cSRoman Divacky                                CodeGenDAGPatterns &CDP,
4383f22ef01cSRoman Divacky                                const MultipleUseVarSet &DepVars) {
438491bc56edSDimitry Andric   // We cannot permute leaves or ComplexPattern uses.
438591bc56edSDimitry Andric   if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
4386f22ef01cSRoman Divacky     OutVariants.push_back(N);
4387f22ef01cSRoman Divacky     return;
4388f22ef01cSRoman Divacky   }
4389f22ef01cSRoman Divacky 
4390f22ef01cSRoman Divacky   // Look up interesting info about the node.
4391f22ef01cSRoman Divacky   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4392f22ef01cSRoman Divacky 
4393f22ef01cSRoman Divacky   // If this node is associative, re-associate.
4394f22ef01cSRoman Divacky   if (NodeInfo.hasProperty(SDNPAssociative)) {
4395f22ef01cSRoman Divacky     // Re-associate by pulling together all of the linked operators
43964ba319b5SDimitry Andric     std::vector<TreePatternNodePtr> MaximalChildren;
4397f22ef01cSRoman Divacky     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4398f22ef01cSRoman Divacky 
4399f22ef01cSRoman Divacky     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
4400f22ef01cSRoman Divacky     // permutations.
4401f22ef01cSRoman Divacky     if (MaximalChildren.size() == 3) {
4402f22ef01cSRoman Divacky       // Find the variants of all of our maximal children.
44034ba319b5SDimitry Andric       std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
4404f22ef01cSRoman Divacky       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4405f22ef01cSRoman Divacky       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4406f22ef01cSRoman Divacky       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
4407f22ef01cSRoman Divacky 
4408f22ef01cSRoman Divacky       // There are only two ways we can permute the tree:
4409f22ef01cSRoman Divacky       //   (A op B) op C    and    A op (B op C)
4410f22ef01cSRoman Divacky       // Within these forms, we can also permute A/B/C.
4411f22ef01cSRoman Divacky 
4412f22ef01cSRoman Divacky       // Generate legal pair permutations of A/B/C.
44134ba319b5SDimitry Andric       std::vector<TreePatternNodePtr> ABVariants;
44144ba319b5SDimitry Andric       std::vector<TreePatternNodePtr> BAVariants;
44154ba319b5SDimitry Andric       std::vector<TreePatternNodePtr> ACVariants;
44164ba319b5SDimitry Andric       std::vector<TreePatternNodePtr> CAVariants;
44174ba319b5SDimitry Andric       std::vector<TreePatternNodePtr> BCVariants;
44184ba319b5SDimitry Andric       std::vector<TreePatternNodePtr> CBVariants;
4419f22ef01cSRoman Divacky       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4420f22ef01cSRoman Divacky       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4421f22ef01cSRoman Divacky       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4422f22ef01cSRoman Divacky       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4423f22ef01cSRoman Divacky       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4424f22ef01cSRoman Divacky       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
4425f22ef01cSRoman Divacky 
4426f22ef01cSRoman Divacky       // Combine those into the result: (x op x) op x
4427f22ef01cSRoman Divacky       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4428f22ef01cSRoman Divacky       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4429f22ef01cSRoman Divacky       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4430f22ef01cSRoman Divacky       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4431f22ef01cSRoman Divacky       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4432f22ef01cSRoman Divacky       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
4433f22ef01cSRoman Divacky 
4434f22ef01cSRoman Divacky       // Combine those into the result: x op (x op x)
4435f22ef01cSRoman Divacky       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4436f22ef01cSRoman Divacky       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4437f22ef01cSRoman Divacky       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4438f22ef01cSRoman Divacky       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4439f22ef01cSRoman Divacky       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4440f22ef01cSRoman Divacky       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
4441f22ef01cSRoman Divacky       return;
4442f22ef01cSRoman Divacky     }
4443f22ef01cSRoman Divacky   }
4444f22ef01cSRoman Divacky 
4445f22ef01cSRoman Divacky   // Compute permutations of all children.
44464ba319b5SDimitry Andric   std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4447f22ef01cSRoman Divacky   ChildVariants.resize(N->getNumChildren());
4448f22ef01cSRoman Divacky   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
44494ba319b5SDimitry Andric     GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
4450f22ef01cSRoman Divacky 
4451f22ef01cSRoman Divacky   // Build all permutations based on how the children were formed.
4452f22ef01cSRoman Divacky   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
4453f22ef01cSRoman Divacky 
4454f22ef01cSRoman Divacky   // If this node is commutative, consider the commuted order.
4455f22ef01cSRoman Divacky   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4456f22ef01cSRoman Divacky   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
44572cab237bSDimitry Andric     assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
4458f22ef01cSRoman Divacky            "Commutative but doesn't have 2 children!");
4459f22ef01cSRoman Divacky     // Don't count children which are actually register references.
4460f22ef01cSRoman Divacky     unsigned NC = 0;
4461f22ef01cSRoman Divacky     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4462f22ef01cSRoman Divacky       TreePatternNode *Child = N->getChild(i);
4463f22ef01cSRoman Divacky       if (Child->isLeaf())
44643861d79fSDimitry Andric         if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
4465f22ef01cSRoman Divacky           Record *RR = DI->getDef();
4466f22ef01cSRoman Divacky           if (RR->isSubClassOf("Register"))
4467f22ef01cSRoman Divacky             continue;
4468f22ef01cSRoman Divacky         }
4469f22ef01cSRoman Divacky       NC++;
4470f22ef01cSRoman Divacky     }
4471f22ef01cSRoman Divacky     // Consider the commuted order.
4472f22ef01cSRoman Divacky     if (isCommIntrinsic) {
4473f22ef01cSRoman Divacky       // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4474f22ef01cSRoman Divacky       // operands are the commutative operands, and there might be more operands
4475f22ef01cSRoman Divacky       // after those.
4476f22ef01cSRoman Divacky       assert(NC >= 3 &&
44777d523365SDimitry Andric              "Commutative intrinsic should have at least 3 children!");
44784ba319b5SDimitry Andric       std::vector<std::vector<TreePatternNodePtr>> Variants;
44794ba319b5SDimitry Andric       Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
44804ba319b5SDimitry Andric       Variants.push_back(std::move(ChildVariants[2]));
44814ba319b5SDimitry Andric       Variants.push_back(std::move(ChildVariants[1]));
4482f22ef01cSRoman Divacky       for (unsigned i = 3; i != NC; ++i)
44834ba319b5SDimitry Andric         Variants.push_back(std::move(ChildVariants[i]));
4484f22ef01cSRoman Divacky       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
44852cab237bSDimitry Andric     } else if (NC == N->getNumChildren()) {
44864ba319b5SDimitry Andric       std::vector<std::vector<TreePatternNodePtr>> Variants;
44874ba319b5SDimitry Andric       Variants.push_back(std::move(ChildVariants[1]));
44884ba319b5SDimitry Andric       Variants.push_back(std::move(ChildVariants[0]));
44892cab237bSDimitry Andric       for (unsigned i = 2; i != NC; ++i)
44904ba319b5SDimitry Andric         Variants.push_back(std::move(ChildVariants[i]));
44912cab237bSDimitry Andric       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
44922cab237bSDimitry Andric     }
4493f22ef01cSRoman Divacky   }
4494f22ef01cSRoman Divacky }
4495f22ef01cSRoman Divacky 
4496f22ef01cSRoman Divacky 
4497f22ef01cSRoman Divacky // GenerateVariants - Generate variants.  For example, commutative patterns can
4498f22ef01cSRoman Divacky // match multiple ways.  Add them to PatternsToMatch as well.
GenerateVariants()4499f22ef01cSRoman Divacky void CodeGenDAGPatterns::GenerateVariants() {
45004ba319b5SDimitry Andric   LLVM_DEBUG(errs() << "Generating instruction variants.\n");
4501f22ef01cSRoman Divacky 
4502f22ef01cSRoman Divacky   // Loop over all of the patterns we've collected, checking to see if we can
4503f22ef01cSRoman Divacky   // generate variants of the instruction, through the exploitation of
4504f22ef01cSRoman Divacky   // identities.  This permits the target to provide aggressive matching without
4505f22ef01cSRoman Divacky   // the .td file having to contain tons of variants of instructions.
4506f22ef01cSRoman Divacky   //
4507f22ef01cSRoman Divacky   // Note that this loop adds new patterns to the PatternsToMatch list, but we
4508f22ef01cSRoman Divacky   // intentionally do not reconsider these.  Any variants of added patterns have
4509f22ef01cSRoman Divacky   // already been added.
4510f22ef01cSRoman Divacky   //
4511*b5893f02SDimitry Andric   const unsigned NumOriginalPatterns = PatternsToMatch.size();
4512*b5893f02SDimitry Andric   BitVector MatchedPatterns(NumOriginalPatterns);
4513*b5893f02SDimitry Andric   std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
4514*b5893f02SDimitry Andric                                            BitVector(NumOriginalPatterns));
4515*b5893f02SDimitry Andric 
4516*b5893f02SDimitry Andric   typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
4517*b5893f02SDimitry Andric       DepsAndVariants;
4518*b5893f02SDimitry Andric   std::map<unsigned, DepsAndVariants> PatternsWithVariants;
4519*b5893f02SDimitry Andric 
4520*b5893f02SDimitry Andric   // Collect patterns with more than one variant.
4521*b5893f02SDimitry Andric   for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
4522f22ef01cSRoman Divacky     MultipleUseVarSet DepVars;
45234ba319b5SDimitry Andric     std::vector<TreePatternNodePtr> Variants;
4524f22ef01cSRoman Divacky     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
45254ba319b5SDimitry Andric     LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
45264ba319b5SDimitry Andric     LLVM_DEBUG(DumpDepVars(DepVars));
45274ba319b5SDimitry Andric     LLVM_DEBUG(errs() << "\n");
45284ba319b5SDimitry Andric     GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
45294ba319b5SDimitry Andric                        *this, DepVars);
4530f22ef01cSRoman Divacky 
4531f22ef01cSRoman Divacky     assert(!Variants.empty() && "Must create at least original variant!");
453224d58133SDimitry Andric     if (Variants.size() == 1) // No additional variants for this pattern.
4533f22ef01cSRoman Divacky       continue;
4534f22ef01cSRoman Divacky 
45354ba319b5SDimitry Andric     LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
45364ba319b5SDimitry Andric                PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
4537f22ef01cSRoman Divacky 
4538*b5893f02SDimitry Andric     PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
4539*b5893f02SDimitry Andric 
4540*b5893f02SDimitry Andric     // Cache matching predicates.
4541*b5893f02SDimitry Andric     if (MatchedPatterns[i])
4542*b5893f02SDimitry Andric       continue;
4543*b5893f02SDimitry Andric 
4544*b5893f02SDimitry Andric     const std::vector<Predicate> &Predicates =
4545*b5893f02SDimitry Andric         PatternsToMatch[i].getPredicates();
4546*b5893f02SDimitry Andric 
4547*b5893f02SDimitry Andric     BitVector &Matches = MatchedPredicates[i];
4548*b5893f02SDimitry Andric     MatchedPatterns.set(i);
4549*b5893f02SDimitry Andric     Matches.set(i);
4550*b5893f02SDimitry Andric 
4551*b5893f02SDimitry Andric     // Don't test patterns that have already been cached - it won't match.
4552*b5893f02SDimitry Andric     for (unsigned p = 0; p != NumOriginalPatterns; ++p)
4553*b5893f02SDimitry Andric       if (!MatchedPatterns[p])
4554*b5893f02SDimitry Andric         Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
4555*b5893f02SDimitry Andric 
4556*b5893f02SDimitry Andric     // Copy this to all the matching patterns.
4557*b5893f02SDimitry Andric     for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
4558*b5893f02SDimitry Andric       if (p != (int)i) {
4559*b5893f02SDimitry Andric         MatchedPatterns.set(p);
4560*b5893f02SDimitry Andric         MatchedPredicates[p] = Matches;
4561*b5893f02SDimitry Andric       }
4562*b5893f02SDimitry Andric   }
4563*b5893f02SDimitry Andric 
4564*b5893f02SDimitry Andric   for (auto it : PatternsWithVariants) {
4565*b5893f02SDimitry Andric     unsigned i = it.first;
4566*b5893f02SDimitry Andric     const MultipleUseVarSet &DepVars = it.second.first;
4567*b5893f02SDimitry Andric     const std::vector<TreePatternNodePtr> &Variants = it.second.second;
4568*b5893f02SDimitry Andric 
4569f22ef01cSRoman Divacky     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
45704ba319b5SDimitry Andric       TreePatternNodePtr Variant = Variants[v];
4571*b5893f02SDimitry Andric       BitVector &Matches = MatchedPredicates[i];
4572f22ef01cSRoman Divacky 
45734ba319b5SDimitry Andric       LLVM_DEBUG(errs() << "  VAR#" << v << ": "; Variant->dump();
4574f22ef01cSRoman Divacky                  errs() << "\n");
4575f22ef01cSRoman Divacky 
4576f22ef01cSRoman Divacky       // Scan to see if an instruction or explicit pattern already matches this.
4577f22ef01cSRoman Divacky       bool AlreadyExists = false;
4578f22ef01cSRoman Divacky       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4579f22ef01cSRoman Divacky         // Skip if the top level predicates do not match.
4580*b5893f02SDimitry Andric         if (!Matches[p])
4581f22ef01cSRoman Divacky           continue;
4582f22ef01cSRoman Divacky         // Check to see if this variant already exists.
45832754fe60SDimitry Andric         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
45842754fe60SDimitry Andric                                     DepVars)) {
45854ba319b5SDimitry Andric           LLVM_DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
4586f22ef01cSRoman Divacky           AlreadyExists = true;
4587f22ef01cSRoman Divacky           break;
4588f22ef01cSRoman Divacky         }
4589f22ef01cSRoman Divacky       }
4590f22ef01cSRoman Divacky       // If we already have it, ignore the variant.
4591f22ef01cSRoman Divacky       if (AlreadyExists) continue;
4592f22ef01cSRoman Divacky 
4593f22ef01cSRoman Divacky       // Otherwise, add it to the list of patterns we have.
4594a580b014SDimitry Andric       PatternsToMatch.push_back(PatternToMatch(
459597bc6c73SDimitry Andric           PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
45964ba319b5SDimitry Andric           Variant, PatternsToMatch[i].getDstPatternShared(),
4597f22ef01cSRoman Divacky           PatternsToMatch[i].getDstRegs(),
4598a580b014SDimitry Andric           PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
4599*b5893f02SDimitry Andric       MatchedPredicates.push_back(Matches);
4600*b5893f02SDimitry Andric 
4601*b5893f02SDimitry Andric       // Add a new match the same as this pattern.
4602*b5893f02SDimitry Andric       for (auto &P : MatchedPredicates)
4603*b5893f02SDimitry Andric         P.push_back(P[i]);
4604f22ef01cSRoman Divacky     }
4605f22ef01cSRoman Divacky 
46064ba319b5SDimitry Andric     LLVM_DEBUG(errs() << "\n");
4607f22ef01cSRoman Divacky   }
4608f22ef01cSRoman Divacky }
4609