blob: e5c6613edfd38b03116888115b51c61267ac69a5 [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 {
110 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
111 if (isInteger(TypeVec[i]))
112 return true;
113 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000114}
Chris Lattnercabe0372010-03-15 06:00:16 +0000115
116/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
117/// a floating point value type.
118bool EEVT::TypeSet::hasFloatingPointTypes() const {
119 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
120 if (isFloatingPoint(TypeVec[i]))
121 return true;
122 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000123}
Chris Lattnercabe0372010-03-15 06:00:16 +0000124
Craig Topper74169dc2014-01-28 04:49:01 +0000125/// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
126bool EEVT::TypeSet::hasScalarTypes() const {
127 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
128 if (isScalar(TypeVec[i]))
129 return true;
130 return false;
131}
132
Chris Lattnercabe0372010-03-15 06:00:16 +0000133/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
134/// value type.
135bool EEVT::TypeSet::hasVectorTypes() const {
136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
137 if (isVector(TypeVec[i]))
138 return true;
139 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +0000140}
Bob Wilson2cd5da82009-08-11 01:14:02 +0000141
Chris Lattnercabe0372010-03-15 06:00:16 +0000142
143std::string EEVT::TypeSet::getName() const {
Chris Lattnerda5b4ad2010-03-19 01:14:27 +0000144 if (TypeVec.empty()) return "<empty>";
Jim Grosbach65586fe2010-12-21 16:16:00 +0000145
Chris Lattnercabe0372010-03-15 06:00:16 +0000146 std::string Result;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000147
Chris Lattnercabe0372010-03-15 06:00:16 +0000148 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
149 std::string VTName = llvm::getEnumName(TypeVec[i]);
150 // Strip off MVT:: prefix if present.
151 if (VTName.substr(0,5) == "MVT::")
152 VTName = VTName.substr(5);
153 if (i) Result += ':';
154 Result += VTName;
155 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000156
Chris Lattnercabe0372010-03-15 06:00:16 +0000157 if (TypeVec.size() == 1)
158 return Result;
159 return "{" + Result + "}";
Bob Wilson2cd5da82009-08-11 01:14:02 +0000160}
Chris Lattnercabe0372010-03-15 06:00:16 +0000161
162/// MergeInTypeInfo - This merges in type information from the specified
163/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000164/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattnercabe0372010-03-15 06:00:16 +0000165bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000166 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattnercabe0372010-03-15 06:00:16 +0000167 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000168
Chris Lattnercabe0372010-03-15 06:00:16 +0000169 if (isCompletelyUnknown()) {
170 *this = InVT;
171 return true;
172 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000173
Chris Lattnercabe0372010-03-15 06:00:16 +0000174 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000175
Chris Lattnercabe0372010-03-15 06:00:16 +0000176 // Handle the abstract cases, seeing if we can resolve them better.
177 switch (TypeVec[0]) {
178 default: break;
179 case MVT::iPTR:
180 case MVT::iPTRAny:
181 if (InVT.hasIntegerTypes()) {
182 EEVT::TypeSet InCopy(InVT);
183 InCopy.EnforceInteger(TP);
184 InCopy.EnforceScalar(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000185
Chris Lattnercabe0372010-03-15 06:00:16 +0000186 if (InCopy.isConcrete()) {
187 // If the RHS has one integer type, upgrade iPTR to i32.
188 TypeVec[0] = InVT.TypeVec[0];
189 return true;
190 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000191
Chris Lattnercabe0372010-03-15 06:00:16 +0000192 // If the input has multiple scalar integers, this doesn't add any info.
193 if (!InCopy.isCompletelyUnknown())
194 return false;
195 }
196 break;
197 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000198
Chris Lattnercabe0372010-03-15 06:00:16 +0000199 // If the input constraint is iAny/iPTR and this is an integer type list,
200 // remove non-integer types from the list.
201 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
202 hasIntegerTypes()) {
203 bool MadeChange = EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000204
Chris Lattnercabe0372010-03-15 06:00:16 +0000205 // If we're merging in iPTR/iPTRAny and the node currently has a list of
206 // multiple different integer types, replace them with a single iPTR.
207 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
208 TypeVec.size() != 1) {
209 TypeVec.resize(1);
210 TypeVec[0] = InVT.TypeVec[0];
211 MadeChange = true;
212 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000213
Chris Lattnercabe0372010-03-15 06:00:16 +0000214 return MadeChange;
215 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000216
Chris Lattnercabe0372010-03-15 06:00:16 +0000217 // If this is a type list and the RHS is a typelist as well, eliminate entries
218 // from this list that aren't in the other one.
219 bool MadeChange = false;
220 TypeSet InputSet(*this);
221
222 for (unsigned i = 0; i != TypeVec.size(); ++i) {
223 bool InInVT = false;
224 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
225 if (TypeVec[i] == InVT.TypeVec[j]) {
226 InInVT = true;
227 break;
228 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000229
Chris Lattnercabe0372010-03-15 06:00:16 +0000230 if (InInVT) continue;
231 TypeVec.erase(TypeVec.begin()+i--);
232 MadeChange = true;
233 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000234
Chris Lattnercabe0372010-03-15 06:00:16 +0000235 // If we removed all of our types, we have a type contradiction.
236 if (!TypeVec.empty())
237 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000238
Chris Lattnercabe0372010-03-15 06:00:16 +0000239 // FIXME: Really want an SMLoc here!
240 TP.error("Type inference contradiction found, merging '" +
241 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000242 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000243}
244
245/// EnforceInteger - Remove all non-integer types from this set.
246bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000247 if (TP.hasError())
248 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000249 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000250 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000251 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattnercabe0372010-03-15 06:00:16 +0000252 if (!hasFloatingPointTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000253 return false;
254
255 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000256
Chris Lattnercabe0372010-03-15 06:00:16 +0000257 // Filter out all the fp types.
258 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000259 if (!isInteger(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000260 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000261
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000262 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000263 TP.error("Type inference contradiction found, '" +
264 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000265 return false;
266 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000267 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000268}
269
270/// EnforceFloatingPoint - Remove all integer types from this set.
271bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000272 if (TP.hasError())
273 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000274 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000275 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000276 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
277
Chris Lattnercabe0372010-03-15 06:00:16 +0000278 if (!hasIntegerTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000279 return false;
280
281 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000282
Chris Lattnercabe0372010-03-15 06:00:16 +0000283 // Filter out all the fp types.
284 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000285 if (!isFloatingPoint(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000286 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000287
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000288 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000289 TP.error("Type inference contradiction found, '" +
290 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000291 return false;
292 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000293 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000294}
295
296/// EnforceScalar - Remove all vector types from this.
297bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000298 if (TP.hasError())
299 return false;
300
Chris Lattnercabe0372010-03-15 06:00:16 +0000301 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000302 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000303 return FillWithPossibleTypes(TP, isScalar, "scalar");
304
Chris Lattnercabe0372010-03-15 06:00:16 +0000305 if (!hasVectorTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000306 return false;
307
308 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000309
Chris Lattnercabe0372010-03-15 06:00:16 +0000310 // Filter out all the vector types.
311 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000312 if (!isScalar(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000313 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000314
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000315 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000316 TP.error("Type inference contradiction found, '" +
317 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000318 return false;
319 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000320 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000321}
322
323/// EnforceVector - Remove all vector types from this.
324bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000325 if (TP.hasError())
326 return false;
327
Chris Lattner6d765eb2010-03-19 17:41:26 +0000328 // If we know nothing, then get the full set.
329 if (TypeVec.empty())
330 return FillWithPossibleTypes(TP, isVector, "vector");
331
Chris Lattnercabe0372010-03-15 06:00:16 +0000332 TypeSet InputSet(*this);
333 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000334
Chris Lattnercabe0372010-03-15 06:00:16 +0000335 // Filter out all the scalar types.
336 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000337 if (!isVector(TypeVec[i])) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000338 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner6d765eb2010-03-19 17:41:26 +0000339 MadeChange = true;
340 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000341
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000342 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000343 TP.error("Type inference contradiction found, '" +
344 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000345 return false;
346 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000347 return MadeChange;
348}
349
350
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000351
Craig Topper74169dc2014-01-28 04:49:01 +0000352/// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
353/// this shoud be based on the element type. Update this and other based on
354/// this information.
Chris Lattnercabe0372010-03-15 06:00:16 +0000355bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000356 if (TP.hasError())
357 return false;
358
Chris Lattnercabe0372010-03-15 06:00:16 +0000359 // Both operands must be integer or FP, but we don't care which.
360 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000361
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000362 if (isCompletelyUnknown())
363 MadeChange = FillWithPossibleTypes(TP);
364
365 if (Other.isCompletelyUnknown())
366 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000367
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000368 // If one side is known to be integer or known to be FP but the other side has
369 // no information, get at least the type integrality info in there.
370 if (!hasFloatingPointTypes())
371 MadeChange |= Other.EnforceInteger(TP);
372 else if (!hasIntegerTypes())
373 MadeChange |= Other.EnforceFloatingPoint(TP);
374 if (!Other.hasFloatingPointTypes())
375 MadeChange |= EnforceInteger(TP);
376 else if (!Other.hasIntegerTypes())
377 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000378
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000379 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
380 "Should have a type list now");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000381
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000382 // If one contains vectors but the other doesn't pull vectors out.
383 if (!hasVectorTypes())
384 MadeChange |= Other.EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000385 else if (!hasScalarTypes())
386 MadeChange |= Other.EnforceVector(TP);
Craig Topper6dbcb942014-01-25 05:17:38 +0000387 if (!Other.hasVectorTypes())
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000388 MadeChange |= EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000389 else if (!Other.hasScalarTypes())
390 MadeChange |= EnforceVector(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000391
Craig Topper74169dc2014-01-28 04:49:01 +0000392 // For vectors we need to ensure that smaller size doesn't produce larger
393 // vector and vice versa.
394 if (isConcrete() && isVector(getConcrete())) {
395 MVT IVT = getConcrete();
396 unsigned Size = IVT.getSizeInBits();
David Greene433c6182011-02-01 19:12:32 +0000397
Craig Topper74169dc2014-01-28 04:49:01 +0000398 // Only keep types that have at least as many bits.
399 TypeSet InputSet(Other);
David Greene433c6182011-02-01 19:12:32 +0000400
Craig Topper74169dc2014-01-28 04:49:01 +0000401 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
402 assert(isVector(Other.TypeVec[i]) && "EnforceVector didn't work");
403 if (MVT(Other.TypeVec[i]).getSizeInBits() < Size) {
404 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
David Greene433c6182011-02-01 19:12:32 +0000405 MadeChange = true;
David Greene433c6182011-02-01 19:12:32 +0000406 }
407 }
Craig Topper74169dc2014-01-28 04:49:01 +0000408
409 if (Other.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
410 TP.error("Type inference contradiction found, forcing '" +
411 InputSet.getName() + "' to have at least as many bits as " +
412 getName() + "'");
413 return false;
414 }
415 } else if (Other.isConcrete() && isVector(Other.getConcrete())) {
416 MVT IVT = Other.getConcrete();
417 unsigned Size = IVT.getSizeInBits();
418
419 // Only keep types with the same or fewer total bits
420 TypeSet InputSet(*this);
421
422 for (unsigned i = 0; i != TypeVec.size(); ++i) {
423 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
424 if (MVT(TypeVec[i]).getSizeInBits() > Size) {
425 TypeVec.erase(TypeVec.begin()+i--);
426 MadeChange = true;
427 }
428 }
429
430 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
431 TP.error("Type inference contradiction found, forcing '" +
432 InputSet.getName() + "' to have the same or fewer bits than " +
433 Other.getName() + "'");
434 return false;
435 }
David Greene433c6182011-02-01 19:12:32 +0000436 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000437
Craig Topper74169dc2014-01-28 04:49:01 +0000438 // This code does not currently handle nodes which have multiple types,
439 // where some types are integer, and some are fp. Assert that this is not
440 // the case.
441 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
442 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
443 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
444
445 if (TP.hasError())
446 return false;
447
448 // Okay, find the smallest scalar type from the other set and remove
449 // anything the same or smaller from the current set.
450 TypeSet InputSet(Other);
451 MVT::SimpleValueType Smallest = TypeVec[0];
452 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
453 if (Other.TypeVec[i] <= Smallest) {
454 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
455 MadeChange = true;
456 }
457 }
458
459 if (Other.TypeVec.empty()) {
460 TP.error("Type inference contradiction found, '" + InputSet.getName() +
461 "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000462 return false;
463 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000464
Craig Topper74169dc2014-01-28 04:49:01 +0000465 // Okay, find the largest scalar type from the other set and remove
466 // anything the same or larger from the current set.
467 InputSet = TypeSet(*this);
468 MVT::SimpleValueType Largest = Other.TypeVec[Other.TypeVec.size()-1];
469 for (unsigned i = 0; i != TypeVec.size(); ++i) {
470 if (TypeVec[i] >= Largest) {
471 TypeVec.erase(TypeVec.begin()+i--);
472 MadeChange = true;
David Greene433c6182011-02-01 19:12:32 +0000473 }
David Greene433c6182011-02-01 19:12:32 +0000474 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000475
Craig Topper74169dc2014-01-28 04:49:01 +0000476 if (TypeVec.empty()) {
477 TP.error("Type inference contradiction found, '" + InputSet.getName() +
478 "' has nothing smaller than '" + Other.getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000479 return false;
480 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000481
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000482 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000483}
484
485/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000486/// whose element is specified by VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000487bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
488 TreePattern &TP) {
489 bool MadeChange = false;
490
491 MadeChange |= EnforceVector(TP);
492
493 TypeSet InputSet(*this);
494
495 // Filter out all the types which don't have the right element type.
496 for (unsigned i = 0; i != TypeVec.size(); ++i) {
497 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
498 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
499 TypeVec.erase(TypeVec.begin()+i--);
500 MadeChange = true;
501 }
502 }
503
504 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
505 TP.error("Type inference contradiction found, forcing '" +
506 InputSet.getName() + "' to have a vector element");
507 return false;
508 }
509
510 return MadeChange;
511}
512
513/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
514/// whose element is specified by VTOperand.
Chris Lattner57ebf632010-03-24 00:01:16 +0000515bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000516 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000517 if (TP.hasError())
518 return false;
519
Chris Lattner57ebf632010-03-24 00:01:16 +0000520 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000521 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000522 MadeChange |= EnforceVector(TP);
523 MadeChange |= VTOperand.EnforceScalar(TP);
524
525 // If we know the vector type, it forces the scalar to agree.
526 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000527 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000528 IVT = IVT.getVectorElementType();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000529 return MadeChange |
Craig Topper95198f42013-09-25 06:37:18 +0000530 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000531 }
532
533 // If the scalar type is known, filter out vector types whose element types
534 // disagree.
535 if (!VTOperand.isConcrete())
536 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000537
Chris Lattner57ebf632010-03-24 00:01:16 +0000538 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000539
Chris Lattner57ebf632010-03-24 00:01:16 +0000540 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000541
Chris Lattner57ebf632010-03-24 00:01:16 +0000542 // Filter out all the types which don't have the right element type.
543 for (unsigned i = 0; i != TypeVec.size(); ++i) {
544 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
Craig Topper95198f42013-09-25 06:37:18 +0000545 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000546 TypeVec.erase(TypeVec.begin()+i--);
547 MadeChange = true;
548 }
Chris Lattner57ebf632010-03-24 00:01:16 +0000549 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000550
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000551 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattnercabe0372010-03-15 06:00:16 +0000552 TP.error("Type inference contradiction found, forcing '" +
553 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000554 return false;
555 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000556 return MadeChange;
557}
558
David Greene127fd1d2011-01-24 20:53:18 +0000559/// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
560/// vector type specified by VTOperand.
561bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
562 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000563 if (TP.hasError())
564 return false;
565
David Greene127fd1d2011-01-24 20:53:18 +0000566 // "This" must be a vector and "VTOperand" must be a vector.
567 bool MadeChange = false;
568 MadeChange |= EnforceVector(TP);
569 MadeChange |= VTOperand.EnforceVector(TP);
570
Craig Topper6e1faaf2014-01-25 17:40:33 +0000571 // If one side is known to be integer or known to be FP but the other side has
572 // no information, get at least the type integrality info in there.
573 if (!hasFloatingPointTypes())
574 MadeChange |= VTOperand.EnforceInteger(TP);
575 else if (!hasIntegerTypes())
576 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
577 if (!VTOperand.hasFloatingPointTypes())
578 MadeChange |= EnforceInteger(TP);
579 else if (!VTOperand.hasIntegerTypes())
580 MadeChange |= EnforceFloatingPoint(TP);
581
582 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
583 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000584
585 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000586 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000587 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000588 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000589 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000590 IVT = IVT.getVectorElementType();
591
Craig Topper95198f42013-09-25 06:37:18 +0000592 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000593 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000594
595 // Only keep types that have less elements than VTOperand.
596 TypeSet InputSet(VTOperand);
597
598 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
599 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
600 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
601 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
602 MadeChange = true;
603 }
604 }
605 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
606 TP.error("Type inference contradiction found, forcing '" +
607 InputSet.getName() + "' to have less vector elements than '" +
608 getName() + "'");
609 return false;
610 }
David Greene127fd1d2011-01-24 20:53:18 +0000611 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000612 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000613 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000614 IVT = IVT.getVectorElementType();
615
Craig Topper95198f42013-09-25 06:37:18 +0000616 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000617 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000618
619 // Only keep types that have more elements than 'this'.
620 TypeSet InputSet(*this);
621
622 for (unsigned i = 0; i != TypeVec.size(); ++i) {
623 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
624 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
625 TypeVec.erase(TypeVec.begin()+i--);
626 MadeChange = true;
627 }
628 }
629 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
630 TP.error("Type inference contradiction found, forcing '" +
631 InputSet.getName() + "' to have more vector elements than '" +
632 VTOperand.getName() + "'");
633 return false;
634 }
David Greene127fd1d2011-01-24 20:53:18 +0000635 }
636
637 return MadeChange;
638}
639
Craig Topper0be34582015-03-05 07:11:34 +0000640/// EnforceVectorSameNumElts - 'this' is now constrainted to
641/// be a vector with same num elements as VTOperand.
642bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
643 TreePattern &TP) {
644 if (TP.hasError())
645 return false;
646
647 // "This" must be a vector and "VTOperand" must be a vector.
648 bool MadeChange = false;
649 MadeChange |= EnforceVector(TP);
650 MadeChange |= VTOperand.EnforceVector(TP);
651
652 // If we know one of the vector types, it forces the other type to agree.
653 if (isConcrete()) {
654 MVT IVT = getConcrete();
655 unsigned NumElems = IVT.getVectorNumElements();
656
657 // Only keep types that have same elements as VTOperand.
658 TypeSet InputSet(VTOperand);
659
660 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
661 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
662 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
663 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
664 MadeChange = true;
665 }
666 }
667 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
668 TP.error("Type inference contradiction found, forcing '" +
669 InputSet.getName() + "' to have same number elements as '" +
670 getName() + "'");
671 return false;
672 }
673 } else if (VTOperand.isConcrete()) {
674 MVT IVT = VTOperand.getConcrete();
675 unsigned NumElems = IVT.getVectorNumElements();
676
677 // Only keep types that have same elements as 'this'.
678 TypeSet InputSet(*this);
679
680 for (unsigned i = 0; i != TypeVec.size(); ++i) {
681 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
682 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
683 TypeVec.erase(TypeVec.begin()+i--);
684 MadeChange = true;
685 }
686 }
687 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
688 TP.error("Type inference contradiction found, forcing '" +
689 InputSet.getName() + "' to have same number elements than '" +
690 VTOperand.getName() + "'");
691 return false;
692 }
693 }
694
695 return MadeChange;
696}
697
Chris Lattnercabe0372010-03-15 06:00:16 +0000698//===----------------------------------------------------------------------===//
699// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000700
Scott Michel94420742008-03-05 17:49:05 +0000701/// Dependent variable map for CodeGenDAGPattern variant generation
702typedef std::map<std::string, int> DepVarMap;
703
704/// Const iterator shorthand for DepVarMap
705typedef DepVarMap::const_iterator DepVarMap_citer;
706
Chris Lattner514e2922011-04-17 21:38:24 +0000707static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000708 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000709 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000710 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000711 } else {
712 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
713 FindDepVarsOf(N->getChild(i), DepMap);
714 }
715}
Chris Lattner514e2922011-04-17 21:38:24 +0000716
717/// Find dependent variables within child patterns
718static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000719 DepVarMap depcounts;
720 FindDepVarsOf(N, depcounts);
721 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner514e2922011-04-17 21:38:24 +0000722 if (i->second > 1) // std::pair<std::string, int>
Scott Michel94420742008-03-05 17:49:05 +0000723 DepVars.insert(i->first);
Scott Michel94420742008-03-05 17:49:05 +0000724 }
725}
726
Daniel Dunbarba66a812010-10-08 02:07:22 +0000727#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000728/// Dump the dependent variable set:
729static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000730 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000731 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000732 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000733 DEBUG(errs() << "[ ");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +0000734 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
735 e = DepVars.end(); i != e; ++i) {
Chris Lattner34822f62009-08-23 04:44:11 +0000736 DEBUG(errs() << (*i) << " ");
Scott Michel94420742008-03-05 17:49:05 +0000737 }
Chris Lattner34822f62009-08-23 04:44:11 +0000738 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000739 }
740}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000741#endif
742
Chris Lattner514e2922011-04-17 21:38:24 +0000743
744//===----------------------------------------------------------------------===//
745// TreePredicateFn Implementation
746//===----------------------------------------------------------------------===//
747
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000748/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
749TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
750 assert((getPredCode().empty() || getImmCode().empty()) &&
751 ".td file corrupt: can't have a node predicate *and* an imm predicate");
752}
753
Chris Lattner514e2922011-04-17 21:38:24 +0000754std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000755 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000756}
757
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000758std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000759 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000760}
761
Chris Lattner514e2922011-04-17 21:38:24 +0000762
763/// isAlwaysTrue - Return true if this is a noop predicate.
764bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000765 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000766}
767
768/// Return the name to use in the generated code to reference this, this is
769/// "Predicate_foo" if from a pattern fragment "foo".
770std::string TreePredicateFn::getFnName() const {
771 return "Predicate_" + PatFragRec->getRecord()->getName();
772}
773
774/// getCodeToRunOnSDNode - Return the code for the function body that
775/// evaluates this predicate. The argument is expected to be in "Node",
776/// not N. This handles casting and conversion to a concrete node type as
777/// appropriate.
778std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000779 // Handle immediate predicates first.
780 std::string ImmCode = getImmCode();
781 if (!ImmCode.empty()) {
782 std::string Result =
783 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000784 return Result + ImmCode;
785 }
786
787 // Handle arbitrary node predicates.
788 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000789 std::string ClassName;
790 if (PatFragRec->getOnlyTree()->isLeaf())
791 ClassName = "SDNode";
792 else {
793 Record *Op = PatFragRec->getOnlyTree()->getOperator();
794 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
795 }
796 std::string Result;
797 if (ClassName == "SDNode")
798 Result = " SDNode *N = Node;\n";
799 else
800 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
801
802 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000803}
804
Chris Lattner8cab0212008-01-05 22:25:12 +0000805//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000806// PatternToMatch implementation
807//
808
Chris Lattner05925fe2010-03-29 01:40:38 +0000809
810/// getPatternSize - Return the 'size' of this pattern. We want to match large
811/// patterns before small ones. This is used to determine the size of a
812/// pattern.
813static unsigned getPatternSize(const TreePatternNode *P,
814 const CodeGenDAGPatterns &CGP) {
815 unsigned Size = 3; // The node itself.
816 // If the root node is a ConstantSDNode, increases its size.
817 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000818 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000819 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000820
Chris Lattner05925fe2010-03-29 01:40:38 +0000821 // FIXME: This is a hack to statically increase the priority of patterns
822 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
823 // Later we can allow complexity / cost for each pattern to be (optionally)
824 // specified. To get best possible pattern match we'll need to dynamically
825 // calculate the complexity of all patterns a dag can potentially map to.
826 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000827 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000828 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000829
Tim Northoverc807a172014-05-20 11:52:46 +0000830 // We don't want to count any children twice, so return early.
831 return Size;
832 }
833
Chris Lattner05925fe2010-03-29 01:40:38 +0000834 // If this node has some predicate function that must match, it adds to the
835 // complexity of this node.
836 if (!P->getPredicateFns().empty())
837 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000838
Chris Lattner05925fe2010-03-29 01:40:38 +0000839 // Count children in the count if they are also nodes.
840 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
841 TreePatternNode *Child = P->getChild(i);
842 if (!Child->isLeaf() && Child->getNumTypes() &&
843 Child->getType(0) != MVT::Other)
844 Size += getPatternSize(Child, CGP);
845 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000846 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000847 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
848 else if (Child->getComplexPatternInfo(CGP))
849 Size += getPatternSize(Child, CGP);
850 else if (!Child->getPredicateFns().empty())
851 ++Size;
852 }
853 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000854
Chris Lattner05925fe2010-03-29 01:40:38 +0000855 return Size;
856}
857
858/// Compute the complexity metric for the input pattern. This roughly
859/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000860int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000861getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
862 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
863}
864
865
Dan Gohman49e19e92008-08-22 00:20:26 +0000866/// getPredicateCheck - Return a single string containing all of this
867/// pattern's predicates concatenated with "&&" operators.
868///
869std::string PatternToMatch::getPredicateCheck() const {
870 std::string PredicateCheck;
871 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +0000872 if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000873 Record *Def = Pred->getDef();
874 if (!Def->isSubClassOf("Predicate")) {
875#ifndef NDEBUG
876 Def->dump();
877#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000878 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000879 }
880 if (!PredicateCheck.empty())
881 PredicateCheck += " && ";
882 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
883 }
884 }
885
886 return PredicateCheck;
887}
888
889//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000890// SDTypeConstraint implementation
891//
892
893SDTypeConstraint::SDTypeConstraint(Record *R) {
894 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000895
Chris Lattner8cab0212008-01-05 22:25:12 +0000896 if (R->isSubClassOf("SDTCisVT")) {
897 ConstraintType = SDTCisVT;
898 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000899 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000900 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000901
Chris Lattner8cab0212008-01-05 22:25:12 +0000902 } else if (R->isSubClassOf("SDTCisPtrTy")) {
903 ConstraintType = SDTCisPtrTy;
904 } else if (R->isSubClassOf("SDTCisInt")) {
905 ConstraintType = SDTCisInt;
906 } else if (R->isSubClassOf("SDTCisFP")) {
907 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000908 } else if (R->isSubClassOf("SDTCisVec")) {
909 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000910 } else if (R->isSubClassOf("SDTCisSameAs")) {
911 ConstraintType = SDTCisSameAs;
912 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
913 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
914 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000915 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000916 R->getValueAsInt("OtherOperandNum");
917 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
918 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000919 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000920 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000921 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
922 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000923 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000924 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
925 ConstraintType = SDTCisSubVecOfVec;
926 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
927 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000928 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
929 ConstraintType = SDTCVecEltisVT;
930 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
931 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
932 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
933 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
934 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
935 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
936 "as SDTCVecEltisVT");
937 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
938 ConstraintType = SDTCisSameNumEltsAs;
939 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
940 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000941 } else {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +0000942 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +0000943 exit(1);
944 }
945}
946
947/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000948/// N, and the result number in ResNo.
949static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
950 const SDNodeInfo &NodeInfo,
951 unsigned &ResNo) {
952 unsigned NumResults = NodeInfo.getNumResults();
953 if (OpNo < NumResults) {
954 ResNo = OpNo;
955 return N;
956 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000957
Chris Lattner2db7aba2010-03-19 21:56:21 +0000958 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000959
Chris Lattner2db7aba2010-03-19 21:56:21 +0000960 if (OpNo >= N->getNumChildren()) {
Jim Grosbach65586fe2010-12-21 16:16:00 +0000961 errs() << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000962 << (OpNo+NumResults) << " ";
Chris Lattner8cab0212008-01-05 22:25:12 +0000963 N->dump();
Daniel Dunbar38a22bf2009-07-03 00:10:29 +0000964 errs() << '\n';
Chris Lattner8cab0212008-01-05 22:25:12 +0000965 exit(1);
966 }
967
Chris Lattner2db7aba2010-03-19 21:56:21 +0000968 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000969}
970
971/// ApplyTypeConstraint - Given a node in a pattern, apply this type
972/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000973/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000974bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
975 const SDNodeInfo &NodeInfo,
976 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000977 if (TP.hasError())
978 return false;
979
Chris Lattner2db7aba2010-03-19 21:56:21 +0000980 unsigned ResNo = 0; // The result number being referenced.
981 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000982
Chris Lattner8cab0212008-01-05 22:25:12 +0000983 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000984 case SDTCisVT:
985 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000986 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000987 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000988 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000989 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000990 case SDTCisInt:
991 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000992 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000993 case SDTCisFP:
994 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000995 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000996 case SDTCisVec:
997 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000998 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000999 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001000 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001001 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001002 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001003 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1004 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001005 }
1006 case SDTCisVTSmallerThanOp: {
1007 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1008 // have an integer type that is smaller than the VT.
1009 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001010 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001011 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001012 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001013 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001014 return false;
1015 }
Owen Anderson9f944592009-08-11 20:47:22 +00001016 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +00001017 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001018
Chris Lattner38c99662010-03-24 00:06:46 +00001019 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001020
Chris Lattner2db7aba2010-03-19 21:56:21 +00001021 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001022 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001023 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1024 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001025
Chris Lattner38c99662010-03-24 00:06:46 +00001026 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001027 }
1028 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001029 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001030 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001031 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1032 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +00001033 return NodeToApply->getExtType(ResNo).
1034 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001035 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001036 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001037 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001038 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001039 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1040 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001041
Chris Lattner57ebf632010-03-24 00:01:16 +00001042 // Filter vector types out of VecOperand that don't have the right element
1043 // type.
1044 return VecOperand->getExtType(VResNo).
1045 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +00001046 }
David Greene127fd1d2011-01-24 20:53:18 +00001047 case SDTCisSubVecOfVec: {
1048 unsigned VResNo = 0;
1049 TreePatternNode *BigVecOperand =
1050 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1051 VResNo);
1052
1053 // Filter vector types out of BigVecOperand that don't have the
1054 // right subvector type.
1055 return BigVecOperand->getExtType(VResNo).
1056 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1057 }
Craig Topper0be34582015-03-05 07:11:34 +00001058 case SDTCVecEltisVT: {
1059 return NodeToApply->getExtType(ResNo).
1060 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1061 }
1062 case SDTCisSameNumEltsAs: {
1063 unsigned OResNo = 0;
1064 TreePatternNode *OtherNode =
1065 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1066 N, NodeInfo, OResNo);
1067 return OtherNode->getExtType(OResNo).
1068 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1069 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001070 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001071 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001072}
1073
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001074// Update the node type to match an instruction operand or result as specified
1075// in the ins or outs lists on the instruction definition. Return true if the
1076// type was actually changed.
1077bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1078 Record *Operand,
1079 TreePattern &TP) {
1080 // The 'unknown' operand indicates that types should be inferred from the
1081 // context.
1082 if (Operand->isSubClassOf("unknown_class"))
1083 return false;
1084
1085 // The Operand class specifies a type directly.
1086 if (Operand->isSubClassOf("Operand"))
1087 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1088 TP);
1089
1090 // PointerLikeRegClass has a type that is determined at runtime.
1091 if (Operand->isSubClassOf("PointerLikeRegClass"))
1092 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1093
1094 // Both RegisterClass and RegisterOperand operands derive their types from a
1095 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001096 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001097 if (Operand->isSubClassOf("RegisterClass"))
1098 RC = Operand;
1099 else if (Operand->isSubClassOf("RegisterOperand"))
1100 RC = Operand->getValueAsDef("RegClass");
1101
1102 assert(RC && "Unknown operand type");
1103 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1104 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1105}
1106
1107
Chris Lattner8cab0212008-01-05 22:25:12 +00001108//===----------------------------------------------------------------------===//
1109// SDNodeInfo implementation
1110//
1111SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1112 EnumName = R->getValueAsString("Opcode");
1113 SDClassName = R->getValueAsString("SDClass");
1114 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1115 NumResults = TypeProfile->getValueAsInt("NumResults");
1116 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001117
Chris Lattner8cab0212008-01-05 22:25:12 +00001118 // Parse the properties.
1119 Properties = 0;
1120 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1121 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1122 if (PropList[i]->getName() == "SDNPCommutative") {
1123 Properties |= 1 << SDNPCommutative;
1124 } else if (PropList[i]->getName() == "SDNPAssociative") {
1125 Properties |= 1 << SDNPAssociative;
1126 } else if (PropList[i]->getName() == "SDNPHasChain") {
1127 Properties |= 1 << SDNPHasChain;
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001128 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1129 Properties |= 1 << SDNPOutGlue;
1130 } else if (PropList[i]->getName() == "SDNPInGlue") {
1131 Properties |= 1 << SDNPInGlue;
1132 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1133 Properties |= 1 << SDNPOptInGlue;
Chris Lattnera348f552008-01-06 06:44:58 +00001134 } else if (PropList[i]->getName() == "SDNPMayStore") {
1135 Properties |= 1 << SDNPMayStore;
Chris Lattner1ca20682008-01-10 04:38:57 +00001136 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1137 Properties |= 1 << SDNPMayLoad;
Chris Lattner42c63ef2008-01-10 05:39:30 +00001138 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1139 Properties |= 1 << SDNPSideEffect;
Mon P Wang6a490372008-06-25 08:15:39 +00001140 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1141 Properties |= 1 << SDNPMemOperand;
Chris Lattner83aeaab2010-03-19 05:07:09 +00001142 } else if (PropList[i]->getName() == "SDNPVariadic") {
1143 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001144 } else {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001145 errs() << "Unknown SD Node property '" << PropList[i]->getName()
1146 << "' on node '" << R->getName() << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +00001147 exit(1);
1148 }
1149 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001150
1151
Chris Lattner8cab0212008-01-05 22:25:12 +00001152 // Parse the type constraints.
1153 std::vector<Record*> ConstraintList =
1154 TypeProfile->getValueAsListOfDefs("Constraints");
1155 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1156}
1157
Chris Lattner99e53b32010-02-28 00:22:30 +00001158/// getKnownType - If the type constraints on this node imply a fixed type
1159/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001160/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001161MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001162 unsigned NumResults = getNumResults();
1163 assert(NumResults <= 1 &&
1164 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001165 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001166
Chris Lattner99e53b32010-02-28 00:22:30 +00001167 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1168 // Make sure that this applies to the correct node result.
1169 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1170 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001171
Chris Lattner99e53b32010-02-28 00:22:30 +00001172 switch (TypeConstraints[i].ConstraintType) {
1173 default: break;
1174 case SDTypeConstraint::SDTCisVT:
1175 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1176 case SDTypeConstraint::SDTCisPtrTy:
1177 return MVT::iPTR;
1178 }
1179 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001180 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001181}
1182
Chris Lattner8cab0212008-01-05 22:25:12 +00001183//===----------------------------------------------------------------------===//
1184// TreePatternNode implementation
1185//
1186
1187TreePatternNode::~TreePatternNode() {
1188#if 0 // FIXME: implement refcounted tree nodes!
1189 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1190 delete getChild(i);
1191#endif
1192}
1193
Chris Lattnerf1447252010-03-19 21:37:09 +00001194static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1195 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001196 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001197 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001198
Chris Lattner2109cb42010-03-22 20:56:36 +00001199 if (Operator->isSubClassOf("Intrinsic"))
1200 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001201
Chris Lattnerf1447252010-03-19 21:37:09 +00001202 if (Operator->isSubClassOf("SDNode"))
1203 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001204
Chris Lattnerf1447252010-03-19 21:37:09 +00001205 if (Operator->isSubClassOf("PatFrag")) {
1206 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1207 // the forward reference case where one pattern fragment references another
1208 // before it is processed.
1209 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1210 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001211
Chris Lattnerf1447252010-03-19 21:37:09 +00001212 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001213 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001214 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001215 if (Tree)
1216 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1217 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001218 assert(Op && "Invalid Fragment");
1219 return GetNumNodeResults(Op, CDP);
1220 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001221
Chris Lattnerf1447252010-03-19 21:37:09 +00001222 if (Operator->isSubClassOf("Instruction")) {
1223 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001224
Craig Topper35b3dbc2015-03-05 07:17:52 +00001225 // FIXME: Should allow access to all the results here.
1226 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001227
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001228 // Add on one implicit def if it has a resolvable type.
1229 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1230 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001231 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001232 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001233
Chris Lattnerf1447252010-03-19 21:37:09 +00001234 if (Operator->isSubClassOf("SDNodeXForm"))
1235 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001236
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001237 if (Operator->isSubClassOf("ValueType"))
1238 return 1; // A type-cast of one result.
1239
Tim Northoverc807a172014-05-20 11:52:46 +00001240 if (Operator->isSubClassOf("ComplexPattern"))
1241 return 1;
1242
Chris Lattnerf1447252010-03-19 21:37:09 +00001243 Operator->dump();
1244 errs() << "Unhandled node in GetNumNodeResults\n";
1245 exit(1);
1246}
1247
1248void TreePatternNode::print(raw_ostream &OS) const {
1249 if (isLeaf())
1250 OS << *getLeafValue();
1251 else
1252 OS << '(' << getOperator()->getName();
1253
1254 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1255 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001256
1257 if (!isLeaf()) {
1258 if (getNumChildren() != 0) {
1259 OS << " ";
1260 getChild(0)->print(OS);
1261 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1262 OS << ", ";
1263 getChild(i)->print(OS);
1264 }
1265 }
1266 OS << ")";
1267 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001268
Dan Gohman6e979022008-10-15 06:17:21 +00001269 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner514e2922011-04-17 21:38:24 +00001270 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001271 if (TransformFn)
1272 OS << "<<X:" << TransformFn->getName() << ">>";
1273 if (!getName().empty())
1274 OS << ":$" << getName();
1275
1276}
1277void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001278 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001279}
1280
Scott Michel94420742008-03-05 17:49:05 +00001281/// isIsomorphicTo - Return true if this node is recursively
1282/// isomorphic to the specified node. For this comparison, the node's
1283/// entire state is considered. The assigned name is ignored, since
1284/// nodes with differing names are considered isomorphic. However, if
1285/// the assigned name is present in the dependent variable set, then
1286/// the assigned name is considered significant and the node is
1287/// isomorphic if the names match.
1288bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1289 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001290 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001291 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001292 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001293 getTransformFn() != N->getTransformFn())
1294 return false;
1295
1296 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001297 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1298 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001299 return ((DI->getDef() == NDI->getDef())
1300 && (DepVars.find(getName()) == DepVars.end()
1301 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001302 }
1303 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001304 return getLeafValue() == N->getLeafValue();
1305 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001306
Chris Lattner8cab0212008-01-05 22:25:12 +00001307 if (N->getOperator() != getOperator() ||
1308 N->getNumChildren() != getNumChildren()) return false;
1309 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001310 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001311 return false;
1312 return true;
1313}
1314
1315/// clone - Make a copy of this tree and all of its children.
1316///
1317TreePatternNode *TreePatternNode::clone() const {
1318 TreePatternNode *New;
1319 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001320 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001321 } else {
1322 std::vector<TreePatternNode*> CChildren;
1323 CChildren.reserve(Children.size());
1324 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1325 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001326 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001327 }
1328 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001329 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001330 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001331 New->setTransformFn(getTransformFn());
1332 return New;
1333}
1334
Chris Lattner53c39ba2010-02-14 22:22:58 +00001335/// RemoveAllTypes - Recursively strip all the types of this tree.
1336void TreePatternNode::RemoveAllTypes() {
Chris Lattnerf1447252010-03-19 21:37:09 +00001337 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1338 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner53c39ba2010-02-14 22:22:58 +00001339 if (isLeaf()) return;
1340 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1341 getChild(i)->RemoveAllTypes();
1342}
1343
1344
Chris Lattner8cab0212008-01-05 22:25:12 +00001345/// SubstituteFormalArguments - Replace the formal arguments in this tree
1346/// with actual values specified by ArgMap.
1347void TreePatternNode::
1348SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1349 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001350
Chris Lattner8cab0212008-01-05 22:25:12 +00001351 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1352 TreePatternNode *Child = getChild(i);
1353 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001354 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001355 // Note that, when substituting into an output pattern, Val might be an
1356 // UnsetInit.
1357 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1358 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001359 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001360 TreePatternNode *NewChild = ArgMap[Child->getName()];
1361 assert(NewChild && "Couldn't find formal argument!");
1362 assert((Child->getPredicateFns().empty() ||
1363 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1364 "Non-empty child predicate clobbered!");
1365 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001366 }
1367 } else {
1368 getChild(i)->SubstituteFormalArguments(ArgMap);
1369 }
1370 }
1371}
1372
1373
1374/// InlinePatternFragments - If this pattern refers to any pattern
1375/// fragments, inline them into place, giving us a pattern without any
1376/// PatFrag references.
1377TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001378 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001379 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001380
1381 if (isLeaf())
1382 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001383 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001384
Chris Lattner8cab0212008-01-05 22:25:12 +00001385 if (!Op->isSubClassOf("PatFrag")) {
1386 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001387 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1388 TreePatternNode *Child = getChild(i);
1389 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1390
1391 assert((Child->getPredicateFns().empty() ||
1392 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1393 "Non-empty child predicate clobbered!");
1394
1395 setChild(i, NewChild);
1396 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001397 return this;
1398 }
1399
1400 // Otherwise, we found a reference to a fragment. First, look up its
1401 // TreePattern record.
1402 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001403
Chris Lattner8cab0212008-01-05 22:25:12 +00001404 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001405 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001406 TP.error("'" + Op->getName() + "' fragment requires " +
1407 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001408 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001409 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001410
1411 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1412
Chris Lattner514e2922011-04-17 21:38:24 +00001413 TreePredicateFn PredFn(Frag);
1414 if (!PredFn.isAlwaysTrue())
1415 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001416
Chris Lattner8cab0212008-01-05 22:25:12 +00001417 // Resolve formal arguments to their actual value.
1418 if (Frag->getNumArgs()) {
1419 // Compute the map of formal to actual arguments.
1420 std::map<std::string, TreePatternNode*> ArgMap;
1421 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1422 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001423
Chris Lattner8cab0212008-01-05 22:25:12 +00001424 FragTree->SubstituteFormalArguments(ArgMap);
1425 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001426
Chris Lattner8cab0212008-01-05 22:25:12 +00001427 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001428 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1429 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001430
1431 // Transfer in the old predicates.
1432 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1433 FragTree->addPredicateFn(getPredicateFns()[i]);
1434
Chris Lattner8cab0212008-01-05 22:25:12 +00001435 // Get a new copy of this fragment to stitch into here.
1436 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001437
Chris Lattner2e253b42008-06-30 03:02:03 +00001438 // The fragment we inlined could have recursive inlining that is needed. See
1439 // if there are any pattern fragments in it and inline them as needed.
1440 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001441}
1442
1443/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001444/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001445/// references from the register file information, for example.
1446///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001447/// When Unnamed is set, return the type of a DAG operand with no name, such as
1448/// the F8RC register class argument in:
1449///
1450/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1451///
1452/// When Unnamed is false, return the type of a named DAG operand such as the
1453/// GPR:$src operand above.
1454///
Chris Lattnerf1447252010-03-19 21:37:09 +00001455static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001456 bool NotRegisters,
1457 bool Unnamed,
1458 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001459 // Check to see if this is a register operand.
1460 if (R->isSubClassOf("RegisterOperand")) {
1461 assert(ResNo == 0 && "Regoperand ref only has one result!");
1462 if (NotRegisters)
1463 return EEVT::TypeSet(); // Unknown.
1464 Record *RegClass = R->getValueAsDef("RegClass");
1465 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1466 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1467 }
1468
Chris Lattnercabe0372010-03-15 06:00:16 +00001469 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001470 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001471 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001472 // An unnamed register class represents itself as an i32 immediate, for
1473 // example on a COPY_TO_REGCLASS instruction.
1474 if (Unnamed)
1475 return EEVT::TypeSet(MVT::i32, TP);
1476
1477 // In a named operand, the register class provides the possible set of
1478 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001479 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001480 return EEVT::TypeSet(); // Unknown.
1481 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1482 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001483 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001484
Chris Lattner6070ee22010-03-23 23:50:31 +00001485 if (R->isSubClassOf("PatFrag")) {
1486 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001487 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001488 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001489 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001490
Chris Lattner6070ee22010-03-23 23:50:31 +00001491 if (R->isSubClassOf("Register")) {
1492 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001493 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001494 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001495 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001496 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001497 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001498
1499 if (R->isSubClassOf("SubRegIndex")) {
1500 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001501 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001502 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001503
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001504 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001505 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001506 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1507 //
1508 // (sext_inreg GPR:$src, i16)
1509 // ~~~
1510 if (Unnamed)
1511 return EEVT::TypeSet(MVT::Other, TP);
1512 // With a name, the ValueType simply provides the type of the named
1513 // variable.
1514 //
1515 // (sext_inreg i32:$src, i16)
1516 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001517 if (NotRegisters)
1518 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001519 return EEVT::TypeSet(getValueType(R), TP);
1520 }
1521
1522 if (R->isSubClassOf("CondCode")) {
1523 assert(ResNo == 0 && "This node only has one result!");
1524 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001525 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001526 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001527
Chris Lattner6070ee22010-03-23 23:50:31 +00001528 if (R->isSubClassOf("ComplexPattern")) {
1529 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001530 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001531 return EEVT::TypeSet(); // Unknown.
1532 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1533 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001534 }
1535 if (R->isSubClassOf("PointerLikeRegClass")) {
1536 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001537 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001538 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001539
Chris Lattner6070ee22010-03-23 23:50:31 +00001540 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1541 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001542 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001543 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001544 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001545
Tim Northoverc807a172014-05-20 11:52:46 +00001546 if (R->isSubClassOf("Operand"))
1547 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1548
Chris Lattner8cab0212008-01-05 22:25:12 +00001549 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001550 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001551}
1552
Chris Lattner89c65662008-01-06 05:36:50 +00001553
1554/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1555/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1556const CodeGenIntrinsic *TreePatternNode::
1557getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1558 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1559 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1560 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001561 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001562
Sean Silva88eb8dd2012-10-10 20:24:47 +00001563 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001564 return &CDP.getIntrinsicInfo(IID);
1565}
1566
Chris Lattner53c39ba2010-02-14 22:22:58 +00001567/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1568/// return the ComplexPattern information, otherwise return null.
1569const ComplexPattern *
1570TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001571 Record *Rec;
1572 if (isLeaf()) {
1573 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1574 if (!DI)
1575 return nullptr;
1576 Rec = DI->getDef();
1577 } else
1578 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001579
Tim Northoverc807a172014-05-20 11:52:46 +00001580 if (!Rec->isSubClassOf("ComplexPattern"))
1581 return nullptr;
1582 return &CGP.getComplexPattern(Rec);
1583}
1584
1585unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1586 // A ComplexPattern specifically declares how many results it fills in.
1587 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1588 return CP->getNumOperands();
1589
1590 // If MIOperandInfo is specified, that gives the count.
1591 if (isLeaf()) {
1592 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1593 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1594 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1595 if (MIOps->getNumArgs())
1596 return MIOps->getNumArgs();
1597 }
1598 }
1599
1600 // Otherwise there is just one result.
1601 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001602}
1603
1604/// NodeHasProperty - Return true if this node has the specified property.
1605bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001606 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001607 if (isLeaf()) {
1608 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1609 return CP->hasProperty(Property);
1610 return false;
1611 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001612
Chris Lattner53c39ba2010-02-14 22:22:58 +00001613 Record *Operator = getOperator();
1614 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001615
Chris Lattner53c39ba2010-02-14 22:22:58 +00001616 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1617}
1618
1619
1620
1621
1622/// TreeHasProperty - Return true if any node in this tree has the specified
1623/// property.
1624bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001625 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001626 if (NodeHasProperty(Property, CGP))
1627 return true;
1628 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1629 if (getChild(i)->TreeHasProperty(Property, CGP))
1630 return true;
1631 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001632}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001633
Evan Cheng49bad4c2008-06-16 20:29:38 +00001634/// isCommutativeIntrinsic - Return true if the node corresponds to a
1635/// commutative intrinsic.
1636bool
1637TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1638 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1639 return Int->isCommutative;
1640 return false;
1641}
1642
Matt Arsenaulteb492162014-11-02 23:46:51 +00001643static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1644 if (!N->isLeaf())
1645 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001646
Matt Arsenaulteb492162014-11-02 23:46:51 +00001647 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1648 if (DI && DI->getDef()->isSubClassOf(Class))
1649 return true;
1650
1651 return false;
1652}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001653
1654static void emitTooManyOperandsError(TreePattern &TP,
1655 StringRef InstName,
1656 unsigned Expected,
1657 unsigned Actual) {
1658 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1659 " operands but expected only " + Twine(Expected) + "!");
1660}
1661
1662static void emitTooFewOperandsError(TreePattern &TP,
1663 StringRef InstName,
1664 unsigned Actual) {
1665 TP.error("Instruction '" + InstName +
1666 "' expects more than the provided " + Twine(Actual) + " operands!");
1667}
1668
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001669/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001670/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001671/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001672bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001673 if (TP.hasError())
1674 return false;
1675
Chris Lattnerab3242f2008-01-06 01:10:31 +00001676 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001677 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001678 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001679 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001680 bool MadeChange = false;
1681 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1682 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001683 NotRegisters,
1684 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001685 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001686 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001687
Sean Silvafb509ed2012-10-10 20:24:43 +00001688 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001689 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001690
Chris Lattnerf1447252010-03-19 21:37:09 +00001691 // Int inits are always integers. :)
1692 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001693
Chris Lattnerf1447252010-03-19 21:37:09 +00001694 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001695 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001696
Chris Lattnerf1447252010-03-19 21:37:09 +00001697 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001698 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1699 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001700
Craig Topper95198f42013-09-25 06:37:18 +00001701 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001702 // Make sure that the value is representable for this type.
1703 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001704
Richard Smith228e6d42012-08-24 23:29:28 +00001705 // Check that the value doesn't use more bits than we have. It must either
1706 // be a sign- or zero-extended equivalent of the original.
1707 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1708 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001709 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001710
Richard Smith228e6d42012-08-24 23:29:28 +00001711 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001712 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001713 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001714 }
1715 return false;
1716 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001717
Chris Lattner8cab0212008-01-05 22:25:12 +00001718 // special handling for set, which isn't really an SDNode.
1719 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001720 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1721 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001722 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001723
Chris Lattnerf1447252010-03-19 21:37:09 +00001724 TreePatternNode *SetVal = getChild(NC-1);
1725 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1726
Elena Demikhovsky09954792015-03-01 08:23:41 +00001727 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001728 TreePatternNode *Child = getChild(i);
1729 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001730
Chris Lattner8cab0212008-01-05 22:25:12 +00001731 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001732 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1733 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001734 }
1735 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001736 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001737
Chris Lattner5c2182e2010-03-27 02:53:27 +00001738 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001739 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1740
Chris Lattner8cab0212008-01-05 22:25:12 +00001741 bool MadeChange = false;
1742 for (unsigned i = 0; i < getNumChildren(); ++i)
1743 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001744 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001745 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001746
Chris Lattneree820ac2010-02-23 05:51:07 +00001747 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001748 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001749
Chris Lattner8cab0212008-01-05 22:25:12 +00001750 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001751 unsigned NumRetVTs = Int->IS.RetVTs.size();
1752 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001753
Bill Wendling91821472008-11-13 09:08:33 +00001754 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001755 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001756
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001757 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001758 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001759 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001760 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001761 return false;
1762 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001763
1764 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001765 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001766
Chris Lattnerf1447252010-03-19 21:37:09 +00001767 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1768 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001769
Chris Lattnerf1447252010-03-19 21:37:09 +00001770 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1771 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1772 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001773 }
1774 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001775 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001776
Chris Lattneree820ac2010-02-23 05:51:07 +00001777 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001778 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001779
Chris Lattner135091b2010-03-28 08:48:47 +00001780 // Check that the number of operands is sane. Negative operands -> varargs.
1781 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001782 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001783 TP.error(getOperator()->getName() + " node requires exactly " +
1784 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001785 return false;
1786 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001787
Chris Lattner8cab0212008-01-05 22:25:12 +00001788 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1789 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1790 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001791 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001792 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001793
Chris Lattneree820ac2010-02-23 05:51:07 +00001794 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001795 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001796 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001797 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001798
Chris Lattnerd44966f2010-03-27 19:15:02 +00001799 bool MadeChange = false;
1800
1801 // Apply the result types to the node, these come from the things in the
1802 // (outs) list of the instruction.
Craig Topper35b3dbc2015-03-05 07:17:52 +00001803 // FIXME: Cap at one result so far.
1804 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001805 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1806 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001807
Chris Lattnerd44966f2010-03-27 19:15:02 +00001808 // If the instruction has implicit defs, we apply the first one as a result.
1809 // FIXME: This sucks, it should apply all implicit defs.
1810 if (!InstInfo.ImplicitDefs.empty()) {
1811 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001812
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001813 // FIXME: Generalize to multiple possible types and multiple possible
1814 // ImplicitDefs.
1815 MVT::SimpleValueType VT =
1816 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001817
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001818 if (VT != MVT::Other)
1819 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001820 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001821
Chris Lattnercabe0372010-03-15 06:00:16 +00001822 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1823 // be the same.
1824 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001825 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1826 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1827 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001828 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1829 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1830 // variadic.
1831
1832 unsigned NChild = getNumChildren();
1833 if (NChild < 3) {
1834 TP.error("REG_SEQUENCE requires at least 3 operands!");
1835 return false;
1836 }
1837
1838 if (NChild % 2 == 0) {
1839 TP.error("REG_SEQUENCE requires an odd number of operands!");
1840 return false;
1841 }
1842
1843 if (!isOperandClass(getChild(0), "RegisterClass")) {
1844 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1845 return false;
1846 }
1847
1848 for (unsigned I = 1; I < NChild; I += 2) {
1849 TreePatternNode *SubIdxChild = getChild(I + 1);
1850 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1851 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1852 itostr(I + 1) + "!");
1853 return false;
1854 }
1855 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001856 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001857
1858 unsigned ChildNo = 0;
1859 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1860 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001861
Chris Lattner8cab0212008-01-05 22:25:12 +00001862 // If the instruction expects a predicate or optional def operand, we
1863 // codegen this by setting the operand to it's default value if it has a
1864 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001865 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001866 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1867 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001868
Chris Lattner8cab0212008-01-05 22:25:12 +00001869 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001870 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001871 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001872 return false;
1873 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001874
Chris Lattner8cab0212008-01-05 22:25:12 +00001875 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001876 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001877
1878 // If the operand has sub-operands, they may be provided by distinct
1879 // child patterns, so attempt to match each sub-operand separately.
1880 if (OperandNode->isSubClassOf("Operand")) {
1881 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1882 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1883 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001884 // a single ComplexPattern-related Operand.
1885
1886 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001887 // Match first sub-operand against the child we already have.
1888 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1889 MadeChange |=
1890 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1891
1892 // And the remaining sub-operands against subsequent children.
1893 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1894 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001895 emitTooFewOperandsError(TP, getOperator()->getName(),
1896 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001897 return false;
1898 }
1899 Child = getChild(ChildNo++);
1900
1901 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1902 MadeChange |=
1903 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1904 }
1905 continue;
1906 }
1907 }
1908 }
1909
1910 // If we didn't match by pieces above, attempt to match the whole
1911 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001912 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001913 }
Christopher Lamba7312392008-03-11 09:33:47 +00001914
Matt Arsenaulteb492162014-11-02 23:46:51 +00001915 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001916 emitTooManyOperandsError(TP, getOperator()->getName(),
1917 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001918 return false;
1919 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001920
Ulrich Weigande618abd2013-03-19 19:51:09 +00001921 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1922 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001923 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001924 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001925
Tim Northoverc807a172014-05-20 11:52:46 +00001926 if (getOperator()->isSubClassOf("ComplexPattern")) {
1927 bool MadeChange = false;
1928
1929 for (unsigned i = 0; i < getNumChildren(); ++i)
1930 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1931
1932 return MadeChange;
1933 }
1934
Chris Lattneree820ac2010-02-23 05:51:07 +00001935 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001936
Chris Lattneree820ac2010-02-23 05:51:07 +00001937 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001938 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001939 TP.error("Node transform '" + getOperator()->getName() +
1940 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001941 return false;
1942 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001943
Chris Lattnercabe0372010-03-15 06:00:16 +00001944 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1945
Jim Grosbach65586fe2010-12-21 16:16:00 +00001946
Chris Lattneree820ac2010-02-23 05:51:07 +00001947 // If either the output or input of the xform does not have exact
1948 // type info. We assume they must be the same. Otherwise, it is perfectly
1949 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001950#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001951 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001952 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1953 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001954 return MadeChange;
1955 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001956#endif
1957 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001958}
1959
1960/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1961/// RHS of a commutative operation, not the on LHS.
1962static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1963 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1964 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001965 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001966 return true;
1967 return false;
1968}
1969
1970
1971/// canPatternMatch - If it is impossible for this pattern to match on this
1972/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001973/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001974/// that can never possibly work), and to prevent the pattern permuter from
1975/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001976bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001977 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001978 if (isLeaf()) return true;
1979
1980 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1981 if (!getChild(i)->canPatternMatch(Reason, CDP))
1982 return false;
1983
1984 // If this is an intrinsic, handle cases that would make it not match. For
1985 // example, if an operand is required to be an immediate.
1986 if (getOperator()->isSubClassOf("Intrinsic")) {
1987 // TODO:
1988 return true;
1989 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001990
Tim Northoverc807a172014-05-20 11:52:46 +00001991 if (getOperator()->isSubClassOf("ComplexPattern"))
1992 return true;
1993
Chris Lattner8cab0212008-01-05 22:25:12 +00001994 // If this node is a commutative operator, check that the LHS isn't an
1995 // immediate.
1996 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001997 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1998 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001999 // Scan all of the operands of the node and make sure that only the last one
2000 // is a constant node, unless the RHS also is.
2001 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00002002 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2003 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002004 if (OnlyOnRHSOfCommutative(getChild(i))) {
2005 Reason="Immediate value must be on the RHS of commutative operators!";
2006 return false;
2007 }
2008 }
2009 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002010
Chris Lattner8cab0212008-01-05 22:25:12 +00002011 return true;
2012}
2013
2014//===----------------------------------------------------------------------===//
2015// TreePattern implementation
2016//
2017
David Greeneaf8ee2c2011-07-29 22:43:06 +00002018TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002019 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2020 isInputPattern(isInput), HasError(false) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002021 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002022 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002023}
2024
David Greeneaf8ee2c2011-07-29 22:43:06 +00002025TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002026 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2027 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002028 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002029}
2030
David Blaikiecf195302014-11-17 22:55:41 +00002031TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002032 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2033 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00002034 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002035}
2036
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002037void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002038 if (HasError)
2039 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002040 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002041 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2042 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002043}
2044
Chris Lattnercabe0372010-03-15 06:00:16 +00002045void TreePattern::ComputeNamedNodes() {
2046 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002047 ComputeNamedNodes(Trees[i]);
Chris Lattnercabe0372010-03-15 06:00:16 +00002048}
2049
2050void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2051 if (!N->getName().empty())
2052 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002053
Chris Lattnercabe0372010-03-15 06:00:16 +00002054 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2055 ComputeNamedNodes(N->getChild(i));
2056}
2057
David Blaikiecf195302014-11-17 22:55:41 +00002058
2059TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002060 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002061 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002062
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002063 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002064 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002065 /// (foo GPR, imm) -> (foo GPR, (imm))
2066 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002067 return ParseTreePattern(
2068 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002069 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002070 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002071
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002072 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002073 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002074 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002075 if (OpName.empty())
2076 error("'node' argument requires a name to match with operand list");
2077 Args.push_back(OpName);
2078 }
2079
2080 Res->setName(OpName);
2081 return Res;
2082 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002083
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002084 // ?:$name or just $name.
2085 if (TheInit == UnsetInit::get()) {
2086 if (OpName.empty())
2087 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002088 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002089 Args.push_back(OpName);
2090 Res->setName(OpName);
2091 return Res;
2092 }
2093
Sean Silvafb509ed2012-10-10 20:24:43 +00002094 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002095 if (!OpName.empty())
2096 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002097 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002098 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002099
Sean Silvafb509ed2012-10-10 20:24:43 +00002100 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002101 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002102 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002103 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002104 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002105 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002106 }
2107
Sean Silvafb509ed2012-10-10 20:24:43 +00002108 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002109 if (!Dag) {
2110 TheInit->dump();
2111 error("Pattern has unexpected init kind!");
2112 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002113 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002114 if (!OpDef) error("Pattern has unexpected operator type!");
2115 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002116
Chris Lattner8cab0212008-01-05 22:25:12 +00002117 if (Operator->isSubClassOf("ValueType")) {
2118 // If the operator is a ValueType, then this must be "type cast" of a leaf
2119 // node.
2120 if (Dag->getNumArgs() != 1)
2121 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002122
David Blaikiecf195302014-11-17 22:55:41 +00002123 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002124
Chris Lattner8cab0212008-01-05 22:25:12 +00002125 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002126 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2127 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002128
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002129 if (!OpName.empty())
2130 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002131 return New;
2132 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002133
Chris Lattner8cab0212008-01-05 22:25:12 +00002134 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002135 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002136 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002137 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002138 !Operator->isSubClassOf("SDNodeXForm") &&
2139 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002140 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002141 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002142 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002143 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002144
Chris Lattner8cab0212008-01-05 22:25:12 +00002145 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002146 if (isInputPattern) {
2147 if (Operator->isSubClassOf("Instruction") ||
2148 Operator->isSubClassOf("SDNodeXForm"))
2149 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2150 } else {
2151 if (Operator->isSubClassOf("Intrinsic"))
2152 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002153
Chris Lattner2e9eae12010-03-28 06:57:56 +00002154 if (Operator->isSubClassOf("SDNode") &&
2155 Operator->getName() != "imm" &&
2156 Operator->getName() != "fpimm" &&
2157 Operator->getName() != "tglobaltlsaddr" &&
2158 Operator->getName() != "tconstpool" &&
2159 Operator->getName() != "tjumptable" &&
2160 Operator->getName() != "tframeindex" &&
2161 Operator->getName() != "texternalsym" &&
2162 Operator->getName() != "tblockaddress" &&
2163 Operator->getName() != "tglobaladdr" &&
2164 Operator->getName() != "bb" &&
2165 Operator->getName() != "vt")
2166 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2167 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002168
Chris Lattner8cab0212008-01-05 22:25:12 +00002169 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002170
2171 // Parse all the operands.
2172 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002173 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002174
Chris Lattner8cab0212008-01-05 22:25:12 +00002175 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002176 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002177 // convert the intrinsic name to a number.
2178 if (Operator->isSubClassOf("Intrinsic")) {
2179 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2180 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2181
2182 // If this intrinsic returns void, it must have side-effects and thus a
2183 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002184 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002185 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002186 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002187 // Has side-effects, requires chain.
2188 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002189 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002190 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002191
David Greenee32ebf22011-07-29 19:07:07 +00002192 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002193 Children.insert(Children.begin(), IIDNode);
2194 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002195
Tim Northoverc807a172014-05-20 11:52:46 +00002196 if (Operator->isSubClassOf("ComplexPattern")) {
2197 for (unsigned i = 0; i < Children.size(); ++i) {
2198 TreePatternNode *Child = Children[i];
2199
2200 if (Child->getName().empty())
2201 error("All arguments to a ComplexPattern must be named");
2202
2203 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2204 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2205 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2206 auto OperandId = std::make_pair(Operator, i);
2207 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2208 if (PrevOp != ComplexPatternOperands.end()) {
2209 if (PrevOp->getValue() != OperandId)
2210 error("All ComplexPattern operands must appear consistently: "
2211 "in the same order in just one ComplexPattern instance.");
2212 } else
2213 ComplexPatternOperands[Child->getName()] = OperandId;
2214 }
2215 }
2216
Chris Lattnerf1447252010-03-19 21:37:09 +00002217 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002218 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002219 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002220
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002221 if (!Dag->getName().empty()) {
2222 assert(Result->getName().empty());
2223 Result->setName(Dag->getName());
2224 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002225 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002226}
2227
Chris Lattnera787c9e2010-03-28 08:38:32 +00002228/// SimplifyTree - See if we can simplify this tree to eliminate something that
2229/// will never match in favor of something obvious that will. This is here
2230/// strictly as a convenience to target authors because it allows them to write
2231/// more type generic things and have useless type casts fold away.
2232///
2233/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002234static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002235 if (N->isLeaf())
2236 return false;
2237
2238 // If we have a bitconvert with a resolved type and if the source and
2239 // destination types are the same, then the bitconvert is useless, remove it.
2240 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002241 N->getExtType(0).isConcrete() &&
2242 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2243 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002244 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002245 SimplifyTree(N);
2246 return true;
2247 }
2248
2249 // Walk all children.
2250 bool MadeChange = false;
2251 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002252 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002253 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002254 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002255 }
2256 return MadeChange;
2257}
2258
2259
2260
Chris Lattner8cab0212008-01-05 22:25:12 +00002261/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002262/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002263/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002264bool TreePattern::
2265InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2266 if (NamedNodes.empty())
2267 ComputeNamedNodes();
2268
Chris Lattner8cab0212008-01-05 22:25:12 +00002269 bool MadeChange = true;
2270 while (MadeChange) {
2271 MadeChange = false;
Chris Lattnera787c9e2010-03-28 08:38:32 +00002272 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002273 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002274 MadeChange |= SimplifyTree(Trees[i]);
2275 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002276
2277 // If there are constraints on our named nodes, apply them.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002278 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattnercabe0372010-03-15 06:00:16 +00002279 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2280 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002281
Chris Lattnercabe0372010-03-15 06:00:16 +00002282 // If we have input named node types, propagate their types to the named
2283 // values here.
2284 if (InNamedTypes) {
Jim Grosbach37b80932014-07-09 18:55:49 +00002285 if (!InNamedTypes->count(I->getKey())) {
2286 error("Node '" + std::string(I->getKey()) +
2287 "' in output pattern but not input pattern");
2288 return true;
2289 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002290
2291 const SmallVectorImpl<TreePatternNode*> &InNodes =
2292 InNamedTypes->find(I->getKey())->second;
2293
2294 // The input types should be fully resolved by now.
2295 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2296 // If this node is a register class, and it is the root of the pattern
2297 // then we're mapping something onto an input register. We allow
2298 // changing the type of the input register in this case. This allows
2299 // us to match things like:
2300 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
David Blaikiecf195302014-11-17 22:55:41 +00002301 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002302 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002303 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2304 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002305 continue;
2306 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002307
Daniel Dunbard177edf2010-03-21 01:38:21 +00002308 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002309 InNodes[0]->getNumTypes() == 1 &&
2310 "FIXME: cannot name multiple result nodes yet");
2311 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2312 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002313 }
2314 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002315
Chris Lattnercabe0372010-03-15 06:00:16 +00002316 // If there are multiple nodes with the same name, they must all have the
2317 // same type.
2318 if (I->second.size() > 1) {
2319 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002320 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002321 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002322 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002323
Chris Lattnerf1447252010-03-19 21:37:09 +00002324 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2325 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002326 }
2327 }
2328 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002329 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002330
Chris Lattner8cab0212008-01-05 22:25:12 +00002331 bool HasUnresolvedTypes = false;
2332 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2333 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2334 return !HasUnresolvedTypes;
2335}
2336
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002337void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002338 OS << getRecord()->getName();
2339 if (!Args.empty()) {
2340 OS << "(" << Args[0];
2341 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2342 OS << ", " << Args[i];
2343 OS << ")";
2344 }
2345 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002346
Chris Lattner8cab0212008-01-05 22:25:12 +00002347 if (Trees.size() > 1)
2348 OS << "[\n";
2349 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2350 OS << "\t";
2351 Trees[i]->print(OS);
2352 OS << "\n";
2353 }
2354
2355 if (Trees.size() > 1)
2356 OS << "]\n";
2357}
2358
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002359void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002360
2361//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002362// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002363//
2364
Jim Grosbach65586fe2010-12-21 16:16:00 +00002365CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002366 Records(R), Target(R) {
2367
Dale Johannesenb842d522009-02-05 01:49:45 +00002368 Intrinsics = LoadIntrinsics(Records, false);
2369 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002370 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002371 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002372 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002373 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002374 ParseDefaultOperands();
2375 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002376 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002377 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002378
Chris Lattner8cab0212008-01-05 22:25:12 +00002379 // Generate variants. For example, commutative patterns can match
2380 // multiple ways. Add them to PatternsToMatch as well.
2381 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002382
2383 // Infer instruction flags. For example, we can detect loads,
2384 // stores, and side effects in many cases by examining an
2385 // instruction's pattern.
2386 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002387
2388 // Verify that instruction flags match the patterns.
2389 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002390}
2391
Chris Lattnerab3242f2008-01-06 01:10:31 +00002392Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002393 Record *N = Records.getDef(Name);
2394 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002395 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +00002396 exit(1);
2397 }
2398 return N;
2399}
2400
2401// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002402void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002403 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2404 while (!Nodes.empty()) {
2405 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2406 Nodes.pop_back();
2407 }
2408
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002409 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002410 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2411 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2412 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2413}
2414
2415/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2416/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002417void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002418 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2419 while (!Xforms.empty()) {
2420 Record *XFormNode = Xforms.back();
2421 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002422 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002423 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002424
2425 Xforms.pop_back();
2426 }
2427}
2428
Chris Lattnerab3242f2008-01-06 01:10:31 +00002429void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002430 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2431 while (!AMs.empty()) {
2432 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2433 AMs.pop_back();
2434 }
2435}
2436
2437
2438/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2439/// file, building up the PatternFragments map. After we've collected them all,
2440/// inline fragments together as necessary, so that there are no references left
2441/// inside a pattern fragment to a pattern fragment.
2442///
Hal Finkel2756dc12014-02-28 00:26:56 +00002443void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002444 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002445
Chris Lattnere7170df2008-01-05 22:43:57 +00002446 // First step, parse all of the fragments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002447 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002448 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2449 continue;
2450
David Greeneaf8ee2c2011-07-29 22:43:06 +00002451 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002452 TreePattern *P =
David Blaikie3c6ca232014-11-13 21:40:02 +00002453 (PatternFragments[Fragments[i]] = llvm::make_unique<TreePattern>(
2454 Fragments[i], Tree, !Fragments[i]->isSubClassOf("OutPatFrag"),
2455 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002456
Chris Lattnere7170df2008-01-05 22:43:57 +00002457 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002458 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002459 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002460
Chris Lattnere7170df2008-01-05 22:43:57 +00002461 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002462 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002463
Chris Lattner8cab0212008-01-05 22:25:12 +00002464 // Parse the operands list.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002465 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002466 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002467 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002468 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002469 if (!OpsOp ||
2470 (OpsOp->getDef()->getName() != "ops" &&
2471 OpsOp->getDef()->getName() != "outs" &&
2472 OpsOp->getDef()->getName() != "ins"))
2473 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002474
2475 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002476 Args.clear();
2477 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002478 if (!isa<DefInit>(OpsList->getArg(j)) ||
2479 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002480 P->error("Operands list should all be 'node' values.");
2481 if (OpsList->getArgName(j).empty())
2482 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002483 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002484 P->error("'" + OpsList->getArgName(j) +
2485 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002486 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002487 Args.push_back(OpsList->getArgName(j));
2488 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002489
Chris Lattnere7170df2008-01-05 22:43:57 +00002490 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002491 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002492 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002493
Chris Lattnere7170df2008-01-05 22:43:57 +00002494 // If there is a code init for this fragment, keep track of the fact that
2495 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002496 TreePredicateFn PredFn(P);
2497 if (!PredFn.isAlwaysTrue())
2498 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002499
Chris Lattner8cab0212008-01-05 22:25:12 +00002500 // If there is a node transformation corresponding to this, keep track of
2501 // it.
2502 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2503 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2504 P->getOnlyTree()->setTransformFn(Transform);
2505 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002506
Chris Lattner8cab0212008-01-05 22:25:12 +00002507 // Now that we've parsed all of the tree fragments, do a closure on them so
2508 // that there are not references to PatFrags left inside of them.
Chris Lattner2e253b42008-06-30 03:02:03 +00002509 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002510 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2511 continue;
2512
David Blaikie3c6ca232014-11-13 21:40:02 +00002513 TreePattern &ThePat = *PatternFragments[Fragments[i]];
2514 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002515
Chris Lattner8cab0212008-01-05 22:25:12 +00002516 // Infer as many types as possible. Don't worry about it if we don't infer
2517 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002518 ThePat.InferAllTypes();
2519 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002520
Chris Lattner8cab0212008-01-05 22:25:12 +00002521 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002522 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002523 }
2524}
2525
Chris Lattnerab3242f2008-01-06 01:10:31 +00002526void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002527 std::vector<Record*> DefaultOps;
2528 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002529
2530 // Find some SDNode.
2531 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002532 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002533
Tom Stellardb7246a72012-09-06 14:15:52 +00002534 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2535 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002536
Tom Stellardb7246a72012-09-06 14:15:52 +00002537 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2538 // SomeSDnode so that we can parse this.
2539 std::vector<std::pair<Init*, std::string> > Ops;
2540 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2541 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2542 DefaultInfo->getArgName(op)));
2543 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002544
Tom Stellardb7246a72012-09-06 14:15:52 +00002545 // Create a TreePattern to parse this.
2546 TreePattern P(DefaultOps[i], DI, false, *this);
2547 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002548
Tom Stellardb7246a72012-09-06 14:15:52 +00002549 // Copy the operands over into a DAGDefaultOperand.
2550 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002551
Tom Stellardb7246a72012-09-06 14:15:52 +00002552 TreePatternNode *T = P.getTree(0);
2553 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2554 TreePatternNode *TPN = T->getChild(op);
2555 while (TPN->ApplyTypeConstraints(P, false))
2556 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002557
Tom Stellardb7246a72012-09-06 14:15:52 +00002558 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002559 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2560 DefaultOps[i]->getName() +
2561 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002562 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002563 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002564 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002565
2566 // Insert it into the DefaultOperands map so we can find it later.
2567 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002568 }
2569}
2570
2571/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2572/// instruction input. Return true if this is a real use.
2573static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002574 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002575 // No name -> not interesting.
2576 if (Pat->getName().empty()) {
2577 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002578 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002579 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2580 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002581 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002582 }
2583 return false;
2584 }
2585
2586 Record *Rec;
2587 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002588 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002589 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2590 Rec = DI->getDef();
2591 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002592 Rec = Pat->getOperator();
2593 }
2594
2595 // SRCVALUE nodes are ignored.
2596 if (Rec->getName() == "srcvalue")
2597 return false;
2598
2599 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2600 if (!Slot) {
2601 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002602 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002603 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002604 Record *SlotRec;
2605 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002606 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002607 } else {
2608 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2609 SlotRec = Slot->getOperator();
2610 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002611
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002612 // Ensure that the inputs agree if we've already seen this input.
2613 if (Rec != SlotRec)
2614 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002615 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002616 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002617 return true;
2618}
2619
2620/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2621/// part of "I", the instruction), computing the set of inputs and outputs of
2622/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002623void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002624FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2625 std::map<std::string, TreePatternNode*> &InstInputs,
2626 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002627 std::vector<Record*> &InstImpResults) {
2628 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002629 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002630 if (!isUse && Pat->getTransformFn())
2631 I->error("Cannot specify a transform function for a non-input value!");
2632 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002633 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002634
Chris Lattnerf2d70992010-02-17 06:53:36 +00002635 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002636 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2637 TreePatternNode *Dest = Pat->getChild(i);
2638 if (!Dest->isLeaf())
2639 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002640
Sean Silvafb509ed2012-10-10 20:24:43 +00002641 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002642 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2643 I->error("implicitly defined value should be a register!");
2644 InstImpResults.push_back(Val->getDef());
2645 }
2646 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002647 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002648
Chris Lattnerf2d70992010-02-17 06:53:36 +00002649 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002650 // If this is not a set, verify that the children nodes are not void typed,
2651 // and recurse.
2652 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002653 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002654 I->error("Cannot have void nodes inside of patterns!");
2655 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002656 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002657 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002658
Chris Lattner8cab0212008-01-05 22:25:12 +00002659 // If this is a non-leaf node with no children, treat it basically as if
2660 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002661 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002662
Chris Lattner8cab0212008-01-05 22:25:12 +00002663 if (!isUse && Pat->getTransformFn())
2664 I->error("Cannot specify a transform function for a non-input value!");
2665 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002666 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002667
Chris Lattner8cab0212008-01-05 22:25:12 +00002668 // Otherwise, this is a set, validate and collect instruction results.
2669 if (Pat->getNumChildren() == 0)
2670 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002671
Chris Lattner8cab0212008-01-05 22:25:12 +00002672 if (Pat->getTransformFn())
2673 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002674
Chris Lattner8cab0212008-01-05 22:25:12 +00002675 // Check the set destinations.
2676 unsigned NumDests = Pat->getNumChildren()-1;
2677 for (unsigned i = 0; i != NumDests; ++i) {
2678 TreePatternNode *Dest = Pat->getChild(i);
2679 if (!Dest->isLeaf())
2680 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002681
Sean Silvafb509ed2012-10-10 20:24:43 +00002682 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002683 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002684 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002685 continue;
2686 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002687
2688 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002689 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002690 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002691 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002692 if (Dest->getName().empty())
2693 I->error("set destination must have a name!");
2694 if (InstResults.count(Dest->getName()))
2695 I->error("cannot set '" + Dest->getName() +"' multiple times");
2696 InstResults[Dest->getName()] = Dest;
2697 } else if (Val->getDef()->isSubClassOf("Register")) {
2698 InstImpResults.push_back(Val->getDef());
2699 } else {
2700 I->error("set destination should be a register!");
2701 }
2702 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002703
Chris Lattner8cab0212008-01-05 22:25:12 +00002704 // Verify and collect info from the computation.
2705 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002706 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002707}
2708
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002709//===----------------------------------------------------------------------===//
2710// Instruction Analysis
2711//===----------------------------------------------------------------------===//
2712
2713class InstAnalyzer {
2714 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002715public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002716 bool hasSideEffects;
2717 bool mayStore;
2718 bool mayLoad;
2719 bool isBitcast;
2720 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002721
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002722 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2723 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2724 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002725
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002726 void Analyze(const TreePattern *Pat) {
2727 // Assume only the first tree is the pattern. The others are clobber nodes.
2728 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002729 }
2730
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002731 void Analyze(const PatternToMatch *Pat) {
2732 AnalyzeNode(Pat->getSrcPattern());
2733 }
2734
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002735private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002736 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002737 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002738 return false;
2739
2740 if (N->getNumChildren() != 2)
2741 return false;
2742
2743 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002744 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002745 return false;
2746
2747 const TreePatternNode *N1 = N->getChild(1);
2748 if (N1->isLeaf())
2749 return false;
2750 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2751 return false;
2752
2753 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2754 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2755 return false;
2756 return OpInfo.getEnumName() == "ISD::BITCAST";
2757 }
2758
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002759public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002760 void AnalyzeNode(const TreePatternNode *N) {
2761 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002762 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002763 Record *LeafRec = DI->getDef();
2764 // Handle ComplexPattern leaves.
2765 if (LeafRec->isSubClassOf("ComplexPattern")) {
2766 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2767 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2768 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002769 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002770 }
2771 }
2772 return;
2773 }
2774
2775 // Analyze children.
2776 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2777 AnalyzeNode(N->getChild(i));
2778
2779 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002780 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002781 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002782 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002783 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002784
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002785 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002786 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2787 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2788 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2789 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002790
2791 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2792 // If this is an intrinsic, analyze it.
2793 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2794 mayLoad = true;// These may load memory.
2795
Dan Gohmanddb2d652010-08-05 23:36:21 +00002796 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002797 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2798
Dan Gohmanddb2d652010-08-05 23:36:21 +00002799 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002800 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002801 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002802 }
2803 }
2804
2805};
2806
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002807static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002808 const InstAnalyzer &PatInfo,
2809 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002810 bool Error = false;
2811
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002812 // Remember where InstInfo got its flags.
2813 if (InstInfo.hasUndefFlags())
2814 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002815
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002816 // Check explicitly set flags for consistency.
2817 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2818 !InstInfo.hasSideEffects_Unset) {
2819 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2820 // the pattern has no side effects. That could be useful for div/rem
2821 // instructions that may trap.
2822 if (!InstInfo.hasSideEffects) {
2823 Error = true;
2824 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2825 Twine(InstInfo.hasSideEffects));
2826 }
2827 }
2828
2829 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2830 Error = true;
2831 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2832 Twine(InstInfo.mayStore));
2833 }
2834
2835 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2836 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2837 // Some targets translate imediates to loads.
2838 if (!InstInfo.mayLoad) {
2839 Error = true;
2840 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2841 Twine(InstInfo.mayLoad));
2842 }
2843 }
2844
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002845 // Transfer inferred flags.
2846 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2847 InstInfo.mayStore |= PatInfo.mayStore;
2848 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002849
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002850 // These flags are silently added without any verification.
2851 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002852
2853 // Don't infer isVariadic. This flag means something different on SDNodes and
2854 // instructions. For example, a CALL SDNode is variadic because it has the
2855 // call arguments as operands, but a CALL instruction is not variadic - it
2856 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002857
2858 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002859}
2860
Jim Grosbach514410b2012-07-17 00:47:06 +00002861/// hasNullFragReference - Return true if the DAG has any reference to the
2862/// null_frag operator.
2863static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002864 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002865 if (!OpDef) return false;
2866 Record *Operator = OpDef->getDef();
2867
2868 // If this is the null fragment, return true.
2869 if (Operator->getName() == "null_frag") return true;
2870 // If any of the arguments reference the null fragment, return true.
2871 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002872 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002873 if (Arg && hasNullFragReference(Arg))
2874 return true;
2875 }
2876
2877 return false;
2878}
2879
2880/// hasNullFragReference - Return true if any DAG in the list references
2881/// the null_frag operator.
2882static bool hasNullFragReference(ListInit *LI) {
2883 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002884 DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002885 assert(DI && "non-dag in an instruction Pattern list?!");
2886 if (hasNullFragReference(DI))
2887 return true;
2888 }
2889 return false;
2890}
2891
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002892/// Get all the instructions in a tree.
2893static void
2894getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2895 if (Tree->isLeaf())
2896 return;
2897 if (Tree->getOperator()->isSubClassOf("Instruction"))
2898 Instrs.push_back(Tree->getOperator());
2899 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2900 getInstructionsInTree(Tree->getChild(i), Instrs);
2901}
2902
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002903/// Check the class of a pattern leaf node against the instruction operand it
2904/// represents.
2905static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2906 Record *Leaf) {
2907 if (OI.Rec == Leaf)
2908 return true;
2909
2910 // Allow direct value types to be used in instruction set patterns.
2911 // The type will be checked later.
2912 if (Leaf->isSubClassOf("ValueType"))
2913 return true;
2914
2915 // Patterns can also be ComplexPattern instances.
2916 if (Leaf->isSubClassOf("ComplexPattern"))
2917 return true;
2918
2919 return false;
2920}
2921
Ahmed Bougacha14107512013-10-28 18:07:21 +00002922const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2923 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002924
Craig Topper0d1fb902015-03-10 03:25:04 +00002925 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002926
Craig Topper0d1fb902015-03-10 03:25:04 +00002927 // Parse the instruction.
2928 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2929 // Inline pattern fragments into it.
2930 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002931
Craig Topper0d1fb902015-03-10 03:25:04 +00002932 // Infer as many types as possible. If we cannot infer all of them, we can
2933 // never do anything with this instruction pattern: report it to the user.
2934 if (!I->InferAllTypes())
2935 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002936
Craig Topper0d1fb902015-03-10 03:25:04 +00002937 // InstInputs - Keep track of all of the inputs of the instruction, along
2938 // with the record they are declared as.
2939 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002940
Craig Topper0d1fb902015-03-10 03:25:04 +00002941 // InstResults - Keep track of all the virtual registers that are 'set'
2942 // in the instruction, including what reg class they are.
2943 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002944
Craig Topper0d1fb902015-03-10 03:25:04 +00002945 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002946
Craig Topper0d1fb902015-03-10 03:25:04 +00002947 // Verify that the top-level forms in the instruction are of void type, and
2948 // fill in the InstResults map.
2949 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2950 TreePatternNode *Pat = I->getTree(j);
2951 if (Pat->getNumTypes() != 0)
2952 I->error("Top-level forms in instruction pattern should have"
2953 " void types");
Chris Lattner8cab0212008-01-05 22:25:12 +00002954
Craig Topper0d1fb902015-03-10 03:25:04 +00002955 // Find inputs and outputs, and verify the structure of the uses/defs.
2956 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2957 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002958 }
2959
Craig Topper0d1fb902015-03-10 03:25:04 +00002960 // Now that we have inputs and outputs of the pattern, inspect the operands
2961 // list for the instruction. This determines the order that operands are
2962 // added to the machine instruction the node corresponds to.
2963 unsigned NumResults = InstResults.size();
2964
2965 // Parse the operands list from the (ops) list, validating it.
2966 assert(I->getArgList().empty() && "Args list should still be empty here!");
2967
2968 // Check that all of the results occur first in the list.
2969 std::vector<Record*> Results;
2970 TreePatternNode *Res0Node = nullptr;
2971 for (unsigned i = 0; i != NumResults; ++i) {
2972 if (i == CGI.Operands.size())
2973 I->error("'" + InstResults.begin()->first +
2974 "' set but does not appear in operand list!");
2975 const std::string &OpName = CGI.Operands[i].Name;
2976
2977 // Check that it exists in InstResults.
2978 TreePatternNode *RNode = InstResults[OpName];
2979 if (!RNode)
2980 I->error("Operand $" + OpName + " does not exist in operand list!");
2981
2982 if (i == 0)
2983 Res0Node = RNode;
2984 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2985 if (!R)
2986 I->error("Operand $" + OpName + " should be a set destination: all "
2987 "outputs must occur before inputs in operand list!");
2988
2989 if (!checkOperandClass(CGI.Operands[i], R))
2990 I->error("Operand $" + OpName + " class mismatch!");
2991
2992 // Remember the return type.
2993 Results.push_back(CGI.Operands[i].Rec);
2994
2995 // Okay, this one checks out.
2996 InstResults.erase(OpName);
2997 }
2998
2999 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3000 // the copy while we're checking the inputs.
3001 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3002
3003 std::vector<TreePatternNode*> ResultNodeOperands;
3004 std::vector<Record*> Operands;
3005 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3006 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3007 const std::string &OpName = Op.Name;
3008 if (OpName.empty())
3009 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3010
3011 if (!InstInputsCheck.count(OpName)) {
3012 // If this is an operand with a DefaultOps set filled in, we can ignore
3013 // this. When we codegen it, we will do so as always executed.
3014 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3015 // Does it have a non-empty DefaultOps field? If so, ignore this
3016 // operand.
3017 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3018 continue;
3019 }
3020 I->error("Operand $" + OpName +
3021 " does not appear in the instruction pattern");
3022 }
3023 TreePatternNode *InVal = InstInputsCheck[OpName];
3024 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3025
3026 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3027 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3028 if (!checkOperandClass(Op, InRec))
3029 I->error("Operand $" + OpName + "'s register class disagrees"
3030 " between the operand and pattern");
3031 }
3032 Operands.push_back(Op.Rec);
3033
3034 // Construct the result for the dest-pattern operand list.
3035 TreePatternNode *OpNode = InVal->clone();
3036
3037 // No predicate is useful on the result.
3038 OpNode->clearPredicateFns();
3039
3040 // Promote the xform function to be an explicit node if set.
3041 if (Record *Xform = OpNode->getTransformFn()) {
3042 OpNode->setTransformFn(nullptr);
3043 std::vector<TreePatternNode*> Children;
3044 Children.push_back(OpNode);
3045 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3046 }
3047
3048 ResultNodeOperands.push_back(OpNode);
3049 }
3050
3051 if (!InstInputsCheck.empty())
3052 I->error("Input operand $" + InstInputsCheck.begin()->first +
3053 " occurs in pattern but not in operands list!");
3054
3055 TreePatternNode *ResultPattern =
3056 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3057 GetNumNodeResults(I->getRecord(), *this));
3058 // Copy fully inferred output node type to instruction result pattern.
3059 for (unsigned i = 0; i != NumResults; ++i)
3060 ResultPattern->setType(i, Res0Node->getExtType(i));
3061
3062 // Create and insert the instruction.
3063 // FIXME: InstImpResults should not be part of DAGInstruction.
3064 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3065 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3066
3067 // Use a temporary tree pattern to infer all types and make sure that the
3068 // constructed result is correct. This depends on the instruction already
3069 // being inserted into the DAGInsts map.
3070 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3071 Temp.InferAllTypes(&I->getNamedNodesMap());
3072
3073 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3074 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3075
3076 return TheInsertedInst;
3077}
3078
Ahmed Bougacha14107512013-10-28 18:07:21 +00003079/// ParseInstructions - Parse all of the instructions, inlining and resolving
3080/// any fragments involved. This populates the Instructions list with fully
3081/// resolved instructions.
3082void CodeGenDAGPatterns::ParseInstructions() {
3083 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3084
3085 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Craig Topper24064772014-04-15 07:20:03 +00003086 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003087
3088 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
3089 LI = Instrs[i]->getValueAsListInit("Pattern");
3090
3091 // If there is no pattern, only collect minimal information about the
3092 // instruction for its operand list. We have to assume that there is one
3093 // result, as we have no detailed info. A pattern which references the
3094 // null_frag operator is as-if no pattern were specified. Normally this
3095 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3096 // null_frag.
3097 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
3098 std::vector<Record*> Results;
3099 std::vector<Record*> Operands;
3100
3101 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3102
3103 if (InstInfo.Operands.size() != 0) {
3104 if (InstInfo.Operands.NumDefs == 0) {
3105 // These produce no results
3106 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
3107 Operands.push_back(InstInfo.Operands[j].Rec);
3108 } else {
3109 // Assume the first operand is the result.
3110 Results.push_back(InstInfo.Operands[0].Rec);
3111
3112 // The rest are inputs.
3113 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
3114 Operands.push_back(InstInfo.Operands[j].Rec);
3115 }
3116 }
3117
3118 // Create and insert the instruction.
3119 std::vector<Record*> ImpResults;
3120 Instructions.insert(std::make_pair(Instrs[i],
Craig Topper24064772014-04-15 07:20:03 +00003121 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003122 continue; // no pattern.
3123 }
3124
3125 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
3126 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3127
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003128 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003129 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003130 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003131
Chris Lattner8cab0212008-01-05 22:25:12 +00003132 // If we can, convert the instructions to be patterns that are matched!
Sean Silvaa4e2c5f2012-09-19 01:47:00 +00003133 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
Benjamin Kramerc2dbd5d2009-08-23 10:39:21 +00003134 Instructions.begin(),
Chris Lattner8cab0212008-01-05 22:25:12 +00003135 E = Instructions.end(); II != E; ++II) {
3136 DAGInstruction &TheInst = II->second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003137 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003138 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003139
3140 // FIXME: Assume only the first tree is the pattern. The others are clobber
3141 // nodes.
3142 TreePatternNode *Pattern = I->getTree(0);
3143 TreePatternNode *SrcPattern;
3144 if (Pattern->getOperator()->getName() == "set") {
3145 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3146 } else{
3147 // Not a set (store or something?)
3148 SrcPattern = Pattern;
3149 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003150
Chris Lattner8cab0212008-01-05 22:25:12 +00003151 Record *Instr = II->first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003152 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003153 PatternToMatch(Instr,
3154 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003155 SrcPattern,
3156 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003157 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003158 Instr->getValueAsInt("AddedComplexity"),
3159 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003160 }
3161}
3162
Chris Lattnera7722b62010-02-23 06:55:24 +00003163
3164typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3165
Jim Grosbach65586fe2010-12-21 16:16:00 +00003166static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003167 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003168 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003169 if (!P->getName().empty()) {
3170 NameRecord &Rec = Names[P->getName()];
3171 // If this is the first instance of the name, remember the node.
3172 if (Rec.second++ == 0)
3173 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003174 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003175 PatternTop->error("repetition of value: $" + P->getName() +
3176 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003177 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003178
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003179 if (!P->isLeaf()) {
3180 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003181 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003182 }
3183}
3184
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003185void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003186 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003187 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003188 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003189 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3190 PrintWarning(Pattern->getRecord()->getLoc(),
3191 Twine("Pattern can never match: ") + Reason);
3192 return;
3193 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003194
Chris Lattner1e634e32010-03-01 22:29:19 +00003195 // If the source pattern's root is a complex pattern, that complex pattern
3196 // must specify the nodes it can potentially match.
3197 if (const ComplexPattern *CP =
3198 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3199 if (CP->getRootNodes().empty())
3200 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3201 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003202
3203
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003204 // Find all of the named values in the input and output, ensure they have the
3205 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003206 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003207 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3208 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003209
3210 // Scan all of the named values in the destination pattern, rejecting them if
3211 // they don't exist in the input pattern.
Chris Lattnera7722b62010-02-23 06:55:24 +00003212 for (std::map<std::string, NameRecord>::iterator
Chris Lattner4b9225b2010-02-23 07:50:58 +00003213 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Craig Topper24064772014-04-15 07:20:03 +00003214 if (SrcNames[I->first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003215 Pattern->error("Pattern has input without matching name in output: $" +
3216 I->first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003217 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003218
Chris Lattnera7722b62010-02-23 06:55:24 +00003219 // Scan all of the named values in the source pattern, rejecting them if the
3220 // name isn't used in the dest, and isn't used to tie two values together.
3221 for (std::map<std::string, NameRecord>::iterator
3222 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
Craig Topper24064772014-04-15 07:20:03 +00003223 if (DstNames[I->first].first == nullptr && SrcNames[I->first].second == 1)
Chris Lattnera7722b62010-02-23 06:55:24 +00003224 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003225
Chris Lattner0c0baa92010-02-23 06:16:51 +00003226 PatternsToMatch.push_back(PTM);
3227}
3228
3229
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003230
3231void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003232 const std::vector<const CodeGenInstruction*> &Instructions =
3233 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003234
3235 // First try to infer flags from the primary instruction pattern, if any.
3236 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003237 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003238 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3239 CodeGenInstruction &InstInfo =
3240 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003241
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003242 // Get the primary instruction pattern.
3243 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3244 if (!Pattern) {
3245 if (InstInfo.hasUndefFlags())
3246 Revisit.push_back(&InstInfo);
3247 continue;
3248 }
3249 InstAnalyzer PatInfo(*this);
3250 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003251 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003252 }
3253
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003254 // Second, look for single-instruction patterns defined outside the
3255 // instruction.
3256 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3257 const PatternToMatch &PTM = *I;
3258
3259 // We can only infer from single-instruction patterns, otherwise we won't
3260 // know which instruction should get the flags.
3261 SmallVector<Record*, 8> PatInstrs;
3262 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3263 if (PatInstrs.size() != 1)
3264 continue;
3265
3266 // Get the single instruction.
3267 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3268
3269 // Only infer properties from the first pattern. We'll verify the others.
3270 if (InstInfo.InferredFrom)
3271 continue;
3272
3273 InstAnalyzer PatInfo(*this);
3274 PatInfo.Analyze(&PTM);
3275 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3276 }
3277
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003278 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003279 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003280
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003281 // Revisit instructions with undefined flags and no pattern.
3282 if (Target.guessInstructionProperties()) {
3283 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3284 CodeGenInstruction &InstInfo = *Revisit[i];
3285 if (InstInfo.InferredFrom)
3286 continue;
3287 // The mayLoad and mayStore flags default to false.
3288 // Conservatively assume hasSideEffects if it wasn't explicit.
3289 if (InstInfo.hasSideEffects_Unset)
3290 InstInfo.hasSideEffects = true;
3291 }
3292 return;
3293 }
3294
3295 // Complain about any flags that are still undefined.
3296 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3297 CodeGenInstruction &InstInfo = *Revisit[i];
3298 if (InstInfo.InferredFrom)
3299 continue;
3300 if (InstInfo.hasSideEffects_Unset)
3301 PrintError(InstInfo.TheDef->getLoc(),
3302 "Can't infer hasSideEffects from patterns");
3303 if (InstInfo.mayStore_Unset)
3304 PrintError(InstInfo.TheDef->getLoc(),
3305 "Can't infer mayStore from patterns");
3306 if (InstInfo.mayLoad_Unset)
3307 PrintError(InstInfo.TheDef->getLoc(),
3308 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003309 }
3310}
3311
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003312
3313/// Verify instruction flags against pattern node properties.
3314void CodeGenDAGPatterns::VerifyInstructionFlags() {
3315 unsigned Errors = 0;
3316 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3317 const PatternToMatch &PTM = *I;
3318 SmallVector<Record*, 8> Instrs;
3319 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3320 if (Instrs.empty())
3321 continue;
3322
3323 // Count the number of instructions with each flag set.
3324 unsigned NumSideEffects = 0;
3325 unsigned NumStores = 0;
3326 unsigned NumLoads = 0;
3327 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3328 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3329 NumSideEffects += InstInfo.hasSideEffects;
3330 NumStores += InstInfo.mayStore;
3331 NumLoads += InstInfo.mayLoad;
3332 }
3333
3334 // Analyze the source pattern.
3335 InstAnalyzer PatInfo(*this);
3336 PatInfo.Analyze(&PTM);
3337
3338 // Collect error messages.
3339 SmallVector<std::string, 4> Msgs;
3340
3341 // Check for missing flags in the output.
3342 // Permit extra flags for now at least.
3343 if (PatInfo.hasSideEffects && !NumSideEffects)
3344 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3345
3346 // Don't verify store flags on instructions with side effects. At least for
3347 // intrinsics, side effects implies mayStore.
3348 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3349 Msgs.push_back("pattern may store, but mayStore isn't set");
3350
3351 // Similarly, mayStore implies mayLoad on intrinsics.
3352 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3353 Msgs.push_back("pattern may load, but mayLoad isn't set");
3354
3355 // Print error messages.
3356 if (Msgs.empty())
3357 continue;
3358 ++Errors;
3359
3360 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3361 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3362 (Instrs.size() == 1 ?
3363 "instruction" : "output instructions"));
3364 // Provide the location of the relevant instruction definitions.
3365 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3366 if (Instrs[i] != PTM.getSrcRecord())
3367 PrintError(Instrs[i]->getLoc(), "defined here");
3368 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3369 if (InstInfo.InferredFrom &&
3370 InstInfo.InferredFrom != InstInfo.TheDef &&
3371 InstInfo.InferredFrom != PTM.getSrcRecord())
3372 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
3373 }
3374 }
3375 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003376 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003377}
3378
Chris Lattnercabe0372010-03-15 06:00:16 +00003379/// Given a pattern result with an unresolved type, see if we can find one
3380/// instruction with an unresolved result type. Force this result type to an
3381/// arbitrary element if it's possible types to converge results.
3382static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3383 if (N->isLeaf())
3384 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003385
Chris Lattnercabe0372010-03-15 06:00:16 +00003386 // Analyze children.
3387 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3388 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3389 return true;
3390
3391 if (!N->getOperator()->isSubClassOf("Instruction"))
3392 return false;
3393
3394 // If this type is already concrete or completely unknown we can't do
3395 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003396 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3397 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3398 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003399
Chris Lattnerf1447252010-03-19 21:37:09 +00003400 // Otherwise, force its type to the first possibility (an arbitrary choice).
3401 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3402 return true;
3403 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003404
Chris Lattnerf1447252010-03-19 21:37:09 +00003405 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003406}
3407
Chris Lattnerab3242f2008-01-06 01:10:31 +00003408void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003409 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3410
3411 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003412 Record *CurPattern = Patterns[i];
David Greeneaf8ee2c2011-07-29 22:43:06 +00003413 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003414
3415 // If the pattern references the null_frag, there's nothing to do.
3416 if (hasNullFragReference(Tree))
3417 continue;
3418
Chris Lattner5c2182e2010-03-27 02:53:27 +00003419 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003420
3421 // Inline pattern fragments into it.
3422 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003423
David Greeneaf8ee2c2011-07-29 22:43:06 +00003424 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner8cab0212008-01-05 22:25:12 +00003425 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003426
Chris Lattner8cab0212008-01-05 22:25:12 +00003427 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003428 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003429
Chris Lattner8cab0212008-01-05 22:25:12 +00003430 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003431 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003432
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003433 if (Result.getNumTrees() != 1)
3434 Result.error("Cannot handle instructions producing instructions "
3435 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003436
Chris Lattner8cab0212008-01-05 22:25:12 +00003437 bool IterateInference;
3438 bool InferredAllPatternTypes, InferredAllResultTypes;
3439 do {
3440 // Infer as many types as possible. If we cannot infer all of them, we
3441 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003442 InferredAllPatternTypes =
3443 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003444
Chris Lattner8cab0212008-01-05 22:25:12 +00003445 // Infer as many types as possible. If we cannot infer all of them, we
3446 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003447 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003448 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003449
Chris Lattnerfdc20712010-03-18 23:15:10 +00003450 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003451
Chris Lattner8cab0212008-01-05 22:25:12 +00003452 // Apply the type of the result to the source pattern. This helps us
3453 // resolve cases where the input type is known to be a pointer type (which
3454 // is considered resolved), but the result knows it needs to be 32- or
3455 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003456 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003457 Pattern->getTree(0)->getNumTypes());
3458 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003459 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3460 i, Result.getTree(0)->getExtType(i), Result);
3461 IterateInference |= Result.getTree(0)->UpdateNodeType(
3462 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003463 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003464
Chris Lattnercabe0372010-03-15 06:00:16 +00003465 // If our iteration has converged and the input pattern's types are fully
3466 // resolved but the result pattern is not fully resolved, we may have a
3467 // situation where we have two instructions in the result pattern and
3468 // the instructions require a common register class, but don't care about
3469 // what actual MVT is used. This is actually a bug in our modelling:
3470 // output patterns should have register classes, not MVTs.
3471 //
3472 // In any case, to handle this, we just go through and disambiguate some
3473 // arbitrary types to the result pattern's nodes.
3474 if (!IterateInference && InferredAllPatternTypes &&
3475 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003476 IterateInference =
3477 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003478 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003479
Chris Lattner8cab0212008-01-05 22:25:12 +00003480 // Verify that we inferred enough types that we can do something with the
3481 // pattern and result. If these fire the user has to add type casts.
3482 if (!InferredAllPatternTypes)
3483 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003484 if (!InferredAllResultTypes) {
3485 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003486 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003487 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003488
Chris Lattner8cab0212008-01-05 22:25:12 +00003489 // Validate that the input pattern is correct.
3490 std::map<std::string, TreePatternNode*> InstInputs;
3491 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003492 std::vector<Record*> InstImpResults;
3493 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3494 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3495 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003496 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003497
3498 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003499 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003500 std::vector<TreePatternNode*> ResultNodeOperands;
3501 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3502 TreePatternNode *OpNode = DstPattern->getChild(ii);
3503 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003504 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003505 std::vector<TreePatternNode*> Children;
3506 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003507 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003508 }
3509 ResultNodeOperands.push_back(OpNode);
3510 }
David Blaikiecf195302014-11-17 22:55:41 +00003511 DstPattern = Result.getOnlyTree();
3512 if (!DstPattern->isLeaf())
3513 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3514 ResultNodeOperands,
3515 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003516
David Blaikiecf195302014-11-17 22:55:41 +00003517 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3518 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3519
3520 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003521 Temp.InferAllTypes();
3522
Jim Grosbach65586fe2010-12-21 16:16:00 +00003523
Chris Lattner0c0baa92010-02-23 06:16:51 +00003524 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003525 PatternToMatch(CurPattern,
3526 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003527 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003528 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003529 CurPattern->getValueAsInt("AddedComplexity"),
3530 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003531 }
3532}
3533
3534/// CombineChildVariants - Given a bunch of permutations of each child of the
3535/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003536static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003537 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3538 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003539 CodeGenDAGPatterns &CDP,
3540 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003541 // Make sure that each operand has at least one variant to choose from.
3542 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3543 if (ChildVariants[i].empty())
3544 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003545
Chris Lattner8cab0212008-01-05 22:25:12 +00003546 // The end result is an all-pairs construction of the resultant pattern.
3547 std::vector<unsigned> Idxs;
3548 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003549 bool NotDone;
3550 do {
3551#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003552 DEBUG(if (!Idxs.empty()) {
3553 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3554 for (unsigned i = 0; i < Idxs.size(); ++i) {
3555 errs() << Idxs[i] << " ";
3556 }
3557 errs() << "]\n";
3558 });
Scott Michel94420742008-03-05 17:49:05 +00003559#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003560 // Create the variant and add it to the output list.
3561 std::vector<TreePatternNode*> NewChildren;
3562 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3563 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerf1447252010-03-19 21:37:09 +00003564 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3565 Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003566
Chris Lattner8cab0212008-01-05 22:25:12 +00003567 // Copy over properties.
3568 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003569 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003570 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003571 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3572 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003573
Scott Michel94420742008-03-05 17:49:05 +00003574 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003575 std::string ErrString;
3576 if (!R->canPatternMatch(ErrString, CDP)) {
3577 delete R;
3578 } else {
3579 bool AlreadyExists = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003580
Chris Lattner8cab0212008-01-05 22:25:12 +00003581 // Scan to see if this pattern has already been emitted. We can get
3582 // duplication due to things like commuting:
3583 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3584 // which are the same pattern. Ignore the dups.
3585 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003586 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003587 AlreadyExists = true;
3588 break;
3589 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003590
Chris Lattner8cab0212008-01-05 22:25:12 +00003591 if (AlreadyExists)
3592 delete R;
3593 else
3594 OutVariants.push_back(R);
3595 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003596
Scott Michel94420742008-03-05 17:49:05 +00003597 // Increment indices to the next permutation by incrementing the
3598 // indicies from last index backward, e.g., generate the sequence
3599 // [0, 0], [0, 1], [1, 0], [1, 1].
3600 int IdxsIdx;
3601 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3602 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3603 Idxs[IdxsIdx] = 0;
3604 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003605 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003606 }
Scott Michel94420742008-03-05 17:49:05 +00003607 NotDone = (IdxsIdx >= 0);
3608 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003609}
3610
3611/// CombineChildVariants - A helper function for binary operators.
3612///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003613static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003614 const std::vector<TreePatternNode*> &LHS,
3615 const std::vector<TreePatternNode*> &RHS,
3616 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003617 CodeGenDAGPatterns &CDP,
3618 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003619 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3620 ChildVariants.push_back(LHS);
3621 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003622 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003623}
Chris Lattner8cab0212008-01-05 22:25:12 +00003624
3625
3626static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3627 std::vector<TreePatternNode *> &Children) {
3628 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3629 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003630
Chris Lattner8cab0212008-01-05 22:25:12 +00003631 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003632 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003633 N->getTransformFn()) {
3634 Children.push_back(N);
3635 return;
3636 }
3637
3638 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3639 Children.push_back(N->getChild(0));
3640 else
3641 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3642
3643 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3644 Children.push_back(N->getChild(1));
3645 else
3646 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3647}
3648
3649/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3650/// the (potentially recursive) pattern by using algebraic laws.
3651///
3652static void GenerateVariantsOf(TreePatternNode *N,
3653 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003654 CodeGenDAGPatterns &CDP,
3655 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003656 // We cannot permute leaves or ComplexPattern uses.
3657 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003658 OutVariants.push_back(N);
3659 return;
3660 }
3661
3662 // Look up interesting info about the node.
3663 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3664
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003665 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003666 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003667 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003668 std::vector<TreePatternNode*> MaximalChildren;
3669 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3670
3671 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3672 // permutations.
3673 if (MaximalChildren.size() == 3) {
3674 // Find the variants of all of our maximal children.
3675 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003676 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3677 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3678 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003679
Chris Lattner8cab0212008-01-05 22:25:12 +00003680 // There are only two ways we can permute the tree:
3681 // (A op B) op C and A op (B op C)
3682 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003683
Chris Lattner8cab0212008-01-05 22:25:12 +00003684 // Generate legal pair permutations of A/B/C.
3685 std::vector<TreePatternNode*> ABVariants;
3686 std::vector<TreePatternNode*> BAVariants;
3687 std::vector<TreePatternNode*> ACVariants;
3688 std::vector<TreePatternNode*> CAVariants;
3689 std::vector<TreePatternNode*> BCVariants;
3690 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003691 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3692 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3693 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3694 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3695 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3696 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003697
3698 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003699 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3700 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3701 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3702 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3703 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3704 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003705
3706 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003707 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3708 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3709 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3710 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3711 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3712 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003713 return;
3714 }
3715 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003716
Chris Lattner8cab0212008-01-05 22:25:12 +00003717 // Compute permutations of all children.
3718 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3719 ChildVariants.resize(N->getNumChildren());
3720 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003721 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003722
3723 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003724 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003725
3726 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003727 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3728 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3729 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3730 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003731 // Don't count children which are actually register references.
3732 unsigned NC = 0;
3733 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3734 TreePatternNode *Child = N->getChild(i);
3735 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003736 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003737 Record *RR = DI->getDef();
3738 if (RR->isSubClassOf("Register"))
3739 continue;
3740 }
3741 NC++;
3742 }
3743 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003744 if (isCommIntrinsic) {
3745 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3746 // operands are the commutative operands, and there might be more operands
3747 // after those.
3748 assert(NC >= 3 &&
3749 "Commutative intrinsic should have at least 3 childrean!");
3750 std::vector<std::vector<TreePatternNode*> > Variants;
3751 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3752 Variants.push_back(ChildVariants[2]);
3753 Variants.push_back(ChildVariants[1]);
3754 for (unsigned i = 3; i != NC; ++i)
3755 Variants.push_back(ChildVariants[i]);
3756 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3757 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003758 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003759 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003760 }
3761}
3762
3763
3764// GenerateVariants - Generate variants. For example, commutative patterns can
3765// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003766void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003767 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003768
Chris Lattner8cab0212008-01-05 22:25:12 +00003769 // Loop over all of the patterns we've collected, checking to see if we can
3770 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003771 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003772 // the .td file having to contain tons of variants of instructions.
3773 //
3774 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3775 // intentionally do not reconsider these. Any variants of added patterns have
3776 // already been added.
3777 //
3778 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003779 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003780 std::vector<TreePatternNode*> Variants;
Scott Michel94420742008-03-05 17:49:05 +00003781 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003782 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003783 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003784 DEBUG(errs() << "\n");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003785 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3786 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003787
3788 assert(!Variants.empty() && "Must create at least original variant!");
3789 Variants.erase(Variants.begin()); // Remove the original pattern.
3790
3791 if (Variants.empty()) // No variants for this pattern.
3792 continue;
3793
Chris Lattner34822f62009-08-23 04:44:11 +00003794 DEBUG(errs() << "FOUND VARIANTS OF: ";
3795 PatternsToMatch[i].getSrcPattern()->dump();
3796 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003797
3798 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3799 TreePatternNode *Variant = Variants[v];
3800
Chris Lattner34822f62009-08-23 04:44:11 +00003801 DEBUG(errs() << " VAR#" << v << ": ";
3802 Variant->dump();
3803 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003804
Chris Lattner8cab0212008-01-05 22:25:12 +00003805 // Scan to see if an instruction or explicit pattern already matches this.
3806 bool AlreadyExists = false;
3807 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003808 // Skip if the top level predicates do not match.
3809 if (PatternsToMatch[i].getPredicates() !=
3810 PatternsToMatch[p].getPredicates())
3811 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003812 // Check to see if this variant already exists.
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003813 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3814 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003815 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003816 AlreadyExists = true;
3817 break;
3818 }
3819 }
3820 // If we already have it, ignore the variant.
3821 if (AlreadyExists) continue;
3822
3823 // Otherwise, add it to the list of patterns we have.
3824 PatternsToMatch.
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003825 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3826 PatternsToMatch[i].getPredicates(),
Chris Lattner8cab0212008-01-05 22:25:12 +00003827 Variant, PatternsToMatch[i].getDstPattern(),
3828 PatternsToMatch[i].getDstRegs(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003829 PatternsToMatch[i].getAddedComplexity(),
3830 Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003831 }
3832
Chris Lattner34822f62009-08-23 04:44:11 +00003833 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003834 }
3835}