blob: 1d0995563bcf4722ac44da54c2484ffc5e75aae9 [file] [log] [blame]
Chris Lattnerab3242f2008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerab3242f2008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner8cab0212008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner78ac0742008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000016#include "llvm/ADT/STLExtras.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000017#include "llvm/ADT/StringExtras.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000018#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000019#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000020#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000021#include "llvm/TableGen/Error.h"
22#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000023#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000024#include <cstdio>
25#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000026using namespace llvm;
27
Chandler Carruthe96dd892014-04-21 22:55:11 +000028#define DEBUG_TYPE "dag-patterns"
29
Chris Lattner8cab0212008-01-05 22:25:12 +000030//===----------------------------------------------------------------------===//
Chris Lattnercabe0372010-03-15 06:00:16 +000031// EEVT::TypeSet Implementation
32//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +000033
Owen Anderson9f944592009-08-11 20:47:22 +000034static inline bool isInteger(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000035 return MVT(VT).isInteger();
Duncan Sands13237ac2008-06-06 12:08:01 +000036}
Owen Anderson9f944592009-08-11 20:47:22 +000037static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000038 return MVT(VT).isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000039}
Owen Anderson9f944592009-08-11 20:47:22 +000040static inline bool isVector(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000041 return MVT(VT).isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000042}
Chris Lattner6d765eb2010-03-19 17:41:26 +000043static inline bool isScalar(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000044 return !MVT(VT).isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000045}
Duncan Sands13237ac2008-06-06 12:08:01 +000046
Chris Lattnercabe0372010-03-15 06:00:16 +000047EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
48 if (VT == MVT::iAny)
49 EnforceInteger(TP);
50 else if (VT == MVT::fAny)
51 EnforceFloatingPoint(TP);
52 else if (VT == MVT::vAny)
53 EnforceVector(TP);
54 else {
55 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
Ramkumar Ramachandra75a4f352015-01-22 20:14:38 +000056 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
Chris Lattnercabe0372010-03-15 06:00:16 +000057 TypeVec.push_back(VT);
58 }
Chris Lattner8cab0212008-01-05 22:25:12 +000059}
60
Chris Lattnercabe0372010-03-15 06:00:16 +000061
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000062EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
Chris Lattnercabe0372010-03-15 06:00:16 +000063 assert(!VTList.empty() && "empty list?");
64 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +000065
Chris Lattnercabe0372010-03-15 06:00:16 +000066 if (!VTList.empty())
67 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
68 VTList[0] != MVT::fAny);
Jim Grosbach65586fe2010-12-21 16:16:00 +000069
Chris Lattner4a5f7be2010-03-27 20:32:26 +000070 // Verify no duplicates.
Chris Lattnercabe0372010-03-15 06:00:16 +000071 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner4a5f7be2010-03-27 20:32:26 +000072 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner8cab0212008-01-05 22:25:12 +000073}
74
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000075/// FillWithPossibleTypes - Set to all legal types and return true, only valid
76/// on completely unknown type sets.
Chris Lattner6d765eb2010-03-19 17:41:26 +000077bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
78 bool (*Pred)(MVT::SimpleValueType),
79 const char *PredicateName) {
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000080 assert(isCompletelyUnknown());
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000081 ArrayRef<MVT::SimpleValueType> LegalTypes =
Chris Lattner6d765eb2010-03-19 17:41:26 +000082 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +000083
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000084 if (TP.hasError())
85 return false;
86
Chris Lattner6d765eb2010-03-19 17:41:26 +000087 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
Craig Topper24064772014-04-15 07:20:03 +000088 if (!Pred || Pred(LegalTypes[i]))
Chris Lattner6d765eb2010-03-19 17:41:26 +000089 TypeVec.push_back(LegalTypes[i]);
90
91 // If we have nothing that matches the predicate, bail out.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000092 if (TypeVec.empty()) {
Chris Lattner6d765eb2010-03-19 17:41:26 +000093 TP.error("Type inference contradiction found, no " +
Jim Grosbach65586fe2010-12-21 16:16:00 +000094 std::string(PredicateName) + " types found");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000095 return false;
96 }
Chris Lattner6d765eb2010-03-19 17:41:26 +000097 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
99
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000103
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000104 return true;
105}
Chris Lattnercabe0372010-03-15 06:00:16 +0000106
107/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108/// integer value type.
109bool EEVT::TypeSet::hasIntegerTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000110 return std::any_of(TypeVec.begin(), TypeVec.end(), isInteger);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000111}
Chris Lattnercabe0372010-03-15 06:00:16 +0000112
113/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
114/// a floating point value type.
115bool EEVT::TypeSet::hasFloatingPointTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000116 return std::any_of(TypeVec.begin(), TypeVec.end(), isFloatingPoint);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000117}
Chris Lattnercabe0372010-03-15 06:00:16 +0000118
Craig Topper74169dc2014-01-28 04:49:01 +0000119/// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
120bool EEVT::TypeSet::hasScalarTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000121 return std::any_of(TypeVec.begin(), TypeVec.end(), isScalar);
Craig Topper74169dc2014-01-28 04:49:01 +0000122}
123
Chris Lattnercabe0372010-03-15 06:00:16 +0000124/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
125/// value type.
126bool EEVT::TypeSet::hasVectorTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000127 return std::any_of(TypeVec.begin(), TypeVec.end(), isVector);
Chris Lattner8cab0212008-01-05 22:25:12 +0000128}
Bob Wilson2cd5da82009-08-11 01:14:02 +0000129
Chris Lattnercabe0372010-03-15 06:00:16 +0000130
131std::string EEVT::TypeSet::getName() const {
Chris Lattnerda5b4ad2010-03-19 01:14:27 +0000132 if (TypeVec.empty()) return "<empty>";
Jim Grosbach65586fe2010-12-21 16:16:00 +0000133
Chris Lattnercabe0372010-03-15 06:00:16 +0000134 std::string Result;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000135
Chris Lattnercabe0372010-03-15 06:00:16 +0000136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
137 std::string VTName = llvm::getEnumName(TypeVec[i]);
138 // Strip off MVT:: prefix if present.
139 if (VTName.substr(0,5) == "MVT::")
140 VTName = VTName.substr(5);
141 if (i) Result += ':';
142 Result += VTName;
143 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000144
Chris Lattnercabe0372010-03-15 06:00:16 +0000145 if (TypeVec.size() == 1)
146 return Result;
147 return "{" + Result + "}";
Bob Wilson2cd5da82009-08-11 01:14:02 +0000148}
Chris Lattnercabe0372010-03-15 06:00:16 +0000149
150/// MergeInTypeInfo - This merges in type information from the specified
151/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000152/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattnercabe0372010-03-15 06:00:16 +0000153bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000154 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattnercabe0372010-03-15 06:00:16 +0000155 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000156
Chris Lattnercabe0372010-03-15 06:00:16 +0000157 if (isCompletelyUnknown()) {
158 *this = InVT;
159 return true;
160 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000161
Chris Lattnercabe0372010-03-15 06:00:16 +0000162 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000163
Chris Lattnercabe0372010-03-15 06:00:16 +0000164 // Handle the abstract cases, seeing if we can resolve them better.
165 switch (TypeVec[0]) {
166 default: break;
167 case MVT::iPTR:
168 case MVT::iPTRAny:
169 if (InVT.hasIntegerTypes()) {
170 EEVT::TypeSet InCopy(InVT);
171 InCopy.EnforceInteger(TP);
172 InCopy.EnforceScalar(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000173
Chris Lattnercabe0372010-03-15 06:00:16 +0000174 if (InCopy.isConcrete()) {
175 // If the RHS has one integer type, upgrade iPTR to i32.
176 TypeVec[0] = InVT.TypeVec[0];
177 return true;
178 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000179
Chris Lattnercabe0372010-03-15 06:00:16 +0000180 // If the input has multiple scalar integers, this doesn't add any info.
181 if (!InCopy.isCompletelyUnknown())
182 return false;
183 }
184 break;
185 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000186
Chris Lattnercabe0372010-03-15 06:00:16 +0000187 // If the input constraint is iAny/iPTR and this is an integer type list,
188 // remove non-integer types from the list.
189 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
190 hasIntegerTypes()) {
191 bool MadeChange = EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000192
Chris Lattnercabe0372010-03-15 06:00:16 +0000193 // If we're merging in iPTR/iPTRAny and the node currently has a list of
194 // multiple different integer types, replace them with a single iPTR.
195 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
196 TypeVec.size() != 1) {
197 TypeVec.resize(1);
198 TypeVec[0] = InVT.TypeVec[0];
199 MadeChange = true;
200 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000201
Chris Lattnercabe0372010-03-15 06:00:16 +0000202 return MadeChange;
203 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000204
Chris Lattnercabe0372010-03-15 06:00:16 +0000205 // If this is a type list and the RHS is a typelist as well, eliminate entries
206 // from this list that aren't in the other one.
207 bool MadeChange = false;
208 TypeSet InputSet(*this);
209
210 for (unsigned i = 0; i != TypeVec.size(); ++i) {
Craig Toppercbdc27e2015-11-22 19:27:02 +0000211 if (std::find(InVT.TypeVec.begin(), InVT.TypeVec.end(), TypeVec[i]) !=
212 InVT.TypeVec.end())
213 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000214
Chris Lattnercabe0372010-03-15 06:00:16 +0000215 TypeVec.erase(TypeVec.begin()+i--);
216 MadeChange = true;
217 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000218
Chris Lattnercabe0372010-03-15 06:00:16 +0000219 // If we removed all of our types, we have a type contradiction.
220 if (!TypeVec.empty())
221 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000222
Chris Lattnercabe0372010-03-15 06:00:16 +0000223 // FIXME: Really want an SMLoc here!
224 TP.error("Type inference contradiction found, merging '" +
225 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000226 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000227}
228
229/// EnforceInteger - Remove all non-integer types from this set.
230bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000231 if (TP.hasError())
232 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000233 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000234 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000235 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattnercabe0372010-03-15 06:00:16 +0000236 if (!hasFloatingPointTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000237 return false;
238
239 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000240
Chris Lattnercabe0372010-03-15 06:00:16 +0000241 // Filter out all the fp types.
242 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000243 if (!isInteger(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000244 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000245
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000246 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000247 TP.error("Type inference contradiction found, '" +
248 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000249 return false;
250 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000251 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000252}
253
254/// EnforceFloatingPoint - Remove all integer types from this set.
255bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000256 if (TP.hasError())
257 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000258 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000259 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000260 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
261
Chris Lattnercabe0372010-03-15 06:00:16 +0000262 if (!hasIntegerTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000263 return false;
264
265 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000266
Chris Lattnercabe0372010-03-15 06:00:16 +0000267 // Filter out all the fp types.
268 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000269 if (!isFloatingPoint(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000270 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000271
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000272 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000273 TP.error("Type inference contradiction found, '" +
274 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000275 return false;
276 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000277 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000278}
279
280/// EnforceScalar - Remove all vector types from this.
281bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000282 if (TP.hasError())
283 return false;
284
Chris Lattnercabe0372010-03-15 06:00:16 +0000285 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000286 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000287 return FillWithPossibleTypes(TP, isScalar, "scalar");
288
Chris Lattnercabe0372010-03-15 06:00:16 +0000289 if (!hasVectorTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000290 return false;
291
292 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000293
Chris Lattnercabe0372010-03-15 06:00:16 +0000294 // Filter out all the vector types.
295 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000296 if (!isScalar(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000297 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000298
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000299 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000300 TP.error("Type inference contradiction found, '" +
301 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000302 return false;
303 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000304 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000305}
306
307/// EnforceVector - Remove all vector types from this.
308bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000309 if (TP.hasError())
310 return false;
311
Chris Lattner6d765eb2010-03-19 17:41:26 +0000312 // If we know nothing, then get the full set.
313 if (TypeVec.empty())
314 return FillWithPossibleTypes(TP, isVector, "vector");
315
Chris Lattnercabe0372010-03-15 06:00:16 +0000316 TypeSet InputSet(*this);
317 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000318
Chris Lattnercabe0372010-03-15 06:00:16 +0000319 // Filter out all the scalar types.
320 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000321 if (!isVector(TypeVec[i])) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000322 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner6d765eb2010-03-19 17:41:26 +0000323 MadeChange = true;
324 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000325
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000326 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000327 TP.error("Type inference contradiction found, '" +
328 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000329 return false;
330 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000331 return MadeChange;
332}
333
334
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000335
Craig Topper74169dc2014-01-28 04:49:01 +0000336/// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000337/// this should be based on the element type. Update this and other based on
Craig Topper74169dc2014-01-28 04:49:01 +0000338/// this information.
Chris Lattnercabe0372010-03-15 06:00:16 +0000339bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000340 if (TP.hasError())
341 return false;
342
Chris Lattnercabe0372010-03-15 06:00:16 +0000343 // Both operands must be integer or FP, but we don't care which.
344 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000345
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000346 if (isCompletelyUnknown())
347 MadeChange = FillWithPossibleTypes(TP);
348
349 if (Other.isCompletelyUnknown())
350 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000351
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000352 // If one side is known to be integer or known to be FP but the other side has
353 // no information, get at least the type integrality info in there.
354 if (!hasFloatingPointTypes())
355 MadeChange |= Other.EnforceInteger(TP);
356 else if (!hasIntegerTypes())
357 MadeChange |= Other.EnforceFloatingPoint(TP);
358 if (!Other.hasFloatingPointTypes())
359 MadeChange |= EnforceInteger(TP);
360 else if (!Other.hasIntegerTypes())
361 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000362
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000363 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
364 "Should have a type list now");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000365
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000366 // If one contains vectors but the other doesn't pull vectors out.
367 if (!hasVectorTypes())
368 MadeChange |= Other.EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000369 else if (!hasScalarTypes())
370 MadeChange |= Other.EnforceVector(TP);
Craig Topper6dbcb942014-01-25 05:17:38 +0000371 if (!Other.hasVectorTypes())
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000372 MadeChange |= EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000373 else if (!Other.hasScalarTypes())
374 MadeChange |= EnforceVector(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000375
Craig Topper74169dc2014-01-28 04:49:01 +0000376 // This code does not currently handle nodes which have multiple types,
377 // where some types are integer, and some are fp. Assert that this is not
378 // the case.
379 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
380 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
381 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
382
383 if (TP.hasError())
384 return false;
385
Craig Topper7bbd37b2015-03-10 03:25:07 +0000386 // Okay, find the smallest type from current set and remove anything the
387 // same or smaller from the other set. We need to ensure that the scalar
388 // type size is smaller than the scalar size of the smallest type. For
389 // vectors, we also need to make sure that the total size is no larger than
390 // the size of the smallest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000391 TypeSet InputSet(Other);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000392 MVT Smallest = TypeVec[0];
Craig Topper74169dc2014-01-28 04:49:01 +0000393 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000394 MVT OtherVT = Other.TypeVec[i];
395 // Don't compare vector and non-vector types.
396 if (OtherVT.isVector() != Smallest.isVector())
397 continue;
398 // The getSizeInBits() check here is only needed for vectors, but is
399 // a subset of the scalar check for scalars so no need to qualify.
400 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
401 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000402 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
403 MadeChange = true;
404 }
405 }
406
407 if (Other.TypeVec.empty()) {
408 TP.error("Type inference contradiction found, '" + InputSet.getName() +
409 "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000410 return false;
411 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000412
Craig Topper7bbd37b2015-03-10 03:25:07 +0000413 // Okay, find the largest type from the other set and remove anything the
414 // same or smaller from the current set. We need to ensure that the scalar
415 // type size is larger than the scalar size of the largest type. For
416 // vectors, we also need to make sure that the total size is no smaller than
417 // the size of the largest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000418 InputSet = TypeSet(*this);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000419 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
Craig Topper74169dc2014-01-28 04:49:01 +0000420 for (unsigned i = 0; i != TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000421 MVT OtherVT = TypeVec[i];
422 // Don't compare vector and non-vector types.
423 if (OtherVT.isVector() != Largest.isVector())
424 continue;
425 // The getSizeInBits() check here is only needed for vectors, but is
426 // a subset of the scalar check for scalars so no need to qualify.
427 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
428 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000429 TypeVec.erase(TypeVec.begin()+i--);
430 MadeChange = true;
David Greene433c6182011-02-01 19:12:32 +0000431 }
David Greene433c6182011-02-01 19:12:32 +0000432 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000433
Craig Topper74169dc2014-01-28 04:49:01 +0000434 if (TypeVec.empty()) {
435 TP.error("Type inference contradiction found, '" + InputSet.getName() +
436 "' has nothing smaller than '" + Other.getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000437 return false;
438 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000439
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000440 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000441}
442
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000443/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000444/// whose element is specified by VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000445bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
446 TreePattern &TP) {
447 bool MadeChange = false;
448
449 MadeChange |= EnforceVector(TP);
450
451 TypeSet InputSet(*this);
452
453 // Filter out all the types which don't have the right element type.
454 for (unsigned i = 0; i != TypeVec.size(); ++i) {
455 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
456 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
457 TypeVec.erase(TypeVec.begin()+i--);
458 MadeChange = true;
459 }
460 }
461
462 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
463 TP.error("Type inference contradiction found, forcing '" +
464 InputSet.getName() + "' to have a vector element");
465 return false;
466 }
467
468 return MadeChange;
469}
470
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000471/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Craig Topper0be34582015-03-05 07:11:34 +0000472/// whose element is specified by VTOperand.
Chris Lattner57ebf632010-03-24 00:01:16 +0000473bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000474 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000475 if (TP.hasError())
476 return false;
477
Chris Lattner57ebf632010-03-24 00:01:16 +0000478 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000479 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000480 MadeChange |= EnforceVector(TP);
481 MadeChange |= VTOperand.EnforceScalar(TP);
482
483 // If we know the vector type, it forces the scalar to agree.
484 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000485 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000486 IVT = IVT.getVectorElementType();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000487 return MadeChange |
Craig Topper95198f42013-09-25 06:37:18 +0000488 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000489 }
490
491 // If the scalar type is known, filter out vector types whose element types
492 // disagree.
493 if (!VTOperand.isConcrete())
494 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000495
Chris Lattner57ebf632010-03-24 00:01:16 +0000496 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000497
Chris Lattner57ebf632010-03-24 00:01:16 +0000498 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000499
Chris Lattner57ebf632010-03-24 00:01:16 +0000500 // Filter out all the types which don't have the right element type.
501 for (unsigned i = 0; i != TypeVec.size(); ++i) {
502 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
Craig Topper95198f42013-09-25 06:37:18 +0000503 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000504 TypeVec.erase(TypeVec.begin()+i--);
505 MadeChange = true;
506 }
Chris Lattner57ebf632010-03-24 00:01:16 +0000507 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000508
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000509 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattnercabe0372010-03-15 06:00:16 +0000510 TP.error("Type inference contradiction found, forcing '" +
511 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000512 return false;
513 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000514 return MadeChange;
515}
516
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000517/// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
David Greene127fd1d2011-01-24 20:53:18 +0000518/// vector type specified by VTOperand.
519bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
520 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000521 if (TP.hasError())
522 return false;
523
David Greene127fd1d2011-01-24 20:53:18 +0000524 // "This" must be a vector and "VTOperand" must be a vector.
525 bool MadeChange = false;
526 MadeChange |= EnforceVector(TP);
527 MadeChange |= VTOperand.EnforceVector(TP);
528
Craig Topper6e1faaf2014-01-25 17:40:33 +0000529 // If one side is known to be integer or known to be FP but the other side has
530 // no information, get at least the type integrality info in there.
531 if (!hasFloatingPointTypes())
532 MadeChange |= VTOperand.EnforceInteger(TP);
533 else if (!hasIntegerTypes())
534 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
535 if (!VTOperand.hasFloatingPointTypes())
536 MadeChange |= EnforceInteger(TP);
537 else if (!VTOperand.hasIntegerTypes())
538 MadeChange |= EnforceFloatingPoint(TP);
539
540 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
541 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000542
543 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000544 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000545 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000546 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000547 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000548 IVT = IVT.getVectorElementType();
549
Craig Topper95198f42013-09-25 06:37:18 +0000550 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000551 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000552
553 // Only keep types that have less elements than VTOperand.
554 TypeSet InputSet(VTOperand);
555
556 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
557 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
558 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
559 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
560 MadeChange = true;
561 }
562 }
563 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
564 TP.error("Type inference contradiction found, forcing '" +
565 InputSet.getName() + "' to have less vector elements than '" +
566 getName() + "'");
567 return false;
568 }
David Greene127fd1d2011-01-24 20:53:18 +0000569 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000570 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000571 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000572 IVT = IVT.getVectorElementType();
573
Craig Topper95198f42013-09-25 06:37:18 +0000574 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000575 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000576
577 // Only keep types that have more elements than 'this'.
578 TypeSet InputSet(*this);
579
580 for (unsigned i = 0; i != TypeVec.size(); ++i) {
581 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
582 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
583 TypeVec.erase(TypeVec.begin()+i--);
584 MadeChange = true;
585 }
586 }
587 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
588 TP.error("Type inference contradiction found, forcing '" +
589 InputSet.getName() + "' to have more vector elements than '" +
590 VTOperand.getName() + "'");
591 return false;
592 }
David Greene127fd1d2011-01-24 20:53:18 +0000593 }
594
595 return MadeChange;
596}
597
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000598/// EnforceVectorSameNumElts - 'this' is now constrained to
Craig Topper0be34582015-03-05 07:11:34 +0000599/// be a vector with same num elements as VTOperand.
600bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
601 TreePattern &TP) {
602 if (TP.hasError())
603 return false;
604
605 // "This" must be a vector and "VTOperand" must be a vector.
606 bool MadeChange = false;
607 MadeChange |= EnforceVector(TP);
608 MadeChange |= VTOperand.EnforceVector(TP);
609
610 // If we know one of the vector types, it forces the other type to agree.
611 if (isConcrete()) {
612 MVT IVT = getConcrete();
613 unsigned NumElems = IVT.getVectorNumElements();
614
615 // Only keep types that have same elements as VTOperand.
616 TypeSet InputSet(VTOperand);
617
618 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
619 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
620 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
621 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
622 MadeChange = true;
623 }
624 }
625 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
626 TP.error("Type inference contradiction found, forcing '" +
627 InputSet.getName() + "' to have same number elements as '" +
628 getName() + "'");
629 return false;
630 }
631 } else if (VTOperand.isConcrete()) {
632 MVT IVT = VTOperand.getConcrete();
633 unsigned NumElems = IVT.getVectorNumElements();
634
635 // Only keep types that have same elements as 'this'.
636 TypeSet InputSet(*this);
637
638 for (unsigned i = 0; i != TypeVec.size(); ++i) {
639 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
640 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
641 TypeVec.erase(TypeVec.begin()+i--);
642 MadeChange = true;
643 }
644 }
645 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
646 TP.error("Type inference contradiction found, forcing '" +
647 InputSet.getName() + "' to have same number elements than '" +
648 VTOperand.getName() + "'");
649 return false;
650 }
651 }
652
653 return MadeChange;
654}
655
Chris Lattnercabe0372010-03-15 06:00:16 +0000656//===----------------------------------------------------------------------===//
657// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000658
Scott Michel94420742008-03-05 17:49:05 +0000659/// Dependent variable map for CodeGenDAGPattern variant generation
660typedef std::map<std::string, int> DepVarMap;
661
662/// Const iterator shorthand for DepVarMap
663typedef DepVarMap::const_iterator DepVarMap_citer;
664
Chris Lattner514e2922011-04-17 21:38:24 +0000665static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000666 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000667 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000668 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000669 } else {
670 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
671 FindDepVarsOf(N->getChild(i), DepMap);
672 }
673}
Chris Lattner514e2922011-04-17 21:38:24 +0000674
675/// Find dependent variables within child patterns
676static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000677 DepVarMap depcounts;
678 FindDepVarsOf(N, depcounts);
679 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner514e2922011-04-17 21:38:24 +0000680 if (i->second > 1) // std::pair<std::string, int>
Scott Michel94420742008-03-05 17:49:05 +0000681 DepVars.insert(i->first);
Scott Michel94420742008-03-05 17:49:05 +0000682 }
683}
684
Daniel Dunbarba66a812010-10-08 02:07:22 +0000685#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000686/// Dump the dependent variable set:
687static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000688 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000689 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000690 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000691 DEBUG(errs() << "[ ");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +0000692 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
693 e = DepVars.end(); i != e; ++i) {
Chris Lattner34822f62009-08-23 04:44:11 +0000694 DEBUG(errs() << (*i) << " ");
Scott Michel94420742008-03-05 17:49:05 +0000695 }
Chris Lattner34822f62009-08-23 04:44:11 +0000696 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000697 }
698}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000699#endif
700
Chris Lattner514e2922011-04-17 21:38:24 +0000701
702//===----------------------------------------------------------------------===//
703// TreePredicateFn Implementation
704//===----------------------------------------------------------------------===//
705
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000706/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
707TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
708 assert((getPredCode().empty() || getImmCode().empty()) &&
709 ".td file corrupt: can't have a node predicate *and* an imm predicate");
710}
711
Chris Lattner514e2922011-04-17 21:38:24 +0000712std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000713 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000714}
715
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000716std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000717 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000718}
719
Chris Lattner514e2922011-04-17 21:38:24 +0000720
721/// isAlwaysTrue - Return true if this is a noop predicate.
722bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000723 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000724}
725
726/// Return the name to use in the generated code to reference this, this is
727/// "Predicate_foo" if from a pattern fragment "foo".
728std::string TreePredicateFn::getFnName() const {
729 return "Predicate_" + PatFragRec->getRecord()->getName();
730}
731
732/// getCodeToRunOnSDNode - Return the code for the function body that
733/// evaluates this predicate. The argument is expected to be in "Node",
734/// not N. This handles casting and conversion to a concrete node type as
735/// appropriate.
736std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000737 // Handle immediate predicates first.
738 std::string ImmCode = getImmCode();
739 if (!ImmCode.empty()) {
740 std::string Result =
741 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000742 return Result + ImmCode;
743 }
744
745 // Handle arbitrary node predicates.
746 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000747 std::string ClassName;
748 if (PatFragRec->getOnlyTree()->isLeaf())
749 ClassName = "SDNode";
750 else {
751 Record *Op = PatFragRec->getOnlyTree()->getOperator();
752 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
753 }
754 std::string Result;
755 if (ClassName == "SDNode")
756 Result = " SDNode *N = Node;\n";
757 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000758 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000759
760 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000761}
762
Chris Lattner8cab0212008-01-05 22:25:12 +0000763//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000764// PatternToMatch implementation
765//
766
Chris Lattner05925fe2010-03-29 01:40:38 +0000767
768/// getPatternSize - Return the 'size' of this pattern. We want to match large
769/// patterns before small ones. This is used to determine the size of a
770/// pattern.
771static unsigned getPatternSize(const TreePatternNode *P,
772 const CodeGenDAGPatterns &CGP) {
773 unsigned Size = 3; // The node itself.
774 // If the root node is a ConstantSDNode, increases its size.
775 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000776 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000777 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000778
Chris Lattner05925fe2010-03-29 01:40:38 +0000779 // FIXME: This is a hack to statically increase the priority of patterns
780 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
781 // Later we can allow complexity / cost for each pattern to be (optionally)
782 // specified. To get best possible pattern match we'll need to dynamically
783 // calculate the complexity of all patterns a dag can potentially map to.
784 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000785 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000786 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000787
Tim Northoverc807a172014-05-20 11:52:46 +0000788 // We don't want to count any children twice, so return early.
789 return Size;
790 }
791
Chris Lattner05925fe2010-03-29 01:40:38 +0000792 // If this node has some predicate function that must match, it adds to the
793 // complexity of this node.
794 if (!P->getPredicateFns().empty())
795 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000796
Chris Lattner05925fe2010-03-29 01:40:38 +0000797 // Count children in the count if they are also nodes.
798 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
799 TreePatternNode *Child = P->getChild(i);
800 if (!Child->isLeaf() && Child->getNumTypes() &&
801 Child->getType(0) != MVT::Other)
802 Size += getPatternSize(Child, CGP);
803 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000804 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000805 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
806 else if (Child->getComplexPatternInfo(CGP))
807 Size += getPatternSize(Child, CGP);
808 else if (!Child->getPredicateFns().empty())
809 ++Size;
810 }
811 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000812
Chris Lattner05925fe2010-03-29 01:40:38 +0000813 return Size;
814}
815
816/// Compute the complexity metric for the input pattern. This roughly
817/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000818int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000819getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
820 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
821}
822
823
Dan Gohman49e19e92008-08-22 00:20:26 +0000824/// getPredicateCheck - Return a single string containing all of this
825/// pattern's predicates concatenated with "&&" operators.
826///
827std::string PatternToMatch::getPredicateCheck() const {
828 std::string PredicateCheck;
Craig Topperef0578a2015-06-02 04:15:51 +0000829 for (Init *I : Predicates->getValues()) {
830 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000831 Record *Def = Pred->getDef();
832 if (!Def->isSubClassOf("Predicate")) {
833#ifndef NDEBUG
834 Def->dump();
835#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000836 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000837 }
838 if (!PredicateCheck.empty())
839 PredicateCheck += " && ";
840 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
841 }
842 }
843
844 return PredicateCheck;
845}
846
847//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000848// SDTypeConstraint implementation
849//
850
851SDTypeConstraint::SDTypeConstraint(Record *R) {
852 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000853
Chris Lattner8cab0212008-01-05 22:25:12 +0000854 if (R->isSubClassOf("SDTCisVT")) {
855 ConstraintType = SDTCisVT;
856 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000857 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000858 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000859
Chris Lattner8cab0212008-01-05 22:25:12 +0000860 } else if (R->isSubClassOf("SDTCisPtrTy")) {
861 ConstraintType = SDTCisPtrTy;
862 } else if (R->isSubClassOf("SDTCisInt")) {
863 ConstraintType = SDTCisInt;
864 } else if (R->isSubClassOf("SDTCisFP")) {
865 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000866 } else if (R->isSubClassOf("SDTCisVec")) {
867 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000868 } else if (R->isSubClassOf("SDTCisSameAs")) {
869 ConstraintType = SDTCisSameAs;
870 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
871 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
872 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000873 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000874 R->getValueAsInt("OtherOperandNum");
875 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
876 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000877 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000878 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000879 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
880 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000881 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000882 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
883 ConstraintType = SDTCisSubVecOfVec;
884 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
885 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000886 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
887 ConstraintType = SDTCVecEltisVT;
888 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
889 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
890 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
891 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
892 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
893 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
894 "as SDTCVecEltisVT");
895 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
896 ConstraintType = SDTCisSameNumEltsAs;
897 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
898 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000899 } else {
James Y Knighte452e272015-05-11 22:17:13 +0000900 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +0000901 }
902}
903
904/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000905/// N, and the result number in ResNo.
906static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
907 const SDNodeInfo &NodeInfo,
908 unsigned &ResNo) {
909 unsigned NumResults = NodeInfo.getNumResults();
910 if (OpNo < NumResults) {
911 ResNo = OpNo;
912 return N;
913 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000914
Chris Lattner2db7aba2010-03-19 21:56:21 +0000915 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000916
Chris Lattner2db7aba2010-03-19 21:56:21 +0000917 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +0000918 std::string S;
919 raw_string_ostream OS(S);
920 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000921 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +0000922 N->print(OS);
923 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +0000924 }
925
Chris Lattner2db7aba2010-03-19 21:56:21 +0000926 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000927}
928
929/// ApplyTypeConstraint - Given a node in a pattern, apply this type
930/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000931/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000932bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
933 const SDNodeInfo &NodeInfo,
934 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000935 if (TP.hasError())
936 return false;
937
Chris Lattner2db7aba2010-03-19 21:56:21 +0000938 unsigned ResNo = 0; // The result number being referenced.
939 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000940
Chris Lattner8cab0212008-01-05 22:25:12 +0000941 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000942 case SDTCisVT:
943 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000944 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000945 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000946 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000947 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000948 case SDTCisInt:
949 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000950 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000951 case SDTCisFP:
952 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000953 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000954 case SDTCisVec:
955 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000956 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000957 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000958 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000959 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000960 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +0000961 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
962 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000963 }
964 case SDTCisVTSmallerThanOp: {
965 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
966 // have an integer type that is smaller than the VT.
967 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +0000968 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +0000969 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000970 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000971 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000972 return false;
973 }
Owen Anderson9f944592009-08-11 20:47:22 +0000974 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +0000975 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000976
Chris Lattner38c99662010-03-24 00:06:46 +0000977 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000978
Chris Lattner2db7aba2010-03-19 21:56:21 +0000979 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000980 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000981 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
982 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +0000983
Chris Lattner38c99662010-03-24 00:06:46 +0000984 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000985 }
986 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000987 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000988 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000989 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
990 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000991 return NodeToApply->getExtType(ResNo).
992 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000993 }
Nate Begeman17bedbc2008-02-09 01:37:05 +0000994 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000995 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +0000996 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000997 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
998 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000999
Chris Lattner57ebf632010-03-24 00:01:16 +00001000 // Filter vector types out of VecOperand that don't have the right element
1001 // type.
1002 return VecOperand->getExtType(VResNo).
1003 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +00001004 }
David Greene127fd1d2011-01-24 20:53:18 +00001005 case SDTCisSubVecOfVec: {
1006 unsigned VResNo = 0;
1007 TreePatternNode *BigVecOperand =
1008 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1009 VResNo);
1010
1011 // Filter vector types out of BigVecOperand that don't have the
1012 // right subvector type.
1013 return BigVecOperand->getExtType(VResNo).
1014 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1015 }
Craig Topper0be34582015-03-05 07:11:34 +00001016 case SDTCVecEltisVT: {
1017 return NodeToApply->getExtType(ResNo).
1018 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1019 }
1020 case SDTCisSameNumEltsAs: {
1021 unsigned OResNo = 0;
1022 TreePatternNode *OtherNode =
1023 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1024 N, NodeInfo, OResNo);
1025 return OtherNode->getExtType(OResNo).
1026 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1027 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001028 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001029 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001030}
1031
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001032// Update the node type to match an instruction operand or result as specified
1033// in the ins or outs lists on the instruction definition. Return true if the
1034// type was actually changed.
1035bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1036 Record *Operand,
1037 TreePattern &TP) {
1038 // The 'unknown' operand indicates that types should be inferred from the
1039 // context.
1040 if (Operand->isSubClassOf("unknown_class"))
1041 return false;
1042
1043 // The Operand class specifies a type directly.
1044 if (Operand->isSubClassOf("Operand"))
1045 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1046 TP);
1047
1048 // PointerLikeRegClass has a type that is determined at runtime.
1049 if (Operand->isSubClassOf("PointerLikeRegClass"))
1050 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1051
1052 // Both RegisterClass and RegisterOperand operands derive their types from a
1053 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001054 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001055 if (Operand->isSubClassOf("RegisterClass"))
1056 RC = Operand;
1057 else if (Operand->isSubClassOf("RegisterOperand"))
1058 RC = Operand->getValueAsDef("RegClass");
1059
1060 assert(RC && "Unknown operand type");
1061 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1062 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1063}
1064
1065
Chris Lattner8cab0212008-01-05 22:25:12 +00001066//===----------------------------------------------------------------------===//
1067// SDNodeInfo implementation
1068//
1069SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1070 EnumName = R->getValueAsString("Opcode");
1071 SDClassName = R->getValueAsString("SDClass");
1072 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1073 NumResults = TypeProfile->getValueAsInt("NumResults");
1074 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001075
Chris Lattner8cab0212008-01-05 22:25:12 +00001076 // Parse the properties.
1077 Properties = 0;
1078 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1079 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1080 if (PropList[i]->getName() == "SDNPCommutative") {
1081 Properties |= 1 << SDNPCommutative;
1082 } else if (PropList[i]->getName() == "SDNPAssociative") {
1083 Properties |= 1 << SDNPAssociative;
1084 } else if (PropList[i]->getName() == "SDNPHasChain") {
1085 Properties |= 1 << SDNPHasChain;
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001086 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1087 Properties |= 1 << SDNPOutGlue;
1088 } else if (PropList[i]->getName() == "SDNPInGlue") {
1089 Properties |= 1 << SDNPInGlue;
1090 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1091 Properties |= 1 << SDNPOptInGlue;
Chris Lattnera348f552008-01-06 06:44:58 +00001092 } else if (PropList[i]->getName() == "SDNPMayStore") {
1093 Properties |= 1 << SDNPMayStore;
Chris Lattner1ca20682008-01-10 04:38:57 +00001094 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1095 Properties |= 1 << SDNPMayLoad;
Chris Lattner42c63ef2008-01-10 05:39:30 +00001096 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1097 Properties |= 1 << SDNPSideEffect;
Mon P Wang6a490372008-06-25 08:15:39 +00001098 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1099 Properties |= 1 << SDNPMemOperand;
Chris Lattner83aeaab2010-03-19 05:07:09 +00001100 } else if (PropList[i]->getName() == "SDNPVariadic") {
1101 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001102 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001103 PrintFatalError("Unknown SD Node property '" +
1104 PropList[i]->getName() + "' on node '" +
1105 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001106 }
1107 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001108
1109
Chris Lattner8cab0212008-01-05 22:25:12 +00001110 // Parse the type constraints.
1111 std::vector<Record*> ConstraintList =
1112 TypeProfile->getValueAsListOfDefs("Constraints");
1113 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1114}
1115
Chris Lattner99e53b32010-02-28 00:22:30 +00001116/// getKnownType - If the type constraints on this node imply a fixed type
1117/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001118/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001119MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001120 unsigned NumResults = getNumResults();
1121 assert(NumResults <= 1 &&
1122 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001123 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001124
Chris Lattner99e53b32010-02-28 00:22:30 +00001125 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1126 // Make sure that this applies to the correct node result.
1127 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1128 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001129
Chris Lattner99e53b32010-02-28 00:22:30 +00001130 switch (TypeConstraints[i].ConstraintType) {
1131 default: break;
1132 case SDTypeConstraint::SDTCisVT:
1133 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1134 case SDTypeConstraint::SDTCisPtrTy:
1135 return MVT::iPTR;
1136 }
1137 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001138 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001139}
1140
Chris Lattner8cab0212008-01-05 22:25:12 +00001141//===----------------------------------------------------------------------===//
1142// TreePatternNode implementation
1143//
1144
1145TreePatternNode::~TreePatternNode() {
1146#if 0 // FIXME: implement refcounted tree nodes!
1147 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1148 delete getChild(i);
1149#endif
1150}
1151
Chris Lattnerf1447252010-03-19 21:37:09 +00001152static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1153 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001154 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001155 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001156
Chris Lattner2109cb42010-03-22 20:56:36 +00001157 if (Operator->isSubClassOf("Intrinsic"))
1158 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001159
Chris Lattnerf1447252010-03-19 21:37:09 +00001160 if (Operator->isSubClassOf("SDNode"))
1161 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001162
Chris Lattnerf1447252010-03-19 21:37:09 +00001163 if (Operator->isSubClassOf("PatFrag")) {
1164 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1165 // the forward reference case where one pattern fragment references another
1166 // before it is processed.
1167 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1168 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001169
Chris Lattnerf1447252010-03-19 21:37:09 +00001170 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001171 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001172 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001173 if (Tree)
1174 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1175 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001176 assert(Op && "Invalid Fragment");
1177 return GetNumNodeResults(Op, CDP);
1178 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001179
Chris Lattnerf1447252010-03-19 21:37:09 +00001180 if (Operator->isSubClassOf("Instruction")) {
1181 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001182
Craig Topper3a8eb892015-03-20 05:09:06 +00001183 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1184
1185 // Subtract any defaulted outputs.
1186 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1187 Record *OperandNode = InstInfo.Operands[i].Rec;
1188
1189 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1190 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1191 --NumDefsToAdd;
1192 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001193
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001194 // Add on one implicit def if it has a resolvable type.
1195 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1196 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001197 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001198 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001199
Chris Lattnerf1447252010-03-19 21:37:09 +00001200 if (Operator->isSubClassOf("SDNodeXForm"))
1201 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001202
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001203 if (Operator->isSubClassOf("ValueType"))
1204 return 1; // A type-cast of one result.
1205
Tim Northoverc807a172014-05-20 11:52:46 +00001206 if (Operator->isSubClassOf("ComplexPattern"))
1207 return 1;
1208
Chris Lattnerf1447252010-03-19 21:37:09 +00001209 Operator->dump();
James Y Knighte452e272015-05-11 22:17:13 +00001210 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001211}
1212
1213void TreePatternNode::print(raw_ostream &OS) const {
1214 if (isLeaf())
1215 OS << *getLeafValue();
1216 else
1217 OS << '(' << getOperator()->getName();
1218
1219 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1220 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001221
1222 if (!isLeaf()) {
1223 if (getNumChildren() != 0) {
1224 OS << " ";
1225 getChild(0)->print(OS);
1226 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1227 OS << ", ";
1228 getChild(i)->print(OS);
1229 }
1230 }
1231 OS << ")";
1232 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001233
Dan Gohman6e979022008-10-15 06:17:21 +00001234 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner514e2922011-04-17 21:38:24 +00001235 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001236 if (TransformFn)
1237 OS << "<<X:" << TransformFn->getName() << ">>";
1238 if (!getName().empty())
1239 OS << ":$" << getName();
1240
1241}
1242void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001243 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001244}
1245
Scott Michel94420742008-03-05 17:49:05 +00001246/// isIsomorphicTo - Return true if this node is recursively
1247/// isomorphic to the specified node. For this comparison, the node's
1248/// entire state is considered. The assigned name is ignored, since
1249/// nodes with differing names are considered isomorphic. However, if
1250/// the assigned name is present in the dependent variable set, then
1251/// the assigned name is considered significant and the node is
1252/// isomorphic if the names match.
1253bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1254 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001255 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001256 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001257 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001258 getTransformFn() != N->getTransformFn())
1259 return false;
1260
1261 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001262 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1263 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001264 return ((DI->getDef() == NDI->getDef())
1265 && (DepVars.find(getName()) == DepVars.end()
1266 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001267 }
1268 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001269 return getLeafValue() == N->getLeafValue();
1270 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001271
Chris Lattner8cab0212008-01-05 22:25:12 +00001272 if (N->getOperator() != getOperator() ||
1273 N->getNumChildren() != getNumChildren()) return false;
1274 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001275 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001276 return false;
1277 return true;
1278}
1279
1280/// clone - Make a copy of this tree and all of its children.
1281///
1282TreePatternNode *TreePatternNode::clone() const {
1283 TreePatternNode *New;
1284 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001285 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001286 } else {
1287 std::vector<TreePatternNode*> CChildren;
1288 CChildren.reserve(Children.size());
1289 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1290 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001291 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001292 }
1293 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001294 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001295 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001296 New->setTransformFn(getTransformFn());
1297 return New;
1298}
1299
Chris Lattner53c39ba2010-02-14 22:22:58 +00001300/// RemoveAllTypes - Recursively strip all the types of this tree.
1301void TreePatternNode::RemoveAllTypes() {
Chris Lattnerf1447252010-03-19 21:37:09 +00001302 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1303 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner53c39ba2010-02-14 22:22:58 +00001304 if (isLeaf()) return;
1305 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1306 getChild(i)->RemoveAllTypes();
1307}
1308
1309
Chris Lattner8cab0212008-01-05 22:25:12 +00001310/// SubstituteFormalArguments - Replace the formal arguments in this tree
1311/// with actual values specified by ArgMap.
1312void TreePatternNode::
1313SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1314 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001315
Chris Lattner8cab0212008-01-05 22:25:12 +00001316 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1317 TreePatternNode *Child = getChild(i);
1318 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001319 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001320 // Note that, when substituting into an output pattern, Val might be an
1321 // UnsetInit.
1322 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1323 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001324 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001325 TreePatternNode *NewChild = ArgMap[Child->getName()];
1326 assert(NewChild && "Couldn't find formal argument!");
1327 assert((Child->getPredicateFns().empty() ||
1328 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1329 "Non-empty child predicate clobbered!");
1330 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001331 }
1332 } else {
1333 getChild(i)->SubstituteFormalArguments(ArgMap);
1334 }
1335 }
1336}
1337
1338
1339/// InlinePatternFragments - If this pattern refers to any pattern
1340/// fragments, inline them into place, giving us a pattern without any
1341/// PatFrag references.
1342TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001343 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001344 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001345
1346 if (isLeaf())
1347 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001348 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001349
Chris Lattner8cab0212008-01-05 22:25:12 +00001350 if (!Op->isSubClassOf("PatFrag")) {
1351 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001352 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1353 TreePatternNode *Child = getChild(i);
1354 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1355
1356 assert((Child->getPredicateFns().empty() ||
1357 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1358 "Non-empty child predicate clobbered!");
1359
1360 setChild(i, NewChild);
1361 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001362 return this;
1363 }
1364
1365 // Otherwise, we found a reference to a fragment. First, look up its
1366 // TreePattern record.
1367 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001368
Chris Lattner8cab0212008-01-05 22:25:12 +00001369 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001370 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001371 TP.error("'" + Op->getName() + "' fragment requires " +
1372 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001373 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001374 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001375
1376 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1377
Chris Lattner514e2922011-04-17 21:38:24 +00001378 TreePredicateFn PredFn(Frag);
1379 if (!PredFn.isAlwaysTrue())
1380 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001381
Chris Lattner8cab0212008-01-05 22:25:12 +00001382 // Resolve formal arguments to their actual value.
1383 if (Frag->getNumArgs()) {
1384 // Compute the map of formal to actual arguments.
1385 std::map<std::string, TreePatternNode*> ArgMap;
1386 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1387 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001388
Chris Lattner8cab0212008-01-05 22:25:12 +00001389 FragTree->SubstituteFormalArguments(ArgMap);
1390 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001391
Chris Lattner8cab0212008-01-05 22:25:12 +00001392 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001393 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1394 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001395
1396 // Transfer in the old predicates.
1397 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1398 FragTree->addPredicateFn(getPredicateFns()[i]);
1399
Chris Lattner8cab0212008-01-05 22:25:12 +00001400 // Get a new copy of this fragment to stitch into here.
1401 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001402
Chris Lattner2e253b42008-06-30 03:02:03 +00001403 // The fragment we inlined could have recursive inlining that is needed. See
1404 // if there are any pattern fragments in it and inline them as needed.
1405 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001406}
1407
1408/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001409/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001410/// references from the register file information, for example.
1411///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001412/// When Unnamed is set, return the type of a DAG operand with no name, such as
1413/// the F8RC register class argument in:
1414///
1415/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1416///
1417/// When Unnamed is false, return the type of a named DAG operand such as the
1418/// GPR:$src operand above.
1419///
Chris Lattnerf1447252010-03-19 21:37:09 +00001420static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001421 bool NotRegisters,
1422 bool Unnamed,
1423 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001424 // Check to see if this is a register operand.
1425 if (R->isSubClassOf("RegisterOperand")) {
1426 assert(ResNo == 0 && "Regoperand ref only has one result!");
1427 if (NotRegisters)
1428 return EEVT::TypeSet(); // Unknown.
1429 Record *RegClass = R->getValueAsDef("RegClass");
1430 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1431 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1432 }
1433
Chris Lattnercabe0372010-03-15 06:00:16 +00001434 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001435 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001436 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001437 // An unnamed register class represents itself as an i32 immediate, for
1438 // example on a COPY_TO_REGCLASS instruction.
1439 if (Unnamed)
1440 return EEVT::TypeSet(MVT::i32, TP);
1441
1442 // In a named operand, the register class provides the possible set of
1443 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001444 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001445 return EEVT::TypeSet(); // Unknown.
1446 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1447 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001448 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001449
Chris Lattner6070ee22010-03-23 23:50:31 +00001450 if (R->isSubClassOf("PatFrag")) {
1451 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001452 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001453 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001454 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001455
Chris Lattner6070ee22010-03-23 23:50:31 +00001456 if (R->isSubClassOf("Register")) {
1457 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001458 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001459 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001460 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001461 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001462 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001463
1464 if (R->isSubClassOf("SubRegIndex")) {
1465 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001466 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001467 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001468
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001469 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001470 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001471 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1472 //
1473 // (sext_inreg GPR:$src, i16)
1474 // ~~~
1475 if (Unnamed)
1476 return EEVT::TypeSet(MVT::Other, TP);
1477 // With a name, the ValueType simply provides the type of the named
1478 // variable.
1479 //
1480 // (sext_inreg i32:$src, i16)
1481 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001482 if (NotRegisters)
1483 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001484 return EEVT::TypeSet(getValueType(R), TP);
1485 }
1486
1487 if (R->isSubClassOf("CondCode")) {
1488 assert(ResNo == 0 && "This node only has one result!");
1489 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001490 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001491 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001492
Chris Lattner6070ee22010-03-23 23:50:31 +00001493 if (R->isSubClassOf("ComplexPattern")) {
1494 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001495 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001496 return EEVT::TypeSet(); // Unknown.
1497 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1498 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001499 }
1500 if (R->isSubClassOf("PointerLikeRegClass")) {
1501 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001502 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001503 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001504
Chris Lattner6070ee22010-03-23 23:50:31 +00001505 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1506 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001507 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001508 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001509 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001510
Tim Northoverc807a172014-05-20 11:52:46 +00001511 if (R->isSubClassOf("Operand"))
1512 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1513
Chris Lattner8cab0212008-01-05 22:25:12 +00001514 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001515 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001516}
1517
Chris Lattner89c65662008-01-06 05:36:50 +00001518
1519/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1520/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1521const CodeGenIntrinsic *TreePatternNode::
1522getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1523 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1524 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1525 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001526 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001527
Sean Silva88eb8dd2012-10-10 20:24:47 +00001528 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001529 return &CDP.getIntrinsicInfo(IID);
1530}
1531
Chris Lattner53c39ba2010-02-14 22:22:58 +00001532/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1533/// return the ComplexPattern information, otherwise return null.
1534const ComplexPattern *
1535TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001536 Record *Rec;
1537 if (isLeaf()) {
1538 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1539 if (!DI)
1540 return nullptr;
1541 Rec = DI->getDef();
1542 } else
1543 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001544
Tim Northoverc807a172014-05-20 11:52:46 +00001545 if (!Rec->isSubClassOf("ComplexPattern"))
1546 return nullptr;
1547 return &CGP.getComplexPattern(Rec);
1548}
1549
1550unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1551 // A ComplexPattern specifically declares how many results it fills in.
1552 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1553 return CP->getNumOperands();
1554
1555 // If MIOperandInfo is specified, that gives the count.
1556 if (isLeaf()) {
1557 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1558 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1559 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1560 if (MIOps->getNumArgs())
1561 return MIOps->getNumArgs();
1562 }
1563 }
1564
1565 // Otherwise there is just one result.
1566 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001567}
1568
1569/// NodeHasProperty - Return true if this node has the specified property.
1570bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001571 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001572 if (isLeaf()) {
1573 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1574 return CP->hasProperty(Property);
1575 return false;
1576 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001577
Chris Lattner53c39ba2010-02-14 22:22:58 +00001578 Record *Operator = getOperator();
1579 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001580
Chris Lattner53c39ba2010-02-14 22:22:58 +00001581 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1582}
1583
1584
1585
1586
1587/// TreeHasProperty - Return true if any node in this tree has the specified
1588/// property.
1589bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001590 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001591 if (NodeHasProperty(Property, CGP))
1592 return true;
1593 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1594 if (getChild(i)->TreeHasProperty(Property, CGP))
1595 return true;
1596 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001597}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001598
Evan Cheng49bad4c2008-06-16 20:29:38 +00001599/// isCommutativeIntrinsic - Return true if the node corresponds to a
1600/// commutative intrinsic.
1601bool
1602TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1603 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1604 return Int->isCommutative;
1605 return false;
1606}
1607
Matt Arsenaulteb492162014-11-02 23:46:51 +00001608static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1609 if (!N->isLeaf())
1610 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001611
Matt Arsenaulteb492162014-11-02 23:46:51 +00001612 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1613 if (DI && DI->getDef()->isSubClassOf(Class))
1614 return true;
1615
1616 return false;
1617}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001618
1619static void emitTooManyOperandsError(TreePattern &TP,
1620 StringRef InstName,
1621 unsigned Expected,
1622 unsigned Actual) {
1623 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1624 " operands but expected only " + Twine(Expected) + "!");
1625}
1626
1627static void emitTooFewOperandsError(TreePattern &TP,
1628 StringRef InstName,
1629 unsigned Actual) {
1630 TP.error("Instruction '" + InstName +
1631 "' expects more than the provided " + Twine(Actual) + " operands!");
1632}
1633
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001634/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001635/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001636/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001637bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001638 if (TP.hasError())
1639 return false;
1640
Chris Lattnerab3242f2008-01-06 01:10:31 +00001641 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001642 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001643 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001644 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001645 bool MadeChange = false;
1646 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1647 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001648 NotRegisters,
1649 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001650 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001651 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001652
Sean Silvafb509ed2012-10-10 20:24:43 +00001653 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001654 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001655
Chris Lattnerf1447252010-03-19 21:37:09 +00001656 // Int inits are always integers. :)
1657 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001658
Chris Lattnerf1447252010-03-19 21:37:09 +00001659 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001660 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001661
Chris Lattnerf1447252010-03-19 21:37:09 +00001662 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001663 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1664 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001665
Craig Topper95198f42013-09-25 06:37:18 +00001666 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001667 // Make sure that the value is representable for this type.
1668 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001669
Richard Smith228e6d42012-08-24 23:29:28 +00001670 // Check that the value doesn't use more bits than we have. It must either
1671 // be a sign- or zero-extended equivalent of the original.
1672 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1673 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001674 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001675
Richard Smith228e6d42012-08-24 23:29:28 +00001676 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001677 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001678 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001679 }
1680 return false;
1681 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001682
Chris Lattner8cab0212008-01-05 22:25:12 +00001683 // special handling for set, which isn't really an SDNode.
1684 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001685 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1686 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001687 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001688
Chris Lattnerf1447252010-03-19 21:37:09 +00001689 TreePatternNode *SetVal = getChild(NC-1);
1690 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1691
Elena Demikhovsky09954792015-03-01 08:23:41 +00001692 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001693 TreePatternNode *Child = getChild(i);
1694 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001695
Chris Lattner8cab0212008-01-05 22:25:12 +00001696 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001697 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1698 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001699 }
1700 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001701 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001702
Chris Lattner5c2182e2010-03-27 02:53:27 +00001703 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001704 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1705
Chris Lattner8cab0212008-01-05 22:25:12 +00001706 bool MadeChange = false;
1707 for (unsigned i = 0; i < getNumChildren(); ++i)
1708 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001709 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001710 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001711
Chris Lattneree820ac2010-02-23 05:51:07 +00001712 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001713 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001714
Chris Lattner8cab0212008-01-05 22:25:12 +00001715 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001716 unsigned NumRetVTs = Int->IS.RetVTs.size();
1717 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001718
Bill Wendling91821472008-11-13 09:08:33 +00001719 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001720 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001721
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001722 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001723 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001724 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001725 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001726 return false;
1727 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001728
1729 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001730 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001731
Chris Lattnerf1447252010-03-19 21:37:09 +00001732 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1733 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001734
Chris Lattnerf1447252010-03-19 21:37:09 +00001735 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1736 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1737 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001738 }
1739 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001740 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001741
Chris Lattneree820ac2010-02-23 05:51:07 +00001742 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001743 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001744
Chris Lattner135091b2010-03-28 08:48:47 +00001745 // Check that the number of operands is sane. Negative operands -> varargs.
1746 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001747 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001748 TP.error(getOperator()->getName() + " node requires exactly " +
1749 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001750 return false;
1751 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001752
Chris Lattner8cab0212008-01-05 22:25:12 +00001753 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1754 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1755 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001756 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001757 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001758
Chris Lattneree820ac2010-02-23 05:51:07 +00001759 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001760 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001761 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001762 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001763
Chris Lattnerd44966f2010-03-27 19:15:02 +00001764 bool MadeChange = false;
1765
1766 // Apply the result types to the node, these come from the things in the
1767 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001768 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1769 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001770 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1771 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001772
Chris Lattnerd44966f2010-03-27 19:15:02 +00001773 // If the instruction has implicit defs, we apply the first one as a result.
1774 // FIXME: This sucks, it should apply all implicit defs.
1775 if (!InstInfo.ImplicitDefs.empty()) {
1776 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001777
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001778 // FIXME: Generalize to multiple possible types and multiple possible
1779 // ImplicitDefs.
1780 MVT::SimpleValueType VT =
1781 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001782
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001783 if (VT != MVT::Other)
1784 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001785 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001786
Chris Lattnercabe0372010-03-15 06:00:16 +00001787 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1788 // be the same.
1789 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001790 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1791 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1792 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001793 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1794 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1795 // variadic.
1796
1797 unsigned NChild = getNumChildren();
1798 if (NChild < 3) {
1799 TP.error("REG_SEQUENCE requires at least 3 operands!");
1800 return false;
1801 }
1802
1803 if (NChild % 2 == 0) {
1804 TP.error("REG_SEQUENCE requires an odd number of operands!");
1805 return false;
1806 }
1807
1808 if (!isOperandClass(getChild(0), "RegisterClass")) {
1809 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1810 return false;
1811 }
1812
1813 for (unsigned I = 1; I < NChild; I += 2) {
1814 TreePatternNode *SubIdxChild = getChild(I + 1);
1815 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1816 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1817 itostr(I + 1) + "!");
1818 return false;
1819 }
1820 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001821 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001822
1823 unsigned ChildNo = 0;
1824 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1825 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001826
Chris Lattner8cab0212008-01-05 22:25:12 +00001827 // If the instruction expects a predicate or optional def operand, we
1828 // codegen this by setting the operand to it's default value if it has a
1829 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001830 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001831 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1832 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001833
Chris Lattner8cab0212008-01-05 22:25:12 +00001834 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001835 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001836 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001837 return false;
1838 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001839
Chris Lattner8cab0212008-01-05 22:25:12 +00001840 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001841 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001842
1843 // If the operand has sub-operands, they may be provided by distinct
1844 // child patterns, so attempt to match each sub-operand separately.
1845 if (OperandNode->isSubClassOf("Operand")) {
1846 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1847 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1848 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001849 // a single ComplexPattern-related Operand.
1850
1851 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001852 // Match first sub-operand against the child we already have.
1853 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1854 MadeChange |=
1855 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1856
1857 // And the remaining sub-operands against subsequent children.
1858 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1859 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001860 emitTooFewOperandsError(TP, getOperator()->getName(),
1861 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001862 return false;
1863 }
1864 Child = getChild(ChildNo++);
1865
1866 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1867 MadeChange |=
1868 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1869 }
1870 continue;
1871 }
1872 }
1873 }
1874
1875 // If we didn't match by pieces above, attempt to match the whole
1876 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001877 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001878 }
Christopher Lamba7312392008-03-11 09:33:47 +00001879
Matt Arsenaulteb492162014-11-02 23:46:51 +00001880 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001881 emitTooManyOperandsError(TP, getOperator()->getName(),
1882 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001883 return false;
1884 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001885
Ulrich Weigande618abd2013-03-19 19:51:09 +00001886 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1887 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001888 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001889 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001890
Tim Northoverc807a172014-05-20 11:52:46 +00001891 if (getOperator()->isSubClassOf("ComplexPattern")) {
1892 bool MadeChange = false;
1893
1894 for (unsigned i = 0; i < getNumChildren(); ++i)
1895 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1896
1897 return MadeChange;
1898 }
1899
Chris Lattneree820ac2010-02-23 05:51:07 +00001900 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001901
Chris Lattneree820ac2010-02-23 05:51:07 +00001902 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001903 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001904 TP.error("Node transform '" + getOperator()->getName() +
1905 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001906 return false;
1907 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001908
Chris Lattnercabe0372010-03-15 06:00:16 +00001909 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1910
Jim Grosbach65586fe2010-12-21 16:16:00 +00001911
Chris Lattneree820ac2010-02-23 05:51:07 +00001912 // If either the output or input of the xform does not have exact
1913 // type info. We assume they must be the same. Otherwise, it is perfectly
1914 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001915#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001916 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001917 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1918 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001919 return MadeChange;
1920 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001921#endif
1922 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001923}
1924
1925/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1926/// RHS of a commutative operation, not the on LHS.
1927static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1928 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1929 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001930 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001931 return true;
1932 return false;
1933}
1934
1935
1936/// canPatternMatch - If it is impossible for this pattern to match on this
1937/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001938/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001939/// that can never possibly work), and to prevent the pattern permuter from
1940/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001941bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001942 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001943 if (isLeaf()) return true;
1944
1945 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1946 if (!getChild(i)->canPatternMatch(Reason, CDP))
1947 return false;
1948
1949 // If this is an intrinsic, handle cases that would make it not match. For
1950 // example, if an operand is required to be an immediate.
1951 if (getOperator()->isSubClassOf("Intrinsic")) {
1952 // TODO:
1953 return true;
1954 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001955
Tim Northoverc807a172014-05-20 11:52:46 +00001956 if (getOperator()->isSubClassOf("ComplexPattern"))
1957 return true;
1958
Chris Lattner8cab0212008-01-05 22:25:12 +00001959 // If this node is a commutative operator, check that the LHS isn't an
1960 // immediate.
1961 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001962 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1963 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001964 // Scan all of the operands of the node and make sure that only the last one
1965 // is a constant node, unless the RHS also is.
1966 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001967 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1968 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001969 if (OnlyOnRHSOfCommutative(getChild(i))) {
1970 Reason="Immediate value must be on the RHS of commutative operators!";
1971 return false;
1972 }
1973 }
1974 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001975
Chris Lattner8cab0212008-01-05 22:25:12 +00001976 return true;
1977}
1978
1979//===----------------------------------------------------------------------===//
1980// TreePattern implementation
1981//
1982
David Greeneaf8ee2c2011-07-29 22:43:06 +00001983TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001984 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1985 isInputPattern(isInput), HasError(false) {
Craig Topperef0578a2015-06-02 04:15:51 +00001986 for (Init *I : RawPat->getValues())
1987 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001988}
1989
David Greeneaf8ee2c2011-07-29 22:43:06 +00001990TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001991 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1992 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001993 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001994}
1995
David Blaikiecf195302014-11-17 22:55:41 +00001996TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001997 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1998 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00001999 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002000}
2001
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002002void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002003 if (HasError)
2004 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002005 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002006 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2007 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002008}
2009
Chris Lattnercabe0372010-03-15 06:00:16 +00002010void TreePattern::ComputeNamedNodes() {
2011 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002012 ComputeNamedNodes(Trees[i]);
Chris Lattnercabe0372010-03-15 06:00:16 +00002013}
2014
2015void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2016 if (!N->getName().empty())
2017 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002018
Chris Lattnercabe0372010-03-15 06:00:16 +00002019 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2020 ComputeNamedNodes(N->getChild(i));
2021}
2022
David Blaikiecf195302014-11-17 22:55:41 +00002023
2024TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002025 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002026 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002027
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002028 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002029 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002030 /// (foo GPR, imm) -> (foo GPR, (imm))
2031 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002032 return ParseTreePattern(
2033 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002034 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002035 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002036
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002037 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002038 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002039 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002040 if (OpName.empty())
2041 error("'node' argument requires a name to match with operand list");
2042 Args.push_back(OpName);
2043 }
2044
2045 Res->setName(OpName);
2046 return Res;
2047 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002048
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002049 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002050 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002051 if (OpName.empty())
2052 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002053 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002054 Args.push_back(OpName);
2055 Res->setName(OpName);
2056 return Res;
2057 }
2058
Sean Silvafb509ed2012-10-10 20:24:43 +00002059 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002060 if (!OpName.empty())
2061 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002062 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002063 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002064
Sean Silvafb509ed2012-10-10 20:24:43 +00002065 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002066 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002067 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002068 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002069 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002070 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002071 }
2072
Sean Silvafb509ed2012-10-10 20:24:43 +00002073 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002074 if (!Dag) {
2075 TheInit->dump();
2076 error("Pattern has unexpected init kind!");
2077 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002078 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002079 if (!OpDef) error("Pattern has unexpected operator type!");
2080 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002081
Chris Lattner8cab0212008-01-05 22:25:12 +00002082 if (Operator->isSubClassOf("ValueType")) {
2083 // If the operator is a ValueType, then this must be "type cast" of a leaf
2084 // node.
2085 if (Dag->getNumArgs() != 1)
2086 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002087
David Blaikiecf195302014-11-17 22:55:41 +00002088 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002089
Chris Lattner8cab0212008-01-05 22:25:12 +00002090 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002091 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2092 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002093
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002094 if (!OpName.empty())
2095 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002096 return New;
2097 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002098
Chris Lattner8cab0212008-01-05 22:25:12 +00002099 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002100 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002101 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002102 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002103 !Operator->isSubClassOf("SDNodeXForm") &&
2104 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002105 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002106 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002107 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002108 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002109
Chris Lattner8cab0212008-01-05 22:25:12 +00002110 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002111 if (isInputPattern) {
2112 if (Operator->isSubClassOf("Instruction") ||
2113 Operator->isSubClassOf("SDNodeXForm"))
2114 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2115 } else {
2116 if (Operator->isSubClassOf("Intrinsic"))
2117 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002118
Chris Lattner2e9eae12010-03-28 06:57:56 +00002119 if (Operator->isSubClassOf("SDNode") &&
2120 Operator->getName() != "imm" &&
2121 Operator->getName() != "fpimm" &&
2122 Operator->getName() != "tglobaltlsaddr" &&
2123 Operator->getName() != "tconstpool" &&
2124 Operator->getName() != "tjumptable" &&
2125 Operator->getName() != "tframeindex" &&
2126 Operator->getName() != "texternalsym" &&
2127 Operator->getName() != "tblockaddress" &&
2128 Operator->getName() != "tglobaladdr" &&
2129 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002130 Operator->getName() != "vt" &&
2131 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002132 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2133 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002134
Chris Lattner8cab0212008-01-05 22:25:12 +00002135 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002136
2137 // Parse all the operands.
2138 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002139 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002140
Chris Lattner8cab0212008-01-05 22:25:12 +00002141 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002142 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002143 // convert the intrinsic name to a number.
2144 if (Operator->isSubClassOf("Intrinsic")) {
2145 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2146 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2147
2148 // If this intrinsic returns void, it must have side-effects and thus a
2149 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002150 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002151 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002152 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002153 // Has side-effects, requires chain.
2154 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002155 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002156 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002157
David Greenee32ebf22011-07-29 19:07:07 +00002158 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002159 Children.insert(Children.begin(), IIDNode);
2160 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002161
Tim Northoverc807a172014-05-20 11:52:46 +00002162 if (Operator->isSubClassOf("ComplexPattern")) {
2163 for (unsigned i = 0; i < Children.size(); ++i) {
2164 TreePatternNode *Child = Children[i];
2165
2166 if (Child->getName().empty())
2167 error("All arguments to a ComplexPattern must be named");
2168
2169 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2170 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2171 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2172 auto OperandId = std::make_pair(Operator, i);
2173 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2174 if (PrevOp != ComplexPatternOperands.end()) {
2175 if (PrevOp->getValue() != OperandId)
2176 error("All ComplexPattern operands must appear consistently: "
2177 "in the same order in just one ComplexPattern instance.");
2178 } else
2179 ComplexPatternOperands[Child->getName()] = OperandId;
2180 }
2181 }
2182
Chris Lattnerf1447252010-03-19 21:37:09 +00002183 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002184 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002185 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002186
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002187 if (!Dag->getName().empty()) {
2188 assert(Result->getName().empty());
2189 Result->setName(Dag->getName());
2190 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002191 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002192}
2193
Chris Lattnera787c9e2010-03-28 08:38:32 +00002194/// SimplifyTree - See if we can simplify this tree to eliminate something that
2195/// will never match in favor of something obvious that will. This is here
2196/// strictly as a convenience to target authors because it allows them to write
2197/// more type generic things and have useless type casts fold away.
2198///
2199/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002200static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002201 if (N->isLeaf())
2202 return false;
2203
2204 // If we have a bitconvert with a resolved type and if the source and
2205 // destination types are the same, then the bitconvert is useless, remove it.
2206 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002207 N->getExtType(0).isConcrete() &&
2208 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2209 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002210 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002211 SimplifyTree(N);
2212 return true;
2213 }
2214
2215 // Walk all children.
2216 bool MadeChange = false;
2217 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002218 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002219 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002220 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002221 }
2222 return MadeChange;
2223}
2224
2225
2226
Chris Lattner8cab0212008-01-05 22:25:12 +00002227/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002228/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002229/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002230bool TreePattern::
2231InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2232 if (NamedNodes.empty())
2233 ComputeNamedNodes();
2234
Chris Lattner8cab0212008-01-05 22:25:12 +00002235 bool MadeChange = true;
2236 while (MadeChange) {
2237 MadeChange = false;
Chris Lattnera787c9e2010-03-28 08:38:32 +00002238 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002239 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002240 MadeChange |= SimplifyTree(Trees[i]);
2241 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002242
2243 // If there are constraints on our named nodes, apply them.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002244 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattnercabe0372010-03-15 06:00:16 +00002245 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2246 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002247
Chris Lattnercabe0372010-03-15 06:00:16 +00002248 // If we have input named node types, propagate their types to the named
2249 // values here.
2250 if (InNamedTypes) {
Jim Grosbach37b80932014-07-09 18:55:49 +00002251 if (!InNamedTypes->count(I->getKey())) {
2252 error("Node '" + std::string(I->getKey()) +
2253 "' in output pattern but not input pattern");
2254 return true;
2255 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002256
2257 const SmallVectorImpl<TreePatternNode*> &InNodes =
2258 InNamedTypes->find(I->getKey())->second;
2259
2260 // The input types should be fully resolved by now.
2261 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2262 // If this node is a register class, and it is the root of the pattern
2263 // then we're mapping something onto an input register. We allow
2264 // changing the type of the input register in this case. This allows
2265 // us to match things like:
2266 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
David Blaikiecf195302014-11-17 22:55:41 +00002267 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002268 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002269 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2270 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002271 continue;
2272 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002273
Daniel Dunbard177edf2010-03-21 01:38:21 +00002274 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002275 InNodes[0]->getNumTypes() == 1 &&
2276 "FIXME: cannot name multiple result nodes yet");
2277 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2278 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002279 }
2280 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002281
Chris Lattnercabe0372010-03-15 06:00:16 +00002282 // If there are multiple nodes with the same name, they must all have the
2283 // same type.
2284 if (I->second.size() > 1) {
2285 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002286 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002287 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002288 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002289
Chris Lattnerf1447252010-03-19 21:37:09 +00002290 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2291 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002292 }
2293 }
2294 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002295 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002296
Chris Lattner8cab0212008-01-05 22:25:12 +00002297 bool HasUnresolvedTypes = false;
2298 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2299 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2300 return !HasUnresolvedTypes;
2301}
2302
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002303void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002304 OS << getRecord()->getName();
2305 if (!Args.empty()) {
2306 OS << "(" << Args[0];
2307 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2308 OS << ", " << Args[i];
2309 OS << ")";
2310 }
2311 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002312
Chris Lattner8cab0212008-01-05 22:25:12 +00002313 if (Trees.size() > 1)
2314 OS << "[\n";
2315 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2316 OS << "\t";
2317 Trees[i]->print(OS);
2318 OS << "\n";
2319 }
2320
2321 if (Trees.size() > 1)
2322 OS << "]\n";
2323}
2324
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002325void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002326
2327//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002328// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002329//
2330
Jim Grosbach65586fe2010-12-21 16:16:00 +00002331CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002332 Records(R), Target(R) {
2333
Dale Johannesenb842d522009-02-05 01:49:45 +00002334 Intrinsics = LoadIntrinsics(Records, false);
2335 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002336 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002337 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002338 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002339 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002340 ParseDefaultOperands();
2341 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002342 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002343 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002344
Chris Lattner8cab0212008-01-05 22:25:12 +00002345 // Generate variants. For example, commutative patterns can match
2346 // multiple ways. Add them to PatternsToMatch as well.
2347 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002348
2349 // Infer instruction flags. For example, we can detect loads,
2350 // stores, and side effects in many cases by examining an
2351 // instruction's pattern.
2352 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002353
2354 // Verify that instruction flags match the patterns.
2355 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002356}
2357
Chris Lattnerab3242f2008-01-06 01:10:31 +00002358Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002359 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002360 if (!N || !N->isSubClassOf("SDNode"))
2361 PrintFatalError("Error getting SDNode '" + Name + "'!");
2362
Chris Lattner8cab0212008-01-05 22:25:12 +00002363 return N;
2364}
2365
2366// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002367void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002368 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2369 while (!Nodes.empty()) {
2370 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2371 Nodes.pop_back();
2372 }
2373
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002374 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002375 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2376 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2377 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2378}
2379
2380/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2381/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002382void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002383 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2384 while (!Xforms.empty()) {
2385 Record *XFormNode = Xforms.back();
2386 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002387 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002388 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002389
2390 Xforms.pop_back();
2391 }
2392}
2393
Chris Lattnerab3242f2008-01-06 01:10:31 +00002394void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002395 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2396 while (!AMs.empty()) {
2397 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2398 AMs.pop_back();
2399 }
2400}
2401
2402
2403/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2404/// file, building up the PatternFragments map. After we've collected them all,
2405/// inline fragments together as necessary, so that there are no references left
2406/// inside a pattern fragment to a pattern fragment.
2407///
Hal Finkel2756dc12014-02-28 00:26:56 +00002408void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002409 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002410
Chris Lattnere7170df2008-01-05 22:43:57 +00002411 // First step, parse all of the fragments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002412 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002413 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2414 continue;
2415
David Greeneaf8ee2c2011-07-29 22:43:06 +00002416 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002417 TreePattern *P =
David Blaikie3c6ca232014-11-13 21:40:02 +00002418 (PatternFragments[Fragments[i]] = llvm::make_unique<TreePattern>(
2419 Fragments[i], Tree, !Fragments[i]->isSubClassOf("OutPatFrag"),
2420 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002421
Chris Lattnere7170df2008-01-05 22:43:57 +00002422 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002423 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002424 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002425
Chris Lattnere7170df2008-01-05 22:43:57 +00002426 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002427 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002428
Chris Lattner8cab0212008-01-05 22:25:12 +00002429 // Parse the operands list.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002430 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002431 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002432 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002433 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002434 if (!OpsOp ||
2435 (OpsOp->getDef()->getName() != "ops" &&
2436 OpsOp->getDef()->getName() != "outs" &&
2437 OpsOp->getDef()->getName() != "ins"))
2438 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002439
2440 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002441 Args.clear();
2442 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002443 if (!isa<DefInit>(OpsList->getArg(j)) ||
2444 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002445 P->error("Operands list should all be 'node' values.");
2446 if (OpsList->getArgName(j).empty())
2447 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002448 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002449 P->error("'" + OpsList->getArgName(j) +
2450 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002451 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002452 Args.push_back(OpsList->getArgName(j));
2453 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002454
Chris Lattnere7170df2008-01-05 22:43:57 +00002455 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002456 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002457 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002458
Chris Lattnere7170df2008-01-05 22:43:57 +00002459 // If there is a code init for this fragment, keep track of the fact that
2460 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002461 TreePredicateFn PredFn(P);
2462 if (!PredFn.isAlwaysTrue())
2463 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002464
Chris Lattner8cab0212008-01-05 22:25:12 +00002465 // If there is a node transformation corresponding to this, keep track of
2466 // it.
2467 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2468 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2469 P->getOnlyTree()->setTransformFn(Transform);
2470 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002471
Chris Lattner8cab0212008-01-05 22:25:12 +00002472 // Now that we've parsed all of the tree fragments, do a closure on them so
2473 // that there are not references to PatFrags left inside of them.
Chris Lattner2e253b42008-06-30 03:02:03 +00002474 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002475 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2476 continue;
2477
David Blaikie3c6ca232014-11-13 21:40:02 +00002478 TreePattern &ThePat = *PatternFragments[Fragments[i]];
2479 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002480
Chris Lattner8cab0212008-01-05 22:25:12 +00002481 // Infer as many types as possible. Don't worry about it if we don't infer
2482 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002483 ThePat.InferAllTypes();
2484 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002485
Chris Lattner8cab0212008-01-05 22:25:12 +00002486 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002487 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002488 }
2489}
2490
Chris Lattnerab3242f2008-01-06 01:10:31 +00002491void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002492 std::vector<Record*> DefaultOps;
2493 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002494
2495 // Find some SDNode.
2496 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002497 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002498
Tom Stellardb7246a72012-09-06 14:15:52 +00002499 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2500 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002501
Tom Stellardb7246a72012-09-06 14:15:52 +00002502 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2503 // SomeSDnode so that we can parse this.
2504 std::vector<std::pair<Init*, std::string> > Ops;
2505 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2506 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2507 DefaultInfo->getArgName(op)));
2508 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002509
Tom Stellardb7246a72012-09-06 14:15:52 +00002510 // Create a TreePattern to parse this.
2511 TreePattern P(DefaultOps[i], DI, false, *this);
2512 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002513
Tom Stellardb7246a72012-09-06 14:15:52 +00002514 // Copy the operands over into a DAGDefaultOperand.
2515 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002516
Tom Stellardb7246a72012-09-06 14:15:52 +00002517 TreePatternNode *T = P.getTree(0);
2518 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2519 TreePatternNode *TPN = T->getChild(op);
2520 while (TPN->ApplyTypeConstraints(P, false))
2521 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002522
Tom Stellardb7246a72012-09-06 14:15:52 +00002523 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002524 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2525 DefaultOps[i]->getName() +
2526 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002527 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002528 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002529 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002530
2531 // Insert it into the DefaultOperands map so we can find it later.
2532 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002533 }
2534}
2535
2536/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2537/// instruction input. Return true if this is a real use.
2538static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002539 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002540 // No name -> not interesting.
2541 if (Pat->getName().empty()) {
2542 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002543 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002544 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2545 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002546 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002547 }
2548 return false;
2549 }
2550
2551 Record *Rec;
2552 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002553 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002554 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2555 Rec = DI->getDef();
2556 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002557 Rec = Pat->getOperator();
2558 }
2559
2560 // SRCVALUE nodes are ignored.
2561 if (Rec->getName() == "srcvalue")
2562 return false;
2563
2564 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2565 if (!Slot) {
2566 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002567 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002568 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002569 Record *SlotRec;
2570 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002571 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002572 } else {
2573 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2574 SlotRec = Slot->getOperator();
2575 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002576
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002577 // Ensure that the inputs agree if we've already seen this input.
2578 if (Rec != SlotRec)
2579 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002580 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002581 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002582 return true;
2583}
2584
2585/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2586/// part of "I", the instruction), computing the set of inputs and outputs of
2587/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002588void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002589FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2590 std::map<std::string, TreePatternNode*> &InstInputs,
2591 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002592 std::vector<Record*> &InstImpResults) {
2593 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002594 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002595 if (!isUse && Pat->getTransformFn())
2596 I->error("Cannot specify a transform function for a non-input value!");
2597 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002598 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002599
Chris Lattnerf2d70992010-02-17 06:53:36 +00002600 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002601 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2602 TreePatternNode *Dest = Pat->getChild(i);
2603 if (!Dest->isLeaf())
2604 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002605
Sean Silvafb509ed2012-10-10 20:24:43 +00002606 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002607 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2608 I->error("implicitly defined value should be a register!");
2609 InstImpResults.push_back(Val->getDef());
2610 }
2611 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002612 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002613
Chris Lattnerf2d70992010-02-17 06:53:36 +00002614 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002615 // If this is not a set, verify that the children nodes are not void typed,
2616 // and recurse.
2617 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002618 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002619 I->error("Cannot have void nodes inside of patterns!");
2620 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002621 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002622 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002623
Chris Lattner8cab0212008-01-05 22:25:12 +00002624 // If this is a non-leaf node with no children, treat it basically as if
2625 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002626 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002627
Chris Lattner8cab0212008-01-05 22:25:12 +00002628 if (!isUse && Pat->getTransformFn())
2629 I->error("Cannot specify a transform function for a non-input value!");
2630 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002631 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002632
Chris Lattner8cab0212008-01-05 22:25:12 +00002633 // Otherwise, this is a set, validate and collect instruction results.
2634 if (Pat->getNumChildren() == 0)
2635 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002636
Chris Lattner8cab0212008-01-05 22:25:12 +00002637 if (Pat->getTransformFn())
2638 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002639
Chris Lattner8cab0212008-01-05 22:25:12 +00002640 // Check the set destinations.
2641 unsigned NumDests = Pat->getNumChildren()-1;
2642 for (unsigned i = 0; i != NumDests; ++i) {
2643 TreePatternNode *Dest = Pat->getChild(i);
2644 if (!Dest->isLeaf())
2645 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002646
Sean Silvafb509ed2012-10-10 20:24:43 +00002647 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002648 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002649 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002650 continue;
2651 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002652
2653 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002654 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002655 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002656 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002657 if (Dest->getName().empty())
2658 I->error("set destination must have a name!");
2659 if (InstResults.count(Dest->getName()))
2660 I->error("cannot set '" + Dest->getName() +"' multiple times");
2661 InstResults[Dest->getName()] = Dest;
2662 } else if (Val->getDef()->isSubClassOf("Register")) {
2663 InstImpResults.push_back(Val->getDef());
2664 } else {
2665 I->error("set destination should be a register!");
2666 }
2667 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002668
Chris Lattner8cab0212008-01-05 22:25:12 +00002669 // Verify and collect info from the computation.
2670 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002671 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002672}
2673
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002674//===----------------------------------------------------------------------===//
2675// Instruction Analysis
2676//===----------------------------------------------------------------------===//
2677
2678class InstAnalyzer {
2679 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002680public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002681 bool hasSideEffects;
2682 bool mayStore;
2683 bool mayLoad;
2684 bool isBitcast;
2685 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002686
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002687 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2688 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2689 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002690
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002691 void Analyze(const TreePattern *Pat) {
2692 // Assume only the first tree is the pattern. The others are clobber nodes.
2693 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002694 }
2695
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002696 void Analyze(const PatternToMatch *Pat) {
2697 AnalyzeNode(Pat->getSrcPattern());
2698 }
2699
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002700private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002701 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002702 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002703 return false;
2704
2705 if (N->getNumChildren() != 2)
2706 return false;
2707
2708 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002709 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002710 return false;
2711
2712 const TreePatternNode *N1 = N->getChild(1);
2713 if (N1->isLeaf())
2714 return false;
2715 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2716 return false;
2717
2718 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2719 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2720 return false;
2721 return OpInfo.getEnumName() == "ISD::BITCAST";
2722 }
2723
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002724public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002725 void AnalyzeNode(const TreePatternNode *N) {
2726 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002727 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002728 Record *LeafRec = DI->getDef();
2729 // Handle ComplexPattern leaves.
2730 if (LeafRec->isSubClassOf("ComplexPattern")) {
2731 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2732 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2733 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002734 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002735 }
2736 }
2737 return;
2738 }
2739
2740 // Analyze children.
2741 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2742 AnalyzeNode(N->getChild(i));
2743
2744 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002745 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002746 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002747 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002748 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002749
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002750 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002751 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2752 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2753 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2754 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002755
2756 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2757 // If this is an intrinsic, analyze it.
2758 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2759 mayLoad = true;// These may load memory.
2760
Dan Gohmanddb2d652010-08-05 23:36:21 +00002761 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002762 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2763
Dan Gohmanddb2d652010-08-05 23:36:21 +00002764 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002765 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002766 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002767 }
2768 }
2769
2770};
2771
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002772static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002773 const InstAnalyzer &PatInfo,
2774 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002775 bool Error = false;
2776
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002777 // Remember where InstInfo got its flags.
2778 if (InstInfo.hasUndefFlags())
2779 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002780
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002781 // Check explicitly set flags for consistency.
2782 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2783 !InstInfo.hasSideEffects_Unset) {
2784 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2785 // the pattern has no side effects. That could be useful for div/rem
2786 // instructions that may trap.
2787 if (!InstInfo.hasSideEffects) {
2788 Error = true;
2789 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2790 Twine(InstInfo.hasSideEffects));
2791 }
2792 }
2793
2794 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2795 Error = true;
2796 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2797 Twine(InstInfo.mayStore));
2798 }
2799
2800 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2801 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00002802 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002803 if (!InstInfo.mayLoad) {
2804 Error = true;
2805 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2806 Twine(InstInfo.mayLoad));
2807 }
2808 }
2809
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002810 // Transfer inferred flags.
2811 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2812 InstInfo.mayStore |= PatInfo.mayStore;
2813 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002814
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002815 // These flags are silently added without any verification.
2816 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002817
2818 // Don't infer isVariadic. This flag means something different on SDNodes and
2819 // instructions. For example, a CALL SDNode is variadic because it has the
2820 // call arguments as operands, but a CALL instruction is not variadic - it
2821 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002822
2823 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002824}
2825
Jim Grosbach514410b2012-07-17 00:47:06 +00002826/// hasNullFragReference - Return true if the DAG has any reference to the
2827/// null_frag operator.
2828static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002829 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002830 if (!OpDef) return false;
2831 Record *Operator = OpDef->getDef();
2832
2833 // If this is the null fragment, return true.
2834 if (Operator->getName() == "null_frag") return true;
2835 // If any of the arguments reference the null fragment, return true.
2836 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002837 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002838 if (Arg && hasNullFragReference(Arg))
2839 return true;
2840 }
2841
2842 return false;
2843}
2844
2845/// hasNullFragReference - Return true if any DAG in the list references
2846/// the null_frag operator.
2847static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00002848 for (Init *I : LI->getValues()) {
2849 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00002850 assert(DI && "non-dag in an instruction Pattern list?!");
2851 if (hasNullFragReference(DI))
2852 return true;
2853 }
2854 return false;
2855}
2856
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002857/// Get all the instructions in a tree.
2858static void
2859getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2860 if (Tree->isLeaf())
2861 return;
2862 if (Tree->getOperator()->isSubClassOf("Instruction"))
2863 Instrs.push_back(Tree->getOperator());
2864 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2865 getInstructionsInTree(Tree->getChild(i), Instrs);
2866}
2867
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002868/// Check the class of a pattern leaf node against the instruction operand it
2869/// represents.
2870static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2871 Record *Leaf) {
2872 if (OI.Rec == Leaf)
2873 return true;
2874
2875 // Allow direct value types to be used in instruction set patterns.
2876 // The type will be checked later.
2877 if (Leaf->isSubClassOf("ValueType"))
2878 return true;
2879
2880 // Patterns can also be ComplexPattern instances.
2881 if (Leaf->isSubClassOf("ComplexPattern"))
2882 return true;
2883
2884 return false;
2885}
2886
Ahmed Bougacha14107512013-10-28 18:07:21 +00002887const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2888 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002889
Craig Topper0d1fb902015-03-10 03:25:04 +00002890 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002891
Craig Topper0d1fb902015-03-10 03:25:04 +00002892 // Parse the instruction.
2893 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2894 // Inline pattern fragments into it.
2895 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002896
Craig Topper0d1fb902015-03-10 03:25:04 +00002897 // Infer as many types as possible. If we cannot infer all of them, we can
2898 // never do anything with this instruction pattern: report it to the user.
2899 if (!I->InferAllTypes())
2900 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002901
Craig Topper0d1fb902015-03-10 03:25:04 +00002902 // InstInputs - Keep track of all of the inputs of the instruction, along
2903 // with the record they are declared as.
2904 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002905
Craig Topper0d1fb902015-03-10 03:25:04 +00002906 // InstResults - Keep track of all the virtual registers that are 'set'
2907 // in the instruction, including what reg class they are.
2908 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002909
Craig Topper0d1fb902015-03-10 03:25:04 +00002910 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002911
Craig Topper0d1fb902015-03-10 03:25:04 +00002912 // Verify that the top-level forms in the instruction are of void type, and
2913 // fill in the InstResults map.
2914 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2915 TreePatternNode *Pat = I->getTree(j);
2916 if (Pat->getNumTypes() != 0)
2917 I->error("Top-level forms in instruction pattern should have"
2918 " void types");
Chris Lattner8cab0212008-01-05 22:25:12 +00002919
Craig Topper0d1fb902015-03-10 03:25:04 +00002920 // Find inputs and outputs, and verify the structure of the uses/defs.
2921 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2922 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002923 }
2924
Craig Topper0d1fb902015-03-10 03:25:04 +00002925 // Now that we have inputs and outputs of the pattern, inspect the operands
2926 // list for the instruction. This determines the order that operands are
2927 // added to the machine instruction the node corresponds to.
2928 unsigned NumResults = InstResults.size();
2929
2930 // Parse the operands list from the (ops) list, validating it.
2931 assert(I->getArgList().empty() && "Args list should still be empty here!");
2932
2933 // Check that all of the results occur first in the list.
2934 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00002935 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00002936 for (unsigned i = 0; i != NumResults; ++i) {
2937 if (i == CGI.Operands.size())
2938 I->error("'" + InstResults.begin()->first +
2939 "' set but does not appear in operand list!");
2940 const std::string &OpName = CGI.Operands[i].Name;
2941
2942 // Check that it exists in InstResults.
2943 TreePatternNode *RNode = InstResults[OpName];
2944 if (!RNode)
2945 I->error("Operand $" + OpName + " does not exist in operand list!");
2946
Craig Topper3a8eb892015-03-20 05:09:06 +00002947 ResNodes.push_back(RNode);
2948
Craig Topper0d1fb902015-03-10 03:25:04 +00002949 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2950 if (!R)
2951 I->error("Operand $" + OpName + " should be a set destination: all "
2952 "outputs must occur before inputs in operand list!");
2953
2954 if (!checkOperandClass(CGI.Operands[i], R))
2955 I->error("Operand $" + OpName + " class mismatch!");
2956
2957 // Remember the return type.
2958 Results.push_back(CGI.Operands[i].Rec);
2959
2960 // Okay, this one checks out.
2961 InstResults.erase(OpName);
2962 }
2963
2964 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2965 // the copy while we're checking the inputs.
2966 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2967
2968 std::vector<TreePatternNode*> ResultNodeOperands;
2969 std::vector<Record*> Operands;
2970 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2971 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2972 const std::string &OpName = Op.Name;
2973 if (OpName.empty())
2974 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2975
2976 if (!InstInputsCheck.count(OpName)) {
2977 // If this is an operand with a DefaultOps set filled in, we can ignore
2978 // this. When we codegen it, we will do so as always executed.
2979 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2980 // Does it have a non-empty DefaultOps field? If so, ignore this
2981 // operand.
2982 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2983 continue;
2984 }
2985 I->error("Operand $" + OpName +
2986 " does not appear in the instruction pattern");
2987 }
2988 TreePatternNode *InVal = InstInputsCheck[OpName];
2989 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2990
2991 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2992 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2993 if (!checkOperandClass(Op, InRec))
2994 I->error("Operand $" + OpName + "'s register class disagrees"
2995 " between the operand and pattern");
2996 }
2997 Operands.push_back(Op.Rec);
2998
2999 // Construct the result for the dest-pattern operand list.
3000 TreePatternNode *OpNode = InVal->clone();
3001
3002 // No predicate is useful on the result.
3003 OpNode->clearPredicateFns();
3004
3005 // Promote the xform function to be an explicit node if set.
3006 if (Record *Xform = OpNode->getTransformFn()) {
3007 OpNode->setTransformFn(nullptr);
3008 std::vector<TreePatternNode*> Children;
3009 Children.push_back(OpNode);
3010 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3011 }
3012
3013 ResultNodeOperands.push_back(OpNode);
3014 }
3015
3016 if (!InstInputsCheck.empty())
3017 I->error("Input operand $" + InstInputsCheck.begin()->first +
3018 " occurs in pattern but not in operands list!");
3019
3020 TreePatternNode *ResultPattern =
3021 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3022 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003023 // Copy fully inferred output node types to instruction result pattern.
3024 for (unsigned i = 0; i != NumResults; ++i) {
3025 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3026 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3027 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003028
3029 // Create and insert the instruction.
3030 // FIXME: InstImpResults should not be part of DAGInstruction.
3031 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3032 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3033
3034 // Use a temporary tree pattern to infer all types and make sure that the
3035 // constructed result is correct. This depends on the instruction already
3036 // being inserted into the DAGInsts map.
3037 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3038 Temp.InferAllTypes(&I->getNamedNodesMap());
3039
3040 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3041 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3042
3043 return TheInsertedInst;
3044}
3045
Ahmed Bougacha14107512013-10-28 18:07:21 +00003046/// ParseInstructions - Parse all of the instructions, inlining and resolving
3047/// any fragments involved. This populates the Instructions list with fully
3048/// resolved instructions.
3049void CodeGenDAGPatterns::ParseInstructions() {
3050 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3051
3052 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Craig Topper24064772014-04-15 07:20:03 +00003053 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003054
3055 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
3056 LI = Instrs[i]->getValueAsListInit("Pattern");
3057
3058 // If there is no pattern, only collect minimal information about the
3059 // instruction for its operand list. We have to assume that there is one
3060 // result, as we have no detailed info. A pattern which references the
3061 // null_frag operator is as-if no pattern were specified. Normally this
3062 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3063 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003064 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003065 std::vector<Record*> Results;
3066 std::vector<Record*> Operands;
3067
3068 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3069
3070 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003071 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3072 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003073
Craig Topper3a8eb892015-03-20 05:09:06 +00003074 // The rest are inputs.
3075 for (unsigned j = InstInfo.Operands.NumDefs,
3076 e = InstInfo.Operands.size(); j < e; ++j)
3077 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003078 }
3079
3080 // Create and insert the instruction.
3081 std::vector<Record*> ImpResults;
3082 Instructions.insert(std::make_pair(Instrs[i],
Craig Topper24064772014-04-15 07:20:03 +00003083 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003084 continue; // no pattern.
3085 }
3086
3087 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
3088 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3089
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003090 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003091 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003092 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003093
Chris Lattner8cab0212008-01-05 22:25:12 +00003094 // If we can, convert the instructions to be patterns that are matched!
Sean Silvaa4e2c5f2012-09-19 01:47:00 +00003095 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
Benjamin Kramerc2dbd5d2009-08-23 10:39:21 +00003096 Instructions.begin(),
Chris Lattner8cab0212008-01-05 22:25:12 +00003097 E = Instructions.end(); II != E; ++II) {
3098 DAGInstruction &TheInst = II->second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003099 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003100 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003101
3102 // FIXME: Assume only the first tree is the pattern. The others are clobber
3103 // nodes.
3104 TreePatternNode *Pattern = I->getTree(0);
3105 TreePatternNode *SrcPattern;
3106 if (Pattern->getOperator()->getName() == "set") {
3107 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3108 } else{
3109 // Not a set (store or something?)
3110 SrcPattern = Pattern;
3111 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003112
Chris Lattner8cab0212008-01-05 22:25:12 +00003113 Record *Instr = II->first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003114 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003115 PatternToMatch(Instr,
3116 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003117 SrcPattern,
3118 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003119 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003120 Instr->getValueAsInt("AddedComplexity"),
3121 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003122 }
3123}
3124
Chris Lattnera7722b62010-02-23 06:55:24 +00003125
3126typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3127
Jim Grosbach65586fe2010-12-21 16:16:00 +00003128static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003129 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003130 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003131 if (!P->getName().empty()) {
3132 NameRecord &Rec = Names[P->getName()];
3133 // If this is the first instance of the name, remember the node.
3134 if (Rec.second++ == 0)
3135 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003136 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003137 PatternTop->error("repetition of value: $" + P->getName() +
3138 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003139 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003140
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003141 if (!P->isLeaf()) {
3142 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003143 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003144 }
3145}
3146
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003147void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003148 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003149 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003150 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003151 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3152 PrintWarning(Pattern->getRecord()->getLoc(),
3153 Twine("Pattern can never match: ") + Reason);
3154 return;
3155 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003156
Chris Lattner1e634e32010-03-01 22:29:19 +00003157 // If the source pattern's root is a complex pattern, that complex pattern
3158 // must specify the nodes it can potentially match.
3159 if (const ComplexPattern *CP =
3160 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3161 if (CP->getRootNodes().empty())
3162 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3163 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003164
3165
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003166 // Find all of the named values in the input and output, ensure they have the
3167 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003168 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003169 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3170 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003171
3172 // Scan all of the named values in the destination pattern, rejecting them if
3173 // they don't exist in the input pattern.
Chris Lattnera7722b62010-02-23 06:55:24 +00003174 for (std::map<std::string, NameRecord>::iterator
Chris Lattner4b9225b2010-02-23 07:50:58 +00003175 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Craig Topper24064772014-04-15 07:20:03 +00003176 if (SrcNames[I->first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003177 Pattern->error("Pattern has input without matching name in output: $" +
3178 I->first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003179 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003180
Chris Lattnera7722b62010-02-23 06:55:24 +00003181 // Scan all of the named values in the source pattern, rejecting them if the
3182 // name isn't used in the dest, and isn't used to tie two values together.
3183 for (std::map<std::string, NameRecord>::iterator
3184 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
Craig Topper24064772014-04-15 07:20:03 +00003185 if (DstNames[I->first].first == nullptr && SrcNames[I->first].second == 1)
Chris Lattnera7722b62010-02-23 06:55:24 +00003186 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003187
Chris Lattner0c0baa92010-02-23 06:16:51 +00003188 PatternsToMatch.push_back(PTM);
3189}
3190
3191
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003192
3193void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003194 const std::vector<const CodeGenInstruction*> &Instructions =
3195 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003196
3197 // First try to infer flags from the primary instruction pattern, if any.
3198 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003199 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003200 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3201 CodeGenInstruction &InstInfo =
3202 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003203
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003204 // Get the primary instruction pattern.
3205 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3206 if (!Pattern) {
3207 if (InstInfo.hasUndefFlags())
3208 Revisit.push_back(&InstInfo);
3209 continue;
3210 }
3211 InstAnalyzer PatInfo(*this);
3212 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003213 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003214 }
3215
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003216 // Second, look for single-instruction patterns defined outside the
3217 // instruction.
3218 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3219 const PatternToMatch &PTM = *I;
3220
3221 // We can only infer from single-instruction patterns, otherwise we won't
3222 // know which instruction should get the flags.
3223 SmallVector<Record*, 8> PatInstrs;
3224 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3225 if (PatInstrs.size() != 1)
3226 continue;
3227
3228 // Get the single instruction.
3229 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3230
3231 // Only infer properties from the first pattern. We'll verify the others.
3232 if (InstInfo.InferredFrom)
3233 continue;
3234
3235 InstAnalyzer PatInfo(*this);
3236 PatInfo.Analyze(&PTM);
3237 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3238 }
3239
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003240 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003241 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003242
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003243 // Revisit instructions with undefined flags and no pattern.
3244 if (Target.guessInstructionProperties()) {
3245 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3246 CodeGenInstruction &InstInfo = *Revisit[i];
3247 if (InstInfo.InferredFrom)
3248 continue;
3249 // The mayLoad and mayStore flags default to false.
3250 // Conservatively assume hasSideEffects if it wasn't explicit.
3251 if (InstInfo.hasSideEffects_Unset)
3252 InstInfo.hasSideEffects = true;
3253 }
3254 return;
3255 }
3256
3257 // Complain about any flags that are still undefined.
3258 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3259 CodeGenInstruction &InstInfo = *Revisit[i];
3260 if (InstInfo.InferredFrom)
3261 continue;
3262 if (InstInfo.hasSideEffects_Unset)
3263 PrintError(InstInfo.TheDef->getLoc(),
3264 "Can't infer hasSideEffects from patterns");
3265 if (InstInfo.mayStore_Unset)
3266 PrintError(InstInfo.TheDef->getLoc(),
3267 "Can't infer mayStore from patterns");
3268 if (InstInfo.mayLoad_Unset)
3269 PrintError(InstInfo.TheDef->getLoc(),
3270 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003271 }
3272}
3273
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003274
3275/// Verify instruction flags against pattern node properties.
3276void CodeGenDAGPatterns::VerifyInstructionFlags() {
3277 unsigned Errors = 0;
3278 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3279 const PatternToMatch &PTM = *I;
3280 SmallVector<Record*, 8> Instrs;
3281 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3282 if (Instrs.empty())
3283 continue;
3284
3285 // Count the number of instructions with each flag set.
3286 unsigned NumSideEffects = 0;
3287 unsigned NumStores = 0;
3288 unsigned NumLoads = 0;
3289 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3290 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3291 NumSideEffects += InstInfo.hasSideEffects;
3292 NumStores += InstInfo.mayStore;
3293 NumLoads += InstInfo.mayLoad;
3294 }
3295
3296 // Analyze the source pattern.
3297 InstAnalyzer PatInfo(*this);
3298 PatInfo.Analyze(&PTM);
3299
3300 // Collect error messages.
3301 SmallVector<std::string, 4> Msgs;
3302
3303 // Check for missing flags in the output.
3304 // Permit extra flags for now at least.
3305 if (PatInfo.hasSideEffects && !NumSideEffects)
3306 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3307
3308 // Don't verify store flags on instructions with side effects. At least for
3309 // intrinsics, side effects implies mayStore.
3310 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3311 Msgs.push_back("pattern may store, but mayStore isn't set");
3312
3313 // Similarly, mayStore implies mayLoad on intrinsics.
3314 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3315 Msgs.push_back("pattern may load, but mayLoad isn't set");
3316
3317 // Print error messages.
3318 if (Msgs.empty())
3319 continue;
3320 ++Errors;
3321
3322 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3323 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3324 (Instrs.size() == 1 ?
3325 "instruction" : "output instructions"));
3326 // Provide the location of the relevant instruction definitions.
3327 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3328 if (Instrs[i] != PTM.getSrcRecord())
3329 PrintError(Instrs[i]->getLoc(), "defined here");
3330 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3331 if (InstInfo.InferredFrom &&
3332 InstInfo.InferredFrom != InstInfo.TheDef &&
3333 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003334 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003335 }
3336 }
3337 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003338 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003339}
3340
Chris Lattnercabe0372010-03-15 06:00:16 +00003341/// Given a pattern result with an unresolved type, see if we can find one
3342/// instruction with an unresolved result type. Force this result type to an
3343/// arbitrary element if it's possible types to converge results.
3344static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3345 if (N->isLeaf())
3346 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003347
Chris Lattnercabe0372010-03-15 06:00:16 +00003348 // Analyze children.
3349 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3350 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3351 return true;
3352
3353 if (!N->getOperator()->isSubClassOf("Instruction"))
3354 return false;
3355
3356 // If this type is already concrete or completely unknown we can't do
3357 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003358 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3359 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3360 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003361
Chris Lattnerf1447252010-03-19 21:37:09 +00003362 // Otherwise, force its type to the first possibility (an arbitrary choice).
3363 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3364 return true;
3365 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003366
Chris Lattnerf1447252010-03-19 21:37:09 +00003367 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003368}
3369
Chris Lattnerab3242f2008-01-06 01:10:31 +00003370void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003371 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3372
3373 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003374 Record *CurPattern = Patterns[i];
David Greeneaf8ee2c2011-07-29 22:43:06 +00003375 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003376
3377 // If the pattern references the null_frag, there's nothing to do.
3378 if (hasNullFragReference(Tree))
3379 continue;
3380
Chris Lattner5c2182e2010-03-27 02:53:27 +00003381 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003382
3383 // Inline pattern fragments into it.
3384 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003385
David Greeneaf8ee2c2011-07-29 22:43:06 +00003386 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003387 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003388
Chris Lattner8cab0212008-01-05 22:25:12 +00003389 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003390 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003391
Chris Lattner8cab0212008-01-05 22:25:12 +00003392 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003393 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003394
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003395 if (Result.getNumTrees() != 1)
3396 Result.error("Cannot handle instructions producing instructions "
3397 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003398
Chris Lattner8cab0212008-01-05 22:25:12 +00003399 bool IterateInference;
3400 bool InferredAllPatternTypes, InferredAllResultTypes;
3401 do {
3402 // Infer as many types as possible. If we cannot infer all of them, we
3403 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003404 InferredAllPatternTypes =
3405 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003406
Chris Lattner8cab0212008-01-05 22:25:12 +00003407 // Infer as many types as possible. If we cannot infer all of them, we
3408 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003409 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003410 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003411
Chris Lattnerfdc20712010-03-18 23:15:10 +00003412 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003413
Chris Lattner8cab0212008-01-05 22:25:12 +00003414 // Apply the type of the result to the source pattern. This helps us
3415 // resolve cases where the input type is known to be a pointer type (which
3416 // is considered resolved), but the result knows it needs to be 32- or
3417 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003418 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003419 Pattern->getTree(0)->getNumTypes());
3420 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003421 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3422 i, Result.getTree(0)->getExtType(i), Result);
3423 IterateInference |= Result.getTree(0)->UpdateNodeType(
3424 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003425 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003426
Chris Lattnercabe0372010-03-15 06:00:16 +00003427 // If our iteration has converged and the input pattern's types are fully
3428 // resolved but the result pattern is not fully resolved, we may have a
3429 // situation where we have two instructions in the result pattern and
3430 // the instructions require a common register class, but don't care about
3431 // what actual MVT is used. This is actually a bug in our modelling:
3432 // output patterns should have register classes, not MVTs.
3433 //
3434 // In any case, to handle this, we just go through and disambiguate some
3435 // arbitrary types to the result pattern's nodes.
3436 if (!IterateInference && InferredAllPatternTypes &&
3437 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003438 IterateInference =
3439 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003440 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003441
Chris Lattner8cab0212008-01-05 22:25:12 +00003442 // Verify that we inferred enough types that we can do something with the
3443 // pattern and result. If these fire the user has to add type casts.
3444 if (!InferredAllPatternTypes)
3445 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003446 if (!InferredAllResultTypes) {
3447 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003448 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003449 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003450
Chris Lattner8cab0212008-01-05 22:25:12 +00003451 // Validate that the input pattern is correct.
3452 std::map<std::string, TreePatternNode*> InstInputs;
3453 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003454 std::vector<Record*> InstImpResults;
3455 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3456 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3457 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003458 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003459
3460 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003461 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003462 std::vector<TreePatternNode*> ResultNodeOperands;
3463 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3464 TreePatternNode *OpNode = DstPattern->getChild(ii);
3465 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003466 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003467 std::vector<TreePatternNode*> Children;
3468 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003469 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003470 }
3471 ResultNodeOperands.push_back(OpNode);
3472 }
David Blaikiecf195302014-11-17 22:55:41 +00003473 DstPattern = Result.getOnlyTree();
3474 if (!DstPattern->isLeaf())
3475 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3476 ResultNodeOperands,
3477 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003478
David Blaikiecf195302014-11-17 22:55:41 +00003479 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3480 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3481
3482 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003483 Temp.InferAllTypes();
3484
Jim Grosbach65586fe2010-12-21 16:16:00 +00003485
Chris Lattner0c0baa92010-02-23 06:16:51 +00003486 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003487 PatternToMatch(CurPattern,
3488 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003489 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003490 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003491 CurPattern->getValueAsInt("AddedComplexity"),
3492 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003493 }
3494}
3495
3496/// CombineChildVariants - Given a bunch of permutations of each child of the
3497/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003498static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003499 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3500 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003501 CodeGenDAGPatterns &CDP,
3502 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003503 // Make sure that each operand has at least one variant to choose from.
3504 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3505 if (ChildVariants[i].empty())
3506 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003507
Chris Lattner8cab0212008-01-05 22:25:12 +00003508 // The end result is an all-pairs construction of the resultant pattern.
3509 std::vector<unsigned> Idxs;
3510 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003511 bool NotDone;
3512 do {
3513#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003514 DEBUG(if (!Idxs.empty()) {
3515 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3516 for (unsigned i = 0; i < Idxs.size(); ++i) {
3517 errs() << Idxs[i] << " ";
3518 }
3519 errs() << "]\n";
3520 });
Scott Michel94420742008-03-05 17:49:05 +00003521#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003522 // Create the variant and add it to the output list.
3523 std::vector<TreePatternNode*> NewChildren;
3524 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3525 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerf1447252010-03-19 21:37:09 +00003526 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3527 Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003528
Chris Lattner8cab0212008-01-05 22:25:12 +00003529 // Copy over properties.
3530 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003531 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003532 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003533 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3534 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003535
Scott Michel94420742008-03-05 17:49:05 +00003536 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003537 std::string ErrString;
3538 if (!R->canPatternMatch(ErrString, CDP)) {
3539 delete R;
3540 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003541 // Scan to see if this pattern has already been emitted. We can get
3542 // duplication due to things like commuting:
3543 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3544 // which are the same pattern. Ignore the dups.
Craig Toppercbdc27e2015-11-22 19:27:02 +00003545 if (std::any_of(OutVariants.begin(), OutVariants.end(),
3546 [=](TreePatternNode *Variant) {
3547 return R->isIsomorphicTo(Variant, DepVars);
3548 }))
Chris Lattner8cab0212008-01-05 22:25:12 +00003549 delete R;
3550 else
3551 OutVariants.push_back(R);
3552 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003553
Scott Michel94420742008-03-05 17:49:05 +00003554 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003555 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003556 // [0, 0], [0, 1], [1, 0], [1, 1].
3557 int IdxsIdx;
3558 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3559 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3560 Idxs[IdxsIdx] = 0;
3561 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003562 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003563 }
Scott Michel94420742008-03-05 17:49:05 +00003564 NotDone = (IdxsIdx >= 0);
3565 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003566}
3567
3568/// CombineChildVariants - A helper function for binary operators.
3569///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003570static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003571 const std::vector<TreePatternNode*> &LHS,
3572 const std::vector<TreePatternNode*> &RHS,
3573 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003574 CodeGenDAGPatterns &CDP,
3575 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003576 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3577 ChildVariants.push_back(LHS);
3578 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003579 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003580}
Chris Lattner8cab0212008-01-05 22:25:12 +00003581
3582
3583static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3584 std::vector<TreePatternNode *> &Children) {
3585 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3586 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003587
Chris Lattner8cab0212008-01-05 22:25:12 +00003588 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003589 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003590 N->getTransformFn()) {
3591 Children.push_back(N);
3592 return;
3593 }
3594
3595 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3596 Children.push_back(N->getChild(0));
3597 else
3598 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3599
3600 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3601 Children.push_back(N->getChild(1));
3602 else
3603 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3604}
3605
3606/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3607/// the (potentially recursive) pattern by using algebraic laws.
3608///
3609static void GenerateVariantsOf(TreePatternNode *N,
3610 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003611 CodeGenDAGPatterns &CDP,
3612 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003613 // We cannot permute leaves or ComplexPattern uses.
3614 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003615 OutVariants.push_back(N);
3616 return;
3617 }
3618
3619 // Look up interesting info about the node.
3620 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3621
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003622 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003623 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003624 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003625 std::vector<TreePatternNode*> MaximalChildren;
3626 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3627
3628 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3629 // permutations.
3630 if (MaximalChildren.size() == 3) {
3631 // Find the variants of all of our maximal children.
3632 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003633 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3634 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3635 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003636
Chris Lattner8cab0212008-01-05 22:25:12 +00003637 // There are only two ways we can permute the tree:
3638 // (A op B) op C and A op (B op C)
3639 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003640
Chris Lattner8cab0212008-01-05 22:25:12 +00003641 // Generate legal pair permutations of A/B/C.
3642 std::vector<TreePatternNode*> ABVariants;
3643 std::vector<TreePatternNode*> BAVariants;
3644 std::vector<TreePatternNode*> ACVariants;
3645 std::vector<TreePatternNode*> CAVariants;
3646 std::vector<TreePatternNode*> BCVariants;
3647 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003648 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3649 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3650 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3651 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3652 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3653 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003654
3655 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003656 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3657 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3658 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3659 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3660 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3661 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003662
3663 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003664 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3665 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3666 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3667 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3668 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3669 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003670 return;
3671 }
3672 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003673
Chris Lattner8cab0212008-01-05 22:25:12 +00003674 // Compute permutations of all children.
3675 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3676 ChildVariants.resize(N->getNumChildren());
3677 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003678 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003679
3680 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003681 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003682
3683 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003684 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3685 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3686 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3687 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003688 // Don't count children which are actually register references.
3689 unsigned NC = 0;
3690 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3691 TreePatternNode *Child = N->getChild(i);
3692 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003693 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003694 Record *RR = DI->getDef();
3695 if (RR->isSubClassOf("Register"))
3696 continue;
3697 }
3698 NC++;
3699 }
3700 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003701 if (isCommIntrinsic) {
3702 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3703 // operands are the commutative operands, and there might be more operands
3704 // after those.
3705 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003706 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00003707 std::vector<std::vector<TreePatternNode*> > Variants;
3708 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3709 Variants.push_back(ChildVariants[2]);
3710 Variants.push_back(ChildVariants[1]);
3711 for (unsigned i = 3; i != NC; ++i)
3712 Variants.push_back(ChildVariants[i]);
3713 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3714 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003715 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003716 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003717 }
3718}
3719
3720
3721// GenerateVariants - Generate variants. For example, commutative patterns can
3722// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003723void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003724 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003725
Chris Lattner8cab0212008-01-05 22:25:12 +00003726 // Loop over all of the patterns we've collected, checking to see if we can
3727 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003728 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003729 // the .td file having to contain tons of variants of instructions.
3730 //
3731 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3732 // intentionally do not reconsider these. Any variants of added patterns have
3733 // already been added.
3734 //
3735 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003736 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003737 std::vector<TreePatternNode*> Variants;
Scott Michel94420742008-03-05 17:49:05 +00003738 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003739 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003740 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003741 DEBUG(errs() << "\n");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003742 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3743 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003744
3745 assert(!Variants.empty() && "Must create at least original variant!");
3746 Variants.erase(Variants.begin()); // Remove the original pattern.
3747
3748 if (Variants.empty()) // No variants for this pattern.
3749 continue;
3750
Chris Lattner34822f62009-08-23 04:44:11 +00003751 DEBUG(errs() << "FOUND VARIANTS OF: ";
3752 PatternsToMatch[i].getSrcPattern()->dump();
3753 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003754
3755 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3756 TreePatternNode *Variant = Variants[v];
3757
Chris Lattner34822f62009-08-23 04:44:11 +00003758 DEBUG(errs() << " VAR#" << v << ": ";
3759 Variant->dump();
3760 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003761
Chris Lattner8cab0212008-01-05 22:25:12 +00003762 // Scan to see if an instruction or explicit pattern already matches this.
3763 bool AlreadyExists = false;
3764 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003765 // Skip if the top level predicates do not match.
3766 if (PatternsToMatch[i].getPredicates() !=
3767 PatternsToMatch[p].getPredicates())
3768 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003769 // Check to see if this variant already exists.
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003770 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3771 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003772 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003773 AlreadyExists = true;
3774 break;
3775 }
3776 }
3777 // If we already have it, ignore the variant.
3778 if (AlreadyExists) continue;
3779
3780 // Otherwise, add it to the list of patterns we have.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00003781 PatternsToMatch.emplace_back(
3782 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3783 Variant, PatternsToMatch[i].getDstPattern(),
3784 PatternsToMatch[i].getDstRegs(),
3785 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
Chris Lattner8cab0212008-01-05 22:25:12 +00003786 }
3787
Chris Lattner34822f62009-08-23 04:44:11 +00003788 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003789 }
3790}