blob: fd02bbdc6b48897629affbe45b1c98adad017422 [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 // This code does not currently handle nodes which have multiple types,
393 // where some types are integer, and some are fp. Assert that this is not
394 // the case.
395 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
396 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
397 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
398
399 if (TP.hasError())
400 return false;
401
Craig Topper7bbd37b2015-03-10 03:25:07 +0000402 // Okay, find the smallest type from current set and remove anything the
403 // same or smaller from the other set. We need to ensure that the scalar
404 // type size is smaller than the scalar size of the smallest type. For
405 // vectors, we also need to make sure that the total size is no larger than
406 // the size of the smallest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000407 TypeSet InputSet(Other);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000408 MVT Smallest = TypeVec[0];
Craig Topper74169dc2014-01-28 04:49:01 +0000409 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000410 MVT OtherVT = Other.TypeVec[i];
411 // Don't compare vector and non-vector types.
412 if (OtherVT.isVector() != Smallest.isVector())
413 continue;
414 // The getSizeInBits() check here is only needed for vectors, but is
415 // a subset of the scalar check for scalars so no need to qualify.
416 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
417 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000418 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
419 MadeChange = true;
420 }
421 }
422
423 if (Other.TypeVec.empty()) {
424 TP.error("Type inference contradiction found, '" + InputSet.getName() +
425 "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000426 return false;
427 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000428
Craig Topper7bbd37b2015-03-10 03:25:07 +0000429 // Okay, find the largest type from the other set and remove anything the
430 // same or smaller from the current set. We need to ensure that the scalar
431 // type size is larger than the scalar size of the largest type. For
432 // vectors, we also need to make sure that the total size is no smaller than
433 // the size of the largest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000434 InputSet = TypeSet(*this);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000435 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
Craig Topper74169dc2014-01-28 04:49:01 +0000436 for (unsigned i = 0; i != TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000437 MVT OtherVT = TypeVec[i];
438 // Don't compare vector and non-vector types.
439 if (OtherVT.isVector() != Largest.isVector())
440 continue;
441 // The getSizeInBits() check here is only needed for vectors, but is
442 // a subset of the scalar check for scalars so no need to qualify.
443 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
444 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000445 TypeVec.erase(TypeVec.begin()+i--);
446 MadeChange = true;
David Greene433c6182011-02-01 19:12:32 +0000447 }
David Greene433c6182011-02-01 19:12:32 +0000448 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000449
Craig Topper74169dc2014-01-28 04:49:01 +0000450 if (TypeVec.empty()) {
451 TP.error("Type inference contradiction found, '" + InputSet.getName() +
452 "' has nothing smaller than '" + Other.getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000453 return false;
454 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000455
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000456 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000457}
458
459/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000460/// whose element is specified by VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000461bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
462 TreePattern &TP) {
463 bool MadeChange = false;
464
465 MadeChange |= EnforceVector(TP);
466
467 TypeSet InputSet(*this);
468
469 // Filter out all the types which don't have the right element type.
470 for (unsigned i = 0; i != TypeVec.size(); ++i) {
471 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
472 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
473 TypeVec.erase(TypeVec.begin()+i--);
474 MadeChange = true;
475 }
476 }
477
478 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
479 TP.error("Type inference contradiction found, forcing '" +
480 InputSet.getName() + "' to have a vector element");
481 return false;
482 }
483
484 return MadeChange;
485}
486
487/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
488/// whose element is specified by VTOperand.
Chris Lattner57ebf632010-03-24 00:01:16 +0000489bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000490 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000491 if (TP.hasError())
492 return false;
493
Chris Lattner57ebf632010-03-24 00:01:16 +0000494 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000495 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000496 MadeChange |= EnforceVector(TP);
497 MadeChange |= VTOperand.EnforceScalar(TP);
498
499 // If we know the vector type, it forces the scalar to agree.
500 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000501 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000502 IVT = IVT.getVectorElementType();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000503 return MadeChange |
Craig Topper95198f42013-09-25 06:37:18 +0000504 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000505 }
506
507 // If the scalar type is known, filter out vector types whose element types
508 // disagree.
509 if (!VTOperand.isConcrete())
510 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000511
Chris Lattner57ebf632010-03-24 00:01:16 +0000512 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000513
Chris Lattner57ebf632010-03-24 00:01:16 +0000514 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000515
Chris Lattner57ebf632010-03-24 00:01:16 +0000516 // Filter out all the types which don't have the right element type.
517 for (unsigned i = 0; i != TypeVec.size(); ++i) {
518 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
Craig Topper95198f42013-09-25 06:37:18 +0000519 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000520 TypeVec.erase(TypeVec.begin()+i--);
521 MadeChange = true;
522 }
Chris Lattner57ebf632010-03-24 00:01:16 +0000523 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000524
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000525 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattnercabe0372010-03-15 06:00:16 +0000526 TP.error("Type inference contradiction found, forcing '" +
527 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000528 return false;
529 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000530 return MadeChange;
531}
532
David Greene127fd1d2011-01-24 20:53:18 +0000533/// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
534/// vector type specified by VTOperand.
535bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
536 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000537 if (TP.hasError())
538 return false;
539
David Greene127fd1d2011-01-24 20:53:18 +0000540 // "This" must be a vector and "VTOperand" must be a vector.
541 bool MadeChange = false;
542 MadeChange |= EnforceVector(TP);
543 MadeChange |= VTOperand.EnforceVector(TP);
544
Craig Topper6e1faaf2014-01-25 17:40:33 +0000545 // If one side is known to be integer or known to be FP but the other side has
546 // no information, get at least the type integrality info in there.
547 if (!hasFloatingPointTypes())
548 MadeChange |= VTOperand.EnforceInteger(TP);
549 else if (!hasIntegerTypes())
550 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
551 if (!VTOperand.hasFloatingPointTypes())
552 MadeChange |= EnforceInteger(TP);
553 else if (!VTOperand.hasIntegerTypes())
554 MadeChange |= EnforceFloatingPoint(TP);
555
556 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
557 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000558
559 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000560 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000561 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000562 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000563 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000564 IVT = IVT.getVectorElementType();
565
Craig Topper95198f42013-09-25 06:37:18 +0000566 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000567 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000568
569 // Only keep types that have less elements than VTOperand.
570 TypeSet InputSet(VTOperand);
571
572 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
573 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
574 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
575 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
576 MadeChange = true;
577 }
578 }
579 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
580 TP.error("Type inference contradiction found, forcing '" +
581 InputSet.getName() + "' to have less vector elements than '" +
582 getName() + "'");
583 return false;
584 }
David Greene127fd1d2011-01-24 20:53:18 +0000585 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000586 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000587 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000588 IVT = IVT.getVectorElementType();
589
Craig Topper95198f42013-09-25 06:37:18 +0000590 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000591 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000592
593 // Only keep types that have more elements than 'this'.
594 TypeSet InputSet(*this);
595
596 for (unsigned i = 0; i != TypeVec.size(); ++i) {
597 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
598 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
599 TypeVec.erase(TypeVec.begin()+i--);
600 MadeChange = true;
601 }
602 }
603 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
604 TP.error("Type inference contradiction found, forcing '" +
605 InputSet.getName() + "' to have more vector elements than '" +
606 VTOperand.getName() + "'");
607 return false;
608 }
David Greene127fd1d2011-01-24 20:53:18 +0000609 }
610
611 return MadeChange;
612}
613
Craig Topper0be34582015-03-05 07:11:34 +0000614/// EnforceVectorSameNumElts - 'this' is now constrainted to
615/// be a vector with same num elements as VTOperand.
616bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
617 TreePattern &TP) {
618 if (TP.hasError())
619 return false;
620
621 // "This" must be a vector and "VTOperand" must be a vector.
622 bool MadeChange = false;
623 MadeChange |= EnforceVector(TP);
624 MadeChange |= VTOperand.EnforceVector(TP);
625
626 // If we know one of the vector types, it forces the other type to agree.
627 if (isConcrete()) {
628 MVT IVT = getConcrete();
629 unsigned NumElems = IVT.getVectorNumElements();
630
631 // Only keep types that have same elements as VTOperand.
632 TypeSet InputSet(VTOperand);
633
634 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
635 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
636 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
637 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
638 MadeChange = true;
639 }
640 }
641 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
642 TP.error("Type inference contradiction found, forcing '" +
643 InputSet.getName() + "' to have same number elements as '" +
644 getName() + "'");
645 return false;
646 }
647 } else if (VTOperand.isConcrete()) {
648 MVT IVT = VTOperand.getConcrete();
649 unsigned NumElems = IVT.getVectorNumElements();
650
651 // Only keep types that have same elements as 'this'.
652 TypeSet InputSet(*this);
653
654 for (unsigned i = 0; i != TypeVec.size(); ++i) {
655 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
656 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
657 TypeVec.erase(TypeVec.begin()+i--);
658 MadeChange = true;
659 }
660 }
661 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
662 TP.error("Type inference contradiction found, forcing '" +
663 InputSet.getName() + "' to have same number elements than '" +
664 VTOperand.getName() + "'");
665 return false;
666 }
667 }
668
669 return MadeChange;
670}
671
Chris Lattnercabe0372010-03-15 06:00:16 +0000672//===----------------------------------------------------------------------===//
673// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000674
Scott Michel94420742008-03-05 17:49:05 +0000675/// Dependent variable map for CodeGenDAGPattern variant generation
676typedef std::map<std::string, int> DepVarMap;
677
678/// Const iterator shorthand for DepVarMap
679typedef DepVarMap::const_iterator DepVarMap_citer;
680
Chris Lattner514e2922011-04-17 21:38:24 +0000681static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000682 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000683 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000684 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000685 } else {
686 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
687 FindDepVarsOf(N->getChild(i), DepMap);
688 }
689}
Chris Lattner514e2922011-04-17 21:38:24 +0000690
691/// Find dependent variables within child patterns
692static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000693 DepVarMap depcounts;
694 FindDepVarsOf(N, depcounts);
695 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner514e2922011-04-17 21:38:24 +0000696 if (i->second > 1) // std::pair<std::string, int>
Scott Michel94420742008-03-05 17:49:05 +0000697 DepVars.insert(i->first);
Scott Michel94420742008-03-05 17:49:05 +0000698 }
699}
700
Daniel Dunbarba66a812010-10-08 02:07:22 +0000701#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000702/// Dump the dependent variable set:
703static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000704 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000705 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000706 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000707 DEBUG(errs() << "[ ");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +0000708 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
709 e = DepVars.end(); i != e; ++i) {
Chris Lattner34822f62009-08-23 04:44:11 +0000710 DEBUG(errs() << (*i) << " ");
Scott Michel94420742008-03-05 17:49:05 +0000711 }
Chris Lattner34822f62009-08-23 04:44:11 +0000712 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000713 }
714}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000715#endif
716
Chris Lattner514e2922011-04-17 21:38:24 +0000717
718//===----------------------------------------------------------------------===//
719// TreePredicateFn Implementation
720//===----------------------------------------------------------------------===//
721
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000722/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
723TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
724 assert((getPredCode().empty() || getImmCode().empty()) &&
725 ".td file corrupt: can't have a node predicate *and* an imm predicate");
726}
727
Chris Lattner514e2922011-04-17 21:38:24 +0000728std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000729 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000730}
731
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000732std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000733 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000734}
735
Chris Lattner514e2922011-04-17 21:38:24 +0000736
737/// isAlwaysTrue - Return true if this is a noop predicate.
738bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000739 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000740}
741
742/// Return the name to use in the generated code to reference this, this is
743/// "Predicate_foo" if from a pattern fragment "foo".
744std::string TreePredicateFn::getFnName() const {
745 return "Predicate_" + PatFragRec->getRecord()->getName();
746}
747
748/// getCodeToRunOnSDNode - Return the code for the function body that
749/// evaluates this predicate. The argument is expected to be in "Node",
750/// not N. This handles casting and conversion to a concrete node type as
751/// appropriate.
752std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000753 // Handle immediate predicates first.
754 std::string ImmCode = getImmCode();
755 if (!ImmCode.empty()) {
756 std::string Result =
757 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000758 return Result + ImmCode;
759 }
760
761 // Handle arbitrary node predicates.
762 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000763 std::string ClassName;
764 if (PatFragRec->getOnlyTree()->isLeaf())
765 ClassName = "SDNode";
766 else {
767 Record *Op = PatFragRec->getOnlyTree()->getOperator();
768 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
769 }
770 std::string Result;
771 if (ClassName == "SDNode")
772 Result = " SDNode *N = Node;\n";
773 else
774 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
775
776 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000777}
778
Chris Lattner8cab0212008-01-05 22:25:12 +0000779//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000780// PatternToMatch implementation
781//
782
Chris Lattner05925fe2010-03-29 01:40:38 +0000783
784/// getPatternSize - Return the 'size' of this pattern. We want to match large
785/// patterns before small ones. This is used to determine the size of a
786/// pattern.
787static unsigned getPatternSize(const TreePatternNode *P,
788 const CodeGenDAGPatterns &CGP) {
789 unsigned Size = 3; // The node itself.
790 // If the root node is a ConstantSDNode, increases its size.
791 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000792 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000793 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000794
Chris Lattner05925fe2010-03-29 01:40:38 +0000795 // FIXME: This is a hack to statically increase the priority of patterns
796 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
797 // Later we can allow complexity / cost for each pattern to be (optionally)
798 // specified. To get best possible pattern match we'll need to dynamically
799 // calculate the complexity of all patterns a dag can potentially map to.
800 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000801 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000802 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000803
Tim Northoverc807a172014-05-20 11:52:46 +0000804 // We don't want to count any children twice, so return early.
805 return Size;
806 }
807
Chris Lattner05925fe2010-03-29 01:40:38 +0000808 // If this node has some predicate function that must match, it adds to the
809 // complexity of this node.
810 if (!P->getPredicateFns().empty())
811 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000812
Chris Lattner05925fe2010-03-29 01:40:38 +0000813 // Count children in the count if they are also nodes.
814 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
815 TreePatternNode *Child = P->getChild(i);
816 if (!Child->isLeaf() && Child->getNumTypes() &&
817 Child->getType(0) != MVT::Other)
818 Size += getPatternSize(Child, CGP);
819 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000820 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000821 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
822 else if (Child->getComplexPatternInfo(CGP))
823 Size += getPatternSize(Child, CGP);
824 else if (!Child->getPredicateFns().empty())
825 ++Size;
826 }
827 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000828
Chris Lattner05925fe2010-03-29 01:40:38 +0000829 return Size;
830}
831
832/// Compute the complexity metric for the input pattern. This roughly
833/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000834int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000835getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
836 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
837}
838
839
Dan Gohman49e19e92008-08-22 00:20:26 +0000840/// getPredicateCheck - Return a single string containing all of this
841/// pattern's predicates concatenated with "&&" operators.
842///
843std::string PatternToMatch::getPredicateCheck() const {
844 std::string PredicateCheck;
845 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +0000846 if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000847 Record *Def = Pred->getDef();
848 if (!Def->isSubClassOf("Predicate")) {
849#ifndef NDEBUG
850 Def->dump();
851#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000852 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000853 }
854 if (!PredicateCheck.empty())
855 PredicateCheck += " && ";
856 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
857 }
858 }
859
860 return PredicateCheck;
861}
862
863//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000864// SDTypeConstraint implementation
865//
866
867SDTypeConstraint::SDTypeConstraint(Record *R) {
868 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000869
Chris Lattner8cab0212008-01-05 22:25:12 +0000870 if (R->isSubClassOf("SDTCisVT")) {
871 ConstraintType = SDTCisVT;
872 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000873 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000874 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000875
Chris Lattner8cab0212008-01-05 22:25:12 +0000876 } else if (R->isSubClassOf("SDTCisPtrTy")) {
877 ConstraintType = SDTCisPtrTy;
878 } else if (R->isSubClassOf("SDTCisInt")) {
879 ConstraintType = SDTCisInt;
880 } else if (R->isSubClassOf("SDTCisFP")) {
881 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000882 } else if (R->isSubClassOf("SDTCisVec")) {
883 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000884 } else if (R->isSubClassOf("SDTCisSameAs")) {
885 ConstraintType = SDTCisSameAs;
886 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
887 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
888 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000889 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000890 R->getValueAsInt("OtherOperandNum");
891 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
892 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000893 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000894 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000895 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
896 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000897 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000898 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
899 ConstraintType = SDTCisSubVecOfVec;
900 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
901 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000902 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
903 ConstraintType = SDTCVecEltisVT;
904 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
905 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
906 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
907 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
908 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
909 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
910 "as SDTCVecEltisVT");
911 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
912 ConstraintType = SDTCisSameNumEltsAs;
913 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
914 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000915 } else {
James Y Knighte452e272015-05-11 22:17:13 +0000916 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +0000917 }
918}
919
920/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000921/// N, and the result number in ResNo.
922static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
923 const SDNodeInfo &NodeInfo,
924 unsigned &ResNo) {
925 unsigned NumResults = NodeInfo.getNumResults();
926 if (OpNo < NumResults) {
927 ResNo = OpNo;
928 return N;
929 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000930
Chris Lattner2db7aba2010-03-19 21:56:21 +0000931 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000932
Chris Lattner2db7aba2010-03-19 21:56:21 +0000933 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +0000934 std::string S;
935 raw_string_ostream OS(S);
936 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000937 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +0000938 N->print(OS);
939 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +0000940 }
941
Chris Lattner2db7aba2010-03-19 21:56:21 +0000942 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000943}
944
945/// ApplyTypeConstraint - Given a node in a pattern, apply this type
946/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000947/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000948bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
949 const SDNodeInfo &NodeInfo,
950 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000951 if (TP.hasError())
952 return false;
953
Chris Lattner2db7aba2010-03-19 21:56:21 +0000954 unsigned ResNo = 0; // The result number being referenced.
955 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000956
Chris Lattner8cab0212008-01-05 22:25:12 +0000957 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000958 case SDTCisVT:
959 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000960 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000961 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000962 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000963 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000964 case SDTCisInt:
965 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000966 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000967 case SDTCisFP:
968 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000969 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000970 case SDTCisVec:
971 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000972 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000973 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000974 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000975 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000976 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +0000977 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
978 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000979 }
980 case SDTCisVTSmallerThanOp: {
981 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
982 // have an integer type that is smaller than the VT.
983 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +0000984 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +0000985 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000986 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000987 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000988 return false;
989 }
Owen Anderson9f944592009-08-11 20:47:22 +0000990 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +0000991 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000992
Chris Lattner38c99662010-03-24 00:06:46 +0000993 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000994
Chris Lattner2db7aba2010-03-19 21:56:21 +0000995 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000996 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000997 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
998 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +0000999
Chris Lattner38c99662010-03-24 00:06:46 +00001000 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001001 }
1002 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001003 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001004 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001005 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1006 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +00001007 return NodeToApply->getExtType(ResNo).
1008 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001009 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001010 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001011 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001012 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001013 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1014 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001015
Chris Lattner57ebf632010-03-24 00:01:16 +00001016 // Filter vector types out of VecOperand that don't have the right element
1017 // type.
1018 return VecOperand->getExtType(VResNo).
1019 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +00001020 }
David Greene127fd1d2011-01-24 20:53:18 +00001021 case SDTCisSubVecOfVec: {
1022 unsigned VResNo = 0;
1023 TreePatternNode *BigVecOperand =
1024 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1025 VResNo);
1026
1027 // Filter vector types out of BigVecOperand that don't have the
1028 // right subvector type.
1029 return BigVecOperand->getExtType(VResNo).
1030 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1031 }
Craig Topper0be34582015-03-05 07:11:34 +00001032 case SDTCVecEltisVT: {
1033 return NodeToApply->getExtType(ResNo).
1034 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1035 }
1036 case SDTCisSameNumEltsAs: {
1037 unsigned OResNo = 0;
1038 TreePatternNode *OtherNode =
1039 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1040 N, NodeInfo, OResNo);
1041 return OtherNode->getExtType(OResNo).
1042 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1043 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001044 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001045 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001046}
1047
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001048// Update the node type to match an instruction operand or result as specified
1049// in the ins or outs lists on the instruction definition. Return true if the
1050// type was actually changed.
1051bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1052 Record *Operand,
1053 TreePattern &TP) {
1054 // The 'unknown' operand indicates that types should be inferred from the
1055 // context.
1056 if (Operand->isSubClassOf("unknown_class"))
1057 return false;
1058
1059 // The Operand class specifies a type directly.
1060 if (Operand->isSubClassOf("Operand"))
1061 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1062 TP);
1063
1064 // PointerLikeRegClass has a type that is determined at runtime.
1065 if (Operand->isSubClassOf("PointerLikeRegClass"))
1066 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1067
1068 // Both RegisterClass and RegisterOperand operands derive their types from a
1069 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001070 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001071 if (Operand->isSubClassOf("RegisterClass"))
1072 RC = Operand;
1073 else if (Operand->isSubClassOf("RegisterOperand"))
1074 RC = Operand->getValueAsDef("RegClass");
1075
1076 assert(RC && "Unknown operand type");
1077 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1078 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1079}
1080
1081
Chris Lattner8cab0212008-01-05 22:25:12 +00001082//===----------------------------------------------------------------------===//
1083// SDNodeInfo implementation
1084//
1085SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1086 EnumName = R->getValueAsString("Opcode");
1087 SDClassName = R->getValueAsString("SDClass");
1088 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1089 NumResults = TypeProfile->getValueAsInt("NumResults");
1090 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001091
Chris Lattner8cab0212008-01-05 22:25:12 +00001092 // Parse the properties.
1093 Properties = 0;
1094 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1095 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1096 if (PropList[i]->getName() == "SDNPCommutative") {
1097 Properties |= 1 << SDNPCommutative;
1098 } else if (PropList[i]->getName() == "SDNPAssociative") {
1099 Properties |= 1 << SDNPAssociative;
1100 } else if (PropList[i]->getName() == "SDNPHasChain") {
1101 Properties |= 1 << SDNPHasChain;
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001102 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1103 Properties |= 1 << SDNPOutGlue;
1104 } else if (PropList[i]->getName() == "SDNPInGlue") {
1105 Properties |= 1 << SDNPInGlue;
1106 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1107 Properties |= 1 << SDNPOptInGlue;
Chris Lattnera348f552008-01-06 06:44:58 +00001108 } else if (PropList[i]->getName() == "SDNPMayStore") {
1109 Properties |= 1 << SDNPMayStore;
Chris Lattner1ca20682008-01-10 04:38:57 +00001110 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1111 Properties |= 1 << SDNPMayLoad;
Chris Lattner42c63ef2008-01-10 05:39:30 +00001112 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1113 Properties |= 1 << SDNPSideEffect;
Mon P Wang6a490372008-06-25 08:15:39 +00001114 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1115 Properties |= 1 << SDNPMemOperand;
Chris Lattner83aeaab2010-03-19 05:07:09 +00001116 } else if (PropList[i]->getName() == "SDNPVariadic") {
1117 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001118 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001119 PrintFatalError("Unknown SD Node property '" +
1120 PropList[i]->getName() + "' on node '" +
1121 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001122 }
1123 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001124
1125
Chris Lattner8cab0212008-01-05 22:25:12 +00001126 // Parse the type constraints.
1127 std::vector<Record*> ConstraintList =
1128 TypeProfile->getValueAsListOfDefs("Constraints");
1129 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1130}
1131
Chris Lattner99e53b32010-02-28 00:22:30 +00001132/// getKnownType - If the type constraints on this node imply a fixed type
1133/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001134/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001135MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001136 unsigned NumResults = getNumResults();
1137 assert(NumResults <= 1 &&
1138 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001139 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001140
Chris Lattner99e53b32010-02-28 00:22:30 +00001141 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1142 // Make sure that this applies to the correct node result.
1143 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1144 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001145
Chris Lattner99e53b32010-02-28 00:22:30 +00001146 switch (TypeConstraints[i].ConstraintType) {
1147 default: break;
1148 case SDTypeConstraint::SDTCisVT:
1149 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1150 case SDTypeConstraint::SDTCisPtrTy:
1151 return MVT::iPTR;
1152 }
1153 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001154 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001155}
1156
Chris Lattner8cab0212008-01-05 22:25:12 +00001157//===----------------------------------------------------------------------===//
1158// TreePatternNode implementation
1159//
1160
1161TreePatternNode::~TreePatternNode() {
1162#if 0 // FIXME: implement refcounted tree nodes!
1163 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1164 delete getChild(i);
1165#endif
1166}
1167
Chris Lattnerf1447252010-03-19 21:37:09 +00001168static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1169 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001170 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001171 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001172
Chris Lattner2109cb42010-03-22 20:56:36 +00001173 if (Operator->isSubClassOf("Intrinsic"))
1174 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001175
Chris Lattnerf1447252010-03-19 21:37:09 +00001176 if (Operator->isSubClassOf("SDNode"))
1177 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001178
Chris Lattnerf1447252010-03-19 21:37:09 +00001179 if (Operator->isSubClassOf("PatFrag")) {
1180 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1181 // the forward reference case where one pattern fragment references another
1182 // before it is processed.
1183 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1184 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001185
Chris Lattnerf1447252010-03-19 21:37:09 +00001186 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001187 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001188 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001189 if (Tree)
1190 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1191 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001192 assert(Op && "Invalid Fragment");
1193 return GetNumNodeResults(Op, CDP);
1194 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001195
Chris Lattnerf1447252010-03-19 21:37:09 +00001196 if (Operator->isSubClassOf("Instruction")) {
1197 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001198
Craig Topper3a8eb892015-03-20 05:09:06 +00001199 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1200
1201 // Subtract any defaulted outputs.
1202 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1203 Record *OperandNode = InstInfo.Operands[i].Rec;
1204
1205 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1206 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1207 --NumDefsToAdd;
1208 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001209
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001210 // Add on one implicit def if it has a resolvable type.
1211 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1212 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001213 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001214 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001215
Chris Lattnerf1447252010-03-19 21:37:09 +00001216 if (Operator->isSubClassOf("SDNodeXForm"))
1217 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001218
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001219 if (Operator->isSubClassOf("ValueType"))
1220 return 1; // A type-cast of one result.
1221
Tim Northoverc807a172014-05-20 11:52:46 +00001222 if (Operator->isSubClassOf("ComplexPattern"))
1223 return 1;
1224
Chris Lattnerf1447252010-03-19 21:37:09 +00001225 Operator->dump();
James Y Knighte452e272015-05-11 22:17:13 +00001226 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001227}
1228
1229void TreePatternNode::print(raw_ostream &OS) const {
1230 if (isLeaf())
1231 OS << *getLeafValue();
1232 else
1233 OS << '(' << getOperator()->getName();
1234
1235 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1236 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001237
1238 if (!isLeaf()) {
1239 if (getNumChildren() != 0) {
1240 OS << " ";
1241 getChild(0)->print(OS);
1242 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1243 OS << ", ";
1244 getChild(i)->print(OS);
1245 }
1246 }
1247 OS << ")";
1248 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001249
Dan Gohman6e979022008-10-15 06:17:21 +00001250 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner514e2922011-04-17 21:38:24 +00001251 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001252 if (TransformFn)
1253 OS << "<<X:" << TransformFn->getName() << ">>";
1254 if (!getName().empty())
1255 OS << ":$" << getName();
1256
1257}
1258void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001259 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001260}
1261
Scott Michel94420742008-03-05 17:49:05 +00001262/// isIsomorphicTo - Return true if this node is recursively
1263/// isomorphic to the specified node. For this comparison, the node's
1264/// entire state is considered. The assigned name is ignored, since
1265/// nodes with differing names are considered isomorphic. However, if
1266/// the assigned name is present in the dependent variable set, then
1267/// the assigned name is considered significant and the node is
1268/// isomorphic if the names match.
1269bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1270 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001271 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001272 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001273 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001274 getTransformFn() != N->getTransformFn())
1275 return false;
1276
1277 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001278 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1279 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001280 return ((DI->getDef() == NDI->getDef())
1281 && (DepVars.find(getName()) == DepVars.end()
1282 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001283 }
1284 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001285 return getLeafValue() == N->getLeafValue();
1286 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001287
Chris Lattner8cab0212008-01-05 22:25:12 +00001288 if (N->getOperator() != getOperator() ||
1289 N->getNumChildren() != getNumChildren()) return false;
1290 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001291 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001292 return false;
1293 return true;
1294}
1295
1296/// clone - Make a copy of this tree and all of its children.
1297///
1298TreePatternNode *TreePatternNode::clone() const {
1299 TreePatternNode *New;
1300 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001301 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001302 } else {
1303 std::vector<TreePatternNode*> CChildren;
1304 CChildren.reserve(Children.size());
1305 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1306 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001307 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001308 }
1309 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001310 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001311 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001312 New->setTransformFn(getTransformFn());
1313 return New;
1314}
1315
Chris Lattner53c39ba2010-02-14 22:22:58 +00001316/// RemoveAllTypes - Recursively strip all the types of this tree.
1317void TreePatternNode::RemoveAllTypes() {
Chris Lattnerf1447252010-03-19 21:37:09 +00001318 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1319 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner53c39ba2010-02-14 22:22:58 +00001320 if (isLeaf()) return;
1321 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1322 getChild(i)->RemoveAllTypes();
1323}
1324
1325
Chris Lattner8cab0212008-01-05 22:25:12 +00001326/// SubstituteFormalArguments - Replace the formal arguments in this tree
1327/// with actual values specified by ArgMap.
1328void TreePatternNode::
1329SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1330 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001331
Chris Lattner8cab0212008-01-05 22:25:12 +00001332 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1333 TreePatternNode *Child = getChild(i);
1334 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001335 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001336 // Note that, when substituting into an output pattern, Val might be an
1337 // UnsetInit.
1338 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1339 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001340 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001341 TreePatternNode *NewChild = ArgMap[Child->getName()];
1342 assert(NewChild && "Couldn't find formal argument!");
1343 assert((Child->getPredicateFns().empty() ||
1344 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1345 "Non-empty child predicate clobbered!");
1346 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001347 }
1348 } else {
1349 getChild(i)->SubstituteFormalArguments(ArgMap);
1350 }
1351 }
1352}
1353
1354
1355/// InlinePatternFragments - If this pattern refers to any pattern
1356/// fragments, inline them into place, giving us a pattern without any
1357/// PatFrag references.
1358TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001359 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001360 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001361
1362 if (isLeaf())
1363 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001364 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001365
Chris Lattner8cab0212008-01-05 22:25:12 +00001366 if (!Op->isSubClassOf("PatFrag")) {
1367 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001368 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1369 TreePatternNode *Child = getChild(i);
1370 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1371
1372 assert((Child->getPredicateFns().empty() ||
1373 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1374 "Non-empty child predicate clobbered!");
1375
1376 setChild(i, NewChild);
1377 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001378 return this;
1379 }
1380
1381 // Otherwise, we found a reference to a fragment. First, look up its
1382 // TreePattern record.
1383 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001384
Chris Lattner8cab0212008-01-05 22:25:12 +00001385 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001386 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001387 TP.error("'" + Op->getName() + "' fragment requires " +
1388 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001389 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001390 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001391
1392 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1393
Chris Lattner514e2922011-04-17 21:38:24 +00001394 TreePredicateFn PredFn(Frag);
1395 if (!PredFn.isAlwaysTrue())
1396 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001397
Chris Lattner8cab0212008-01-05 22:25:12 +00001398 // Resolve formal arguments to their actual value.
1399 if (Frag->getNumArgs()) {
1400 // Compute the map of formal to actual arguments.
1401 std::map<std::string, TreePatternNode*> ArgMap;
1402 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1403 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001404
Chris Lattner8cab0212008-01-05 22:25:12 +00001405 FragTree->SubstituteFormalArguments(ArgMap);
1406 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001407
Chris Lattner8cab0212008-01-05 22:25:12 +00001408 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001409 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1410 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001411
1412 // Transfer in the old predicates.
1413 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1414 FragTree->addPredicateFn(getPredicateFns()[i]);
1415
Chris Lattner8cab0212008-01-05 22:25:12 +00001416 // Get a new copy of this fragment to stitch into here.
1417 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001418
Chris Lattner2e253b42008-06-30 03:02:03 +00001419 // The fragment we inlined could have recursive inlining that is needed. See
1420 // if there are any pattern fragments in it and inline them as needed.
1421 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001422}
1423
1424/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001425/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001426/// references from the register file information, for example.
1427///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001428/// When Unnamed is set, return the type of a DAG operand with no name, such as
1429/// the F8RC register class argument in:
1430///
1431/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1432///
1433/// When Unnamed is false, return the type of a named DAG operand such as the
1434/// GPR:$src operand above.
1435///
Chris Lattnerf1447252010-03-19 21:37:09 +00001436static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001437 bool NotRegisters,
1438 bool Unnamed,
1439 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001440 // Check to see if this is a register operand.
1441 if (R->isSubClassOf("RegisterOperand")) {
1442 assert(ResNo == 0 && "Regoperand ref only has one result!");
1443 if (NotRegisters)
1444 return EEVT::TypeSet(); // Unknown.
1445 Record *RegClass = R->getValueAsDef("RegClass");
1446 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1447 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1448 }
1449
Chris Lattnercabe0372010-03-15 06:00:16 +00001450 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001451 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001452 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001453 // An unnamed register class represents itself as an i32 immediate, for
1454 // example on a COPY_TO_REGCLASS instruction.
1455 if (Unnamed)
1456 return EEVT::TypeSet(MVT::i32, TP);
1457
1458 // In a named operand, the register class provides the possible set of
1459 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001460 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001461 return EEVT::TypeSet(); // Unknown.
1462 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1463 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001464 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001465
Chris Lattner6070ee22010-03-23 23:50:31 +00001466 if (R->isSubClassOf("PatFrag")) {
1467 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001468 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001469 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001470 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001471
Chris Lattner6070ee22010-03-23 23:50:31 +00001472 if (R->isSubClassOf("Register")) {
1473 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001474 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001475 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001476 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001477 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001478 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001479
1480 if (R->isSubClassOf("SubRegIndex")) {
1481 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001482 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001483 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001484
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001485 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001486 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001487 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1488 //
1489 // (sext_inreg GPR:$src, i16)
1490 // ~~~
1491 if (Unnamed)
1492 return EEVT::TypeSet(MVT::Other, TP);
1493 // With a name, the ValueType simply provides the type of the named
1494 // variable.
1495 //
1496 // (sext_inreg i32:$src, i16)
1497 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001498 if (NotRegisters)
1499 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001500 return EEVT::TypeSet(getValueType(R), TP);
1501 }
1502
1503 if (R->isSubClassOf("CondCode")) {
1504 assert(ResNo == 0 && "This node only has one result!");
1505 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001506 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001507 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001508
Chris Lattner6070ee22010-03-23 23:50:31 +00001509 if (R->isSubClassOf("ComplexPattern")) {
1510 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001511 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001512 return EEVT::TypeSet(); // Unknown.
1513 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1514 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001515 }
1516 if (R->isSubClassOf("PointerLikeRegClass")) {
1517 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001518 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001519 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001520
Chris Lattner6070ee22010-03-23 23:50:31 +00001521 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1522 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001523 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001524 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001525 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001526
Tim Northoverc807a172014-05-20 11:52:46 +00001527 if (R->isSubClassOf("Operand"))
1528 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1529
Chris Lattner8cab0212008-01-05 22:25:12 +00001530 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001531 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001532}
1533
Chris Lattner89c65662008-01-06 05:36:50 +00001534
1535/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1536/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1537const CodeGenIntrinsic *TreePatternNode::
1538getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1539 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1540 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1541 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001542 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001543
Sean Silva88eb8dd2012-10-10 20:24:47 +00001544 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001545 return &CDP.getIntrinsicInfo(IID);
1546}
1547
Chris Lattner53c39ba2010-02-14 22:22:58 +00001548/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1549/// return the ComplexPattern information, otherwise return null.
1550const ComplexPattern *
1551TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001552 Record *Rec;
1553 if (isLeaf()) {
1554 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1555 if (!DI)
1556 return nullptr;
1557 Rec = DI->getDef();
1558 } else
1559 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001560
Tim Northoverc807a172014-05-20 11:52:46 +00001561 if (!Rec->isSubClassOf("ComplexPattern"))
1562 return nullptr;
1563 return &CGP.getComplexPattern(Rec);
1564}
1565
1566unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1567 // A ComplexPattern specifically declares how many results it fills in.
1568 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1569 return CP->getNumOperands();
1570
1571 // If MIOperandInfo is specified, that gives the count.
1572 if (isLeaf()) {
1573 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1574 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1575 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1576 if (MIOps->getNumArgs())
1577 return MIOps->getNumArgs();
1578 }
1579 }
1580
1581 // Otherwise there is just one result.
1582 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001583}
1584
1585/// NodeHasProperty - Return true if this node has the specified property.
1586bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001587 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001588 if (isLeaf()) {
1589 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1590 return CP->hasProperty(Property);
1591 return false;
1592 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001593
Chris Lattner53c39ba2010-02-14 22:22:58 +00001594 Record *Operator = getOperator();
1595 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001596
Chris Lattner53c39ba2010-02-14 22:22:58 +00001597 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1598}
1599
1600
1601
1602
1603/// TreeHasProperty - Return true if any node in this tree has the specified
1604/// property.
1605bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001606 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001607 if (NodeHasProperty(Property, CGP))
1608 return true;
1609 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1610 if (getChild(i)->TreeHasProperty(Property, CGP))
1611 return true;
1612 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001613}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001614
Evan Cheng49bad4c2008-06-16 20:29:38 +00001615/// isCommutativeIntrinsic - Return true if the node corresponds to a
1616/// commutative intrinsic.
1617bool
1618TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1619 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1620 return Int->isCommutative;
1621 return false;
1622}
1623
Matt Arsenaulteb492162014-11-02 23:46:51 +00001624static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1625 if (!N->isLeaf())
1626 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001627
Matt Arsenaulteb492162014-11-02 23:46:51 +00001628 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1629 if (DI && DI->getDef()->isSubClassOf(Class))
1630 return true;
1631
1632 return false;
1633}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001634
1635static void emitTooManyOperandsError(TreePattern &TP,
1636 StringRef InstName,
1637 unsigned Expected,
1638 unsigned Actual) {
1639 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1640 " operands but expected only " + Twine(Expected) + "!");
1641}
1642
1643static void emitTooFewOperandsError(TreePattern &TP,
1644 StringRef InstName,
1645 unsigned Actual) {
1646 TP.error("Instruction '" + InstName +
1647 "' expects more than the provided " + Twine(Actual) + " operands!");
1648}
1649
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001650/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001651/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001652/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001653bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001654 if (TP.hasError())
1655 return false;
1656
Chris Lattnerab3242f2008-01-06 01:10:31 +00001657 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001658 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001659 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001660 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001661 bool MadeChange = false;
1662 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1663 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001664 NotRegisters,
1665 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001666 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001667 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001668
Sean Silvafb509ed2012-10-10 20:24:43 +00001669 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001670 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001671
Chris Lattnerf1447252010-03-19 21:37:09 +00001672 // Int inits are always integers. :)
1673 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001674
Chris Lattnerf1447252010-03-19 21:37:09 +00001675 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001676 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001677
Chris Lattnerf1447252010-03-19 21:37:09 +00001678 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001679 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1680 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001681
Craig Topper95198f42013-09-25 06:37:18 +00001682 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001683 // Make sure that the value is representable for this type.
1684 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001685
Richard Smith228e6d42012-08-24 23:29:28 +00001686 // Check that the value doesn't use more bits than we have. It must either
1687 // be a sign- or zero-extended equivalent of the original.
1688 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1689 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001690 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001691
Richard Smith228e6d42012-08-24 23:29:28 +00001692 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001693 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001694 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001695 }
1696 return false;
1697 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001698
Chris Lattner8cab0212008-01-05 22:25:12 +00001699 // special handling for set, which isn't really an SDNode.
1700 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001701 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1702 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001703 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001704
Chris Lattnerf1447252010-03-19 21:37:09 +00001705 TreePatternNode *SetVal = getChild(NC-1);
1706 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1707
Elena Demikhovsky09954792015-03-01 08:23:41 +00001708 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001709 TreePatternNode *Child = getChild(i);
1710 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001711
Chris Lattner8cab0212008-01-05 22:25:12 +00001712 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001713 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1714 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001715 }
1716 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001717 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001718
Chris Lattner5c2182e2010-03-27 02:53:27 +00001719 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001720 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1721
Chris Lattner8cab0212008-01-05 22:25:12 +00001722 bool MadeChange = false;
1723 for (unsigned i = 0; i < getNumChildren(); ++i)
1724 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001725 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001726 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001727
Chris Lattneree820ac2010-02-23 05:51:07 +00001728 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001729 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001730
Chris Lattner8cab0212008-01-05 22:25:12 +00001731 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001732 unsigned NumRetVTs = Int->IS.RetVTs.size();
1733 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001734
Bill Wendling91821472008-11-13 09:08:33 +00001735 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001736 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001737
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001738 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001739 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001740 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001741 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001742 return false;
1743 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001744
1745 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001746 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001747
Chris Lattnerf1447252010-03-19 21:37:09 +00001748 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1749 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001750
Chris Lattnerf1447252010-03-19 21:37:09 +00001751 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1752 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1753 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001754 }
1755 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001756 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001757
Chris Lattneree820ac2010-02-23 05:51:07 +00001758 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001759 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001760
Chris Lattner135091b2010-03-28 08:48:47 +00001761 // Check that the number of operands is sane. Negative operands -> varargs.
1762 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001763 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001764 TP.error(getOperator()->getName() + " node requires exactly " +
1765 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001766 return false;
1767 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001768
Chris Lattner8cab0212008-01-05 22:25:12 +00001769 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1770 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1771 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001772 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001773 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001774
Chris Lattneree820ac2010-02-23 05:51:07 +00001775 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001776 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001777 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001778 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001779
Chris Lattnerd44966f2010-03-27 19:15:02 +00001780 bool MadeChange = false;
1781
1782 // Apply the result types to the node, these come from the things in the
1783 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001784 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1785 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001786 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1787 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001788
Chris Lattnerd44966f2010-03-27 19:15:02 +00001789 // If the instruction has implicit defs, we apply the first one as a result.
1790 // FIXME: This sucks, it should apply all implicit defs.
1791 if (!InstInfo.ImplicitDefs.empty()) {
1792 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001793
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001794 // FIXME: Generalize to multiple possible types and multiple possible
1795 // ImplicitDefs.
1796 MVT::SimpleValueType VT =
1797 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001798
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001799 if (VT != MVT::Other)
1800 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001801 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001802
Chris Lattnercabe0372010-03-15 06:00:16 +00001803 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1804 // be the same.
1805 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001806 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1807 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1808 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001809 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1810 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1811 // variadic.
1812
1813 unsigned NChild = getNumChildren();
1814 if (NChild < 3) {
1815 TP.error("REG_SEQUENCE requires at least 3 operands!");
1816 return false;
1817 }
1818
1819 if (NChild % 2 == 0) {
1820 TP.error("REG_SEQUENCE requires an odd number of operands!");
1821 return false;
1822 }
1823
1824 if (!isOperandClass(getChild(0), "RegisterClass")) {
1825 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1826 return false;
1827 }
1828
1829 for (unsigned I = 1; I < NChild; I += 2) {
1830 TreePatternNode *SubIdxChild = getChild(I + 1);
1831 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1832 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1833 itostr(I + 1) + "!");
1834 return false;
1835 }
1836 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001837 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001838
1839 unsigned ChildNo = 0;
1840 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1841 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001842
Chris Lattner8cab0212008-01-05 22:25:12 +00001843 // If the instruction expects a predicate or optional def operand, we
1844 // codegen this by setting the operand to it's default value if it has a
1845 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001846 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001847 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1848 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001849
Chris Lattner8cab0212008-01-05 22:25:12 +00001850 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001851 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001852 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001853 return false;
1854 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001855
Chris Lattner8cab0212008-01-05 22:25:12 +00001856 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001857 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001858
1859 // If the operand has sub-operands, they may be provided by distinct
1860 // child patterns, so attempt to match each sub-operand separately.
1861 if (OperandNode->isSubClassOf("Operand")) {
1862 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1863 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1864 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001865 // a single ComplexPattern-related Operand.
1866
1867 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001868 // Match first sub-operand against the child we already have.
1869 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1870 MadeChange |=
1871 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1872
1873 // And the remaining sub-operands against subsequent children.
1874 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1875 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001876 emitTooFewOperandsError(TP, getOperator()->getName(),
1877 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001878 return false;
1879 }
1880 Child = getChild(ChildNo++);
1881
1882 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1883 MadeChange |=
1884 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1885 }
1886 continue;
1887 }
1888 }
1889 }
1890
1891 // If we didn't match by pieces above, attempt to match the whole
1892 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001893 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001894 }
Christopher Lamba7312392008-03-11 09:33:47 +00001895
Matt Arsenaulteb492162014-11-02 23:46:51 +00001896 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001897 emitTooManyOperandsError(TP, getOperator()->getName(),
1898 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001899 return false;
1900 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001901
Ulrich Weigande618abd2013-03-19 19:51:09 +00001902 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1903 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001904 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001905 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001906
Tim Northoverc807a172014-05-20 11:52:46 +00001907 if (getOperator()->isSubClassOf("ComplexPattern")) {
1908 bool MadeChange = false;
1909
1910 for (unsigned i = 0; i < getNumChildren(); ++i)
1911 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1912
1913 return MadeChange;
1914 }
1915
Chris Lattneree820ac2010-02-23 05:51:07 +00001916 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001917
Chris Lattneree820ac2010-02-23 05:51:07 +00001918 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001919 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001920 TP.error("Node transform '" + getOperator()->getName() +
1921 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001922 return false;
1923 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001924
Chris Lattnercabe0372010-03-15 06:00:16 +00001925 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1926
Jim Grosbach65586fe2010-12-21 16:16:00 +00001927
Chris Lattneree820ac2010-02-23 05:51:07 +00001928 // If either the output or input of the xform does not have exact
1929 // type info. We assume they must be the same. Otherwise, it is perfectly
1930 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001931#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001932 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001933 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1934 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001935 return MadeChange;
1936 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001937#endif
1938 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001939}
1940
1941/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1942/// RHS of a commutative operation, not the on LHS.
1943static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1944 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1945 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001946 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001947 return true;
1948 return false;
1949}
1950
1951
1952/// canPatternMatch - If it is impossible for this pattern to match on this
1953/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001954/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001955/// that can never possibly work), and to prevent the pattern permuter from
1956/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001957bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001958 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001959 if (isLeaf()) return true;
1960
1961 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1962 if (!getChild(i)->canPatternMatch(Reason, CDP))
1963 return false;
1964
1965 // If this is an intrinsic, handle cases that would make it not match. For
1966 // example, if an operand is required to be an immediate.
1967 if (getOperator()->isSubClassOf("Intrinsic")) {
1968 // TODO:
1969 return true;
1970 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001971
Tim Northoverc807a172014-05-20 11:52:46 +00001972 if (getOperator()->isSubClassOf("ComplexPattern"))
1973 return true;
1974
Chris Lattner8cab0212008-01-05 22:25:12 +00001975 // If this node is a commutative operator, check that the LHS isn't an
1976 // immediate.
1977 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001978 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1979 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001980 // Scan all of the operands of the node and make sure that only the last one
1981 // is a constant node, unless the RHS also is.
1982 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001983 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1984 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001985 if (OnlyOnRHSOfCommutative(getChild(i))) {
1986 Reason="Immediate value must be on the RHS of commutative operators!";
1987 return false;
1988 }
1989 }
1990 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001991
Chris Lattner8cab0212008-01-05 22:25:12 +00001992 return true;
1993}
1994
1995//===----------------------------------------------------------------------===//
1996// TreePattern implementation
1997//
1998
David Greeneaf8ee2c2011-07-29 22:43:06 +00001999TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002000 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2001 isInputPattern(isInput), HasError(false) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002002 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002003 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002004}
2005
David Greeneaf8ee2c2011-07-29 22:43:06 +00002006TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002007 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2008 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002009 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002010}
2011
David Blaikiecf195302014-11-17 22:55:41 +00002012TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002013 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2014 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00002015 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002016}
2017
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002018void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002019 if (HasError)
2020 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002021 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002022 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2023 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002024}
2025
Chris Lattnercabe0372010-03-15 06:00:16 +00002026void TreePattern::ComputeNamedNodes() {
2027 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002028 ComputeNamedNodes(Trees[i]);
Chris Lattnercabe0372010-03-15 06:00:16 +00002029}
2030
2031void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2032 if (!N->getName().empty())
2033 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002034
Chris Lattnercabe0372010-03-15 06:00:16 +00002035 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2036 ComputeNamedNodes(N->getChild(i));
2037}
2038
David Blaikiecf195302014-11-17 22:55:41 +00002039
2040TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002041 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002042 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002043
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002044 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002045 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002046 /// (foo GPR, imm) -> (foo GPR, (imm))
2047 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002048 return ParseTreePattern(
2049 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002050 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002051 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002052
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002053 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002054 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002055 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002056 if (OpName.empty())
2057 error("'node' argument requires a name to match with operand list");
2058 Args.push_back(OpName);
2059 }
2060
2061 Res->setName(OpName);
2062 return Res;
2063 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002064
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002065 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002066 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002067 if (OpName.empty())
2068 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002069 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002070 Args.push_back(OpName);
2071 Res->setName(OpName);
2072 return Res;
2073 }
2074
Sean Silvafb509ed2012-10-10 20:24:43 +00002075 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002076 if (!OpName.empty())
2077 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002078 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002079 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002080
Sean Silvafb509ed2012-10-10 20:24:43 +00002081 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002082 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002083 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002084 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002085 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002086 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002087 }
2088
Sean Silvafb509ed2012-10-10 20:24:43 +00002089 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002090 if (!Dag) {
2091 TheInit->dump();
2092 error("Pattern has unexpected init kind!");
2093 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002094 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002095 if (!OpDef) error("Pattern has unexpected operator type!");
2096 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002097
Chris Lattner8cab0212008-01-05 22:25:12 +00002098 if (Operator->isSubClassOf("ValueType")) {
2099 // If the operator is a ValueType, then this must be "type cast" of a leaf
2100 // node.
2101 if (Dag->getNumArgs() != 1)
2102 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002103
David Blaikiecf195302014-11-17 22:55:41 +00002104 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002105
Chris Lattner8cab0212008-01-05 22:25:12 +00002106 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002107 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2108 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002109
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002110 if (!OpName.empty())
2111 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002112 return New;
2113 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002114
Chris Lattner8cab0212008-01-05 22:25:12 +00002115 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002116 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002117 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002118 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002119 !Operator->isSubClassOf("SDNodeXForm") &&
2120 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002121 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002122 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002123 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002124 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002125
Chris Lattner8cab0212008-01-05 22:25:12 +00002126 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002127 if (isInputPattern) {
2128 if (Operator->isSubClassOf("Instruction") ||
2129 Operator->isSubClassOf("SDNodeXForm"))
2130 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2131 } else {
2132 if (Operator->isSubClassOf("Intrinsic"))
2133 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002134
Chris Lattner2e9eae12010-03-28 06:57:56 +00002135 if (Operator->isSubClassOf("SDNode") &&
2136 Operator->getName() != "imm" &&
2137 Operator->getName() != "fpimm" &&
2138 Operator->getName() != "tglobaltlsaddr" &&
2139 Operator->getName() != "tconstpool" &&
2140 Operator->getName() != "tjumptable" &&
2141 Operator->getName() != "tframeindex" &&
2142 Operator->getName() != "texternalsym" &&
2143 Operator->getName() != "tblockaddress" &&
2144 Operator->getName() != "tglobaladdr" &&
2145 Operator->getName() != "bb" &&
2146 Operator->getName() != "vt")
2147 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2148 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002149
Chris Lattner8cab0212008-01-05 22:25:12 +00002150 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002151
2152 // Parse all the operands.
2153 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002154 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002155
Chris Lattner8cab0212008-01-05 22:25:12 +00002156 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002157 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002158 // convert the intrinsic name to a number.
2159 if (Operator->isSubClassOf("Intrinsic")) {
2160 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2161 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2162
2163 // If this intrinsic returns void, it must have side-effects and thus a
2164 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002165 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002166 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002167 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002168 // Has side-effects, requires chain.
2169 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002170 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002171 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002172
David Greenee32ebf22011-07-29 19:07:07 +00002173 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002174 Children.insert(Children.begin(), IIDNode);
2175 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002176
Tim Northoverc807a172014-05-20 11:52:46 +00002177 if (Operator->isSubClassOf("ComplexPattern")) {
2178 for (unsigned i = 0; i < Children.size(); ++i) {
2179 TreePatternNode *Child = Children[i];
2180
2181 if (Child->getName().empty())
2182 error("All arguments to a ComplexPattern must be named");
2183
2184 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2185 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2186 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2187 auto OperandId = std::make_pair(Operator, i);
2188 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2189 if (PrevOp != ComplexPatternOperands.end()) {
2190 if (PrevOp->getValue() != OperandId)
2191 error("All ComplexPattern operands must appear consistently: "
2192 "in the same order in just one ComplexPattern instance.");
2193 } else
2194 ComplexPatternOperands[Child->getName()] = OperandId;
2195 }
2196 }
2197
Chris Lattnerf1447252010-03-19 21:37:09 +00002198 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002199 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002200 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002201
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002202 if (!Dag->getName().empty()) {
2203 assert(Result->getName().empty());
2204 Result->setName(Dag->getName());
2205 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002206 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002207}
2208
Chris Lattnera787c9e2010-03-28 08:38:32 +00002209/// SimplifyTree - See if we can simplify this tree to eliminate something that
2210/// will never match in favor of something obvious that will. This is here
2211/// strictly as a convenience to target authors because it allows them to write
2212/// more type generic things and have useless type casts fold away.
2213///
2214/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002215static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002216 if (N->isLeaf())
2217 return false;
2218
2219 // If we have a bitconvert with a resolved type and if the source and
2220 // destination types are the same, then the bitconvert is useless, remove it.
2221 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002222 N->getExtType(0).isConcrete() &&
2223 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2224 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002225 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002226 SimplifyTree(N);
2227 return true;
2228 }
2229
2230 // Walk all children.
2231 bool MadeChange = false;
2232 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002233 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002234 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002235 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002236 }
2237 return MadeChange;
2238}
2239
2240
2241
Chris Lattner8cab0212008-01-05 22:25:12 +00002242/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002243/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002244/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002245bool TreePattern::
2246InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2247 if (NamedNodes.empty())
2248 ComputeNamedNodes();
2249
Chris Lattner8cab0212008-01-05 22:25:12 +00002250 bool MadeChange = true;
2251 while (MadeChange) {
2252 MadeChange = false;
Chris Lattnera787c9e2010-03-28 08:38:32 +00002253 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002254 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002255 MadeChange |= SimplifyTree(Trees[i]);
2256 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002257
2258 // If there are constraints on our named nodes, apply them.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002259 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattnercabe0372010-03-15 06:00:16 +00002260 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2261 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002262
Chris Lattnercabe0372010-03-15 06:00:16 +00002263 // If we have input named node types, propagate their types to the named
2264 // values here.
2265 if (InNamedTypes) {
Jim Grosbach37b80932014-07-09 18:55:49 +00002266 if (!InNamedTypes->count(I->getKey())) {
2267 error("Node '" + std::string(I->getKey()) +
2268 "' in output pattern but not input pattern");
2269 return true;
2270 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002271
2272 const SmallVectorImpl<TreePatternNode*> &InNodes =
2273 InNamedTypes->find(I->getKey())->second;
2274
2275 // The input types should be fully resolved by now.
2276 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2277 // If this node is a register class, and it is the root of the pattern
2278 // then we're mapping something onto an input register. We allow
2279 // changing the type of the input register in this case. This allows
2280 // us to match things like:
2281 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
David Blaikiecf195302014-11-17 22:55:41 +00002282 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002283 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002284 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2285 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002286 continue;
2287 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002288
Daniel Dunbard177edf2010-03-21 01:38:21 +00002289 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002290 InNodes[0]->getNumTypes() == 1 &&
2291 "FIXME: cannot name multiple result nodes yet");
2292 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2293 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002294 }
2295 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002296
Chris Lattnercabe0372010-03-15 06:00:16 +00002297 // If there are multiple nodes with the same name, they must all have the
2298 // same type.
2299 if (I->second.size() > 1) {
2300 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002301 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002302 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002303 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002304
Chris Lattnerf1447252010-03-19 21:37:09 +00002305 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2306 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002307 }
2308 }
2309 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002310 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002311
Chris Lattner8cab0212008-01-05 22:25:12 +00002312 bool HasUnresolvedTypes = false;
2313 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2314 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2315 return !HasUnresolvedTypes;
2316}
2317
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002318void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002319 OS << getRecord()->getName();
2320 if (!Args.empty()) {
2321 OS << "(" << Args[0];
2322 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2323 OS << ", " << Args[i];
2324 OS << ")";
2325 }
2326 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002327
Chris Lattner8cab0212008-01-05 22:25:12 +00002328 if (Trees.size() > 1)
2329 OS << "[\n";
2330 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2331 OS << "\t";
2332 Trees[i]->print(OS);
2333 OS << "\n";
2334 }
2335
2336 if (Trees.size() > 1)
2337 OS << "]\n";
2338}
2339
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002340void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002341
2342//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002343// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002344//
2345
Jim Grosbach65586fe2010-12-21 16:16:00 +00002346CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002347 Records(R), Target(R) {
2348
Dale Johannesenb842d522009-02-05 01:49:45 +00002349 Intrinsics = LoadIntrinsics(Records, false);
2350 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002351 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002352 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002353 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002354 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002355 ParseDefaultOperands();
2356 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002357 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002358 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002359
Chris Lattner8cab0212008-01-05 22:25:12 +00002360 // Generate variants. For example, commutative patterns can match
2361 // multiple ways. Add them to PatternsToMatch as well.
2362 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002363
2364 // Infer instruction flags. For example, we can detect loads,
2365 // stores, and side effects in many cases by examining an
2366 // instruction's pattern.
2367 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002368
2369 // Verify that instruction flags match the patterns.
2370 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002371}
2372
Chris Lattnerab3242f2008-01-06 01:10:31 +00002373Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002374 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002375 if (!N || !N->isSubClassOf("SDNode"))
2376 PrintFatalError("Error getting SDNode '" + Name + "'!");
2377
Chris Lattner8cab0212008-01-05 22:25:12 +00002378 return N;
2379}
2380
2381// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002382void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002383 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2384 while (!Nodes.empty()) {
2385 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2386 Nodes.pop_back();
2387 }
2388
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002389 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002390 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2391 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2392 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2393}
2394
2395/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2396/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002397void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002398 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2399 while (!Xforms.empty()) {
2400 Record *XFormNode = Xforms.back();
2401 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002402 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002403 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002404
2405 Xforms.pop_back();
2406 }
2407}
2408
Chris Lattnerab3242f2008-01-06 01:10:31 +00002409void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002410 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2411 while (!AMs.empty()) {
2412 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2413 AMs.pop_back();
2414 }
2415}
2416
2417
2418/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2419/// file, building up the PatternFragments map. After we've collected them all,
2420/// inline fragments together as necessary, so that there are no references left
2421/// inside a pattern fragment to a pattern fragment.
2422///
Hal Finkel2756dc12014-02-28 00:26:56 +00002423void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002424 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002425
Chris Lattnere7170df2008-01-05 22:43:57 +00002426 // First step, parse all of the fragments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002427 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002428 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2429 continue;
2430
David Greeneaf8ee2c2011-07-29 22:43:06 +00002431 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002432 TreePattern *P =
David Blaikie3c6ca232014-11-13 21:40:02 +00002433 (PatternFragments[Fragments[i]] = llvm::make_unique<TreePattern>(
2434 Fragments[i], Tree, !Fragments[i]->isSubClassOf("OutPatFrag"),
2435 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002436
Chris Lattnere7170df2008-01-05 22:43:57 +00002437 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002438 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002439 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002440
Chris Lattnere7170df2008-01-05 22:43:57 +00002441 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002442 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002443
Chris Lattner8cab0212008-01-05 22:25:12 +00002444 // Parse the operands list.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002445 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002446 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002447 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002448 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002449 if (!OpsOp ||
2450 (OpsOp->getDef()->getName() != "ops" &&
2451 OpsOp->getDef()->getName() != "outs" &&
2452 OpsOp->getDef()->getName() != "ins"))
2453 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002454
2455 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002456 Args.clear();
2457 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002458 if (!isa<DefInit>(OpsList->getArg(j)) ||
2459 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002460 P->error("Operands list should all be 'node' values.");
2461 if (OpsList->getArgName(j).empty())
2462 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002463 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002464 P->error("'" + OpsList->getArgName(j) +
2465 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002466 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002467 Args.push_back(OpsList->getArgName(j));
2468 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002469
Chris Lattnere7170df2008-01-05 22:43:57 +00002470 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002471 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002472 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002473
Chris Lattnere7170df2008-01-05 22:43:57 +00002474 // If there is a code init for this fragment, keep track of the fact that
2475 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002476 TreePredicateFn PredFn(P);
2477 if (!PredFn.isAlwaysTrue())
2478 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002479
Chris Lattner8cab0212008-01-05 22:25:12 +00002480 // If there is a node transformation corresponding to this, keep track of
2481 // it.
2482 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2483 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2484 P->getOnlyTree()->setTransformFn(Transform);
2485 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002486
Chris Lattner8cab0212008-01-05 22:25:12 +00002487 // Now that we've parsed all of the tree fragments, do a closure on them so
2488 // that there are not references to PatFrags left inside of them.
Chris Lattner2e253b42008-06-30 03:02:03 +00002489 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002490 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2491 continue;
2492
David Blaikie3c6ca232014-11-13 21:40:02 +00002493 TreePattern &ThePat = *PatternFragments[Fragments[i]];
2494 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002495
Chris Lattner8cab0212008-01-05 22:25:12 +00002496 // Infer as many types as possible. Don't worry about it if we don't infer
2497 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002498 ThePat.InferAllTypes();
2499 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002500
Chris Lattner8cab0212008-01-05 22:25:12 +00002501 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002502 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002503 }
2504}
2505
Chris Lattnerab3242f2008-01-06 01:10:31 +00002506void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002507 std::vector<Record*> DefaultOps;
2508 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002509
2510 // Find some SDNode.
2511 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002512 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002513
Tom Stellardb7246a72012-09-06 14:15:52 +00002514 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2515 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002516
Tom Stellardb7246a72012-09-06 14:15:52 +00002517 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2518 // SomeSDnode so that we can parse this.
2519 std::vector<std::pair<Init*, std::string> > Ops;
2520 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2521 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2522 DefaultInfo->getArgName(op)));
2523 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002524
Tom Stellardb7246a72012-09-06 14:15:52 +00002525 // Create a TreePattern to parse this.
2526 TreePattern P(DefaultOps[i], DI, false, *this);
2527 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002528
Tom Stellardb7246a72012-09-06 14:15:52 +00002529 // Copy the operands over into a DAGDefaultOperand.
2530 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002531
Tom Stellardb7246a72012-09-06 14:15:52 +00002532 TreePatternNode *T = P.getTree(0);
2533 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2534 TreePatternNode *TPN = T->getChild(op);
2535 while (TPN->ApplyTypeConstraints(P, false))
2536 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002537
Tom Stellardb7246a72012-09-06 14:15:52 +00002538 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002539 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2540 DefaultOps[i]->getName() +
2541 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002542 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002543 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002544 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002545
2546 // Insert it into the DefaultOperands map so we can find it later.
2547 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002548 }
2549}
2550
2551/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2552/// instruction input. Return true if this is a real use.
2553static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002554 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002555 // No name -> not interesting.
2556 if (Pat->getName().empty()) {
2557 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002558 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002559 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2560 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002561 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002562 }
2563 return false;
2564 }
2565
2566 Record *Rec;
2567 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002568 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002569 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2570 Rec = DI->getDef();
2571 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002572 Rec = Pat->getOperator();
2573 }
2574
2575 // SRCVALUE nodes are ignored.
2576 if (Rec->getName() == "srcvalue")
2577 return false;
2578
2579 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2580 if (!Slot) {
2581 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002582 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002583 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002584 Record *SlotRec;
2585 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002586 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002587 } else {
2588 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2589 SlotRec = Slot->getOperator();
2590 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002591
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002592 // Ensure that the inputs agree if we've already seen this input.
2593 if (Rec != SlotRec)
2594 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002595 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002596 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002597 return true;
2598}
2599
2600/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2601/// part of "I", the instruction), computing the set of inputs and outputs of
2602/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002603void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002604FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2605 std::map<std::string, TreePatternNode*> &InstInputs,
2606 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002607 std::vector<Record*> &InstImpResults) {
2608 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002609 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002610 if (!isUse && Pat->getTransformFn())
2611 I->error("Cannot specify a transform function for a non-input value!");
2612 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002613 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002614
Chris Lattnerf2d70992010-02-17 06:53:36 +00002615 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002616 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2617 TreePatternNode *Dest = Pat->getChild(i);
2618 if (!Dest->isLeaf())
2619 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002620
Sean Silvafb509ed2012-10-10 20:24:43 +00002621 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002622 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2623 I->error("implicitly defined value should be a register!");
2624 InstImpResults.push_back(Val->getDef());
2625 }
2626 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002627 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002628
Chris Lattnerf2d70992010-02-17 06:53:36 +00002629 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002630 // If this is not a set, verify that the children nodes are not void typed,
2631 // and recurse.
2632 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002633 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002634 I->error("Cannot have void nodes inside of patterns!");
2635 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002636 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002637 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002638
Chris Lattner8cab0212008-01-05 22:25:12 +00002639 // If this is a non-leaf node with no children, treat it basically as if
2640 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002641 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002642
Chris Lattner8cab0212008-01-05 22:25:12 +00002643 if (!isUse && Pat->getTransformFn())
2644 I->error("Cannot specify a transform function for a non-input value!");
2645 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002646 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002647
Chris Lattner8cab0212008-01-05 22:25:12 +00002648 // Otherwise, this is a set, validate and collect instruction results.
2649 if (Pat->getNumChildren() == 0)
2650 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002651
Chris Lattner8cab0212008-01-05 22:25:12 +00002652 if (Pat->getTransformFn())
2653 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002654
Chris Lattner8cab0212008-01-05 22:25:12 +00002655 // Check the set destinations.
2656 unsigned NumDests = Pat->getNumChildren()-1;
2657 for (unsigned i = 0; i != NumDests; ++i) {
2658 TreePatternNode *Dest = Pat->getChild(i);
2659 if (!Dest->isLeaf())
2660 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002661
Sean Silvafb509ed2012-10-10 20:24:43 +00002662 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002663 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002664 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002665 continue;
2666 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002667
2668 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002669 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002670 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002671 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002672 if (Dest->getName().empty())
2673 I->error("set destination must have a name!");
2674 if (InstResults.count(Dest->getName()))
2675 I->error("cannot set '" + Dest->getName() +"' multiple times");
2676 InstResults[Dest->getName()] = Dest;
2677 } else if (Val->getDef()->isSubClassOf("Register")) {
2678 InstImpResults.push_back(Val->getDef());
2679 } else {
2680 I->error("set destination should be a register!");
2681 }
2682 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002683
Chris Lattner8cab0212008-01-05 22:25:12 +00002684 // Verify and collect info from the computation.
2685 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002686 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002687}
2688
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002689//===----------------------------------------------------------------------===//
2690// Instruction Analysis
2691//===----------------------------------------------------------------------===//
2692
2693class InstAnalyzer {
2694 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002695public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002696 bool hasSideEffects;
2697 bool mayStore;
2698 bool mayLoad;
2699 bool isBitcast;
2700 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002701
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002702 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2703 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2704 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002705
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002706 void Analyze(const TreePattern *Pat) {
2707 // Assume only the first tree is the pattern. The others are clobber nodes.
2708 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002709 }
2710
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002711 void Analyze(const PatternToMatch *Pat) {
2712 AnalyzeNode(Pat->getSrcPattern());
2713 }
2714
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002715private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002716 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002717 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002718 return false;
2719
2720 if (N->getNumChildren() != 2)
2721 return false;
2722
2723 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002724 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002725 return false;
2726
2727 const TreePatternNode *N1 = N->getChild(1);
2728 if (N1->isLeaf())
2729 return false;
2730 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2731 return false;
2732
2733 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2734 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2735 return false;
2736 return OpInfo.getEnumName() == "ISD::BITCAST";
2737 }
2738
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002739public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002740 void AnalyzeNode(const TreePatternNode *N) {
2741 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002742 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002743 Record *LeafRec = DI->getDef();
2744 // Handle ComplexPattern leaves.
2745 if (LeafRec->isSubClassOf("ComplexPattern")) {
2746 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2747 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2748 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002749 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002750 }
2751 }
2752 return;
2753 }
2754
2755 // Analyze children.
2756 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2757 AnalyzeNode(N->getChild(i));
2758
2759 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002760 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002761 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002762 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002763 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002764
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002765 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002766 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2767 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2768 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2769 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002770
2771 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2772 // If this is an intrinsic, analyze it.
2773 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2774 mayLoad = true;// These may load memory.
2775
Dan Gohmanddb2d652010-08-05 23:36:21 +00002776 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002777 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2778
Dan Gohmanddb2d652010-08-05 23:36:21 +00002779 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002780 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002781 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002782 }
2783 }
2784
2785};
2786
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002787static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002788 const InstAnalyzer &PatInfo,
2789 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002790 bool Error = false;
2791
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002792 // Remember where InstInfo got its flags.
2793 if (InstInfo.hasUndefFlags())
2794 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002795
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002796 // Check explicitly set flags for consistency.
2797 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2798 !InstInfo.hasSideEffects_Unset) {
2799 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2800 // the pattern has no side effects. That could be useful for div/rem
2801 // instructions that may trap.
2802 if (!InstInfo.hasSideEffects) {
2803 Error = true;
2804 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2805 Twine(InstInfo.hasSideEffects));
2806 }
2807 }
2808
2809 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2810 Error = true;
2811 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2812 Twine(InstInfo.mayStore));
2813 }
2814
2815 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2816 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2817 // Some targets translate imediates to loads.
2818 if (!InstInfo.mayLoad) {
2819 Error = true;
2820 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2821 Twine(InstInfo.mayLoad));
2822 }
2823 }
2824
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002825 // Transfer inferred flags.
2826 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2827 InstInfo.mayStore |= PatInfo.mayStore;
2828 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002829
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002830 // These flags are silently added without any verification.
2831 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002832
2833 // Don't infer isVariadic. This flag means something different on SDNodes and
2834 // instructions. For example, a CALL SDNode is variadic because it has the
2835 // call arguments as operands, but a CALL instruction is not variadic - it
2836 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002837
2838 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002839}
2840
Jim Grosbach514410b2012-07-17 00:47:06 +00002841/// hasNullFragReference - Return true if the DAG has any reference to the
2842/// null_frag operator.
2843static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002844 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002845 if (!OpDef) return false;
2846 Record *Operator = OpDef->getDef();
2847
2848 // If this is the null fragment, return true.
2849 if (Operator->getName() == "null_frag") return true;
2850 // If any of the arguments reference the null fragment, return true.
2851 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002852 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002853 if (Arg && hasNullFragReference(Arg))
2854 return true;
2855 }
2856
2857 return false;
2858}
2859
2860/// hasNullFragReference - Return true if any DAG in the list references
2861/// the null_frag operator.
2862static bool hasNullFragReference(ListInit *LI) {
2863 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002864 DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002865 assert(DI && "non-dag in an instruction Pattern list?!");
2866 if (hasNullFragReference(DI))
2867 return true;
2868 }
2869 return false;
2870}
2871
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002872/// Get all the instructions in a tree.
2873static void
2874getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2875 if (Tree->isLeaf())
2876 return;
2877 if (Tree->getOperator()->isSubClassOf("Instruction"))
2878 Instrs.push_back(Tree->getOperator());
2879 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2880 getInstructionsInTree(Tree->getChild(i), Instrs);
2881}
2882
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002883/// Check the class of a pattern leaf node against the instruction operand it
2884/// represents.
2885static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2886 Record *Leaf) {
2887 if (OI.Rec == Leaf)
2888 return true;
2889
2890 // Allow direct value types to be used in instruction set patterns.
2891 // The type will be checked later.
2892 if (Leaf->isSubClassOf("ValueType"))
2893 return true;
2894
2895 // Patterns can also be ComplexPattern instances.
2896 if (Leaf->isSubClassOf("ComplexPattern"))
2897 return true;
2898
2899 return false;
2900}
2901
Ahmed Bougacha14107512013-10-28 18:07:21 +00002902const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2903 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002904
Craig Topper0d1fb902015-03-10 03:25:04 +00002905 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002906
Craig Topper0d1fb902015-03-10 03:25:04 +00002907 // Parse the instruction.
2908 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2909 // Inline pattern fragments into it.
2910 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002911
Craig Topper0d1fb902015-03-10 03:25:04 +00002912 // Infer as many types as possible. If we cannot infer all of them, we can
2913 // never do anything with this instruction pattern: report it to the user.
2914 if (!I->InferAllTypes())
2915 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002916
Craig Topper0d1fb902015-03-10 03:25:04 +00002917 // InstInputs - Keep track of all of the inputs of the instruction, along
2918 // with the record they are declared as.
2919 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002920
Craig Topper0d1fb902015-03-10 03:25:04 +00002921 // InstResults - Keep track of all the virtual registers that are 'set'
2922 // in the instruction, including what reg class they are.
2923 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002924
Craig Topper0d1fb902015-03-10 03:25:04 +00002925 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002926
Craig Topper0d1fb902015-03-10 03:25:04 +00002927 // Verify that the top-level forms in the instruction are of void type, and
2928 // fill in the InstResults map.
2929 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2930 TreePatternNode *Pat = I->getTree(j);
2931 if (Pat->getNumTypes() != 0)
2932 I->error("Top-level forms in instruction pattern should have"
2933 " void types");
Chris Lattner8cab0212008-01-05 22:25:12 +00002934
Craig Topper0d1fb902015-03-10 03:25:04 +00002935 // Find inputs and outputs, and verify the structure of the uses/defs.
2936 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2937 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002938 }
2939
Craig Topper0d1fb902015-03-10 03:25:04 +00002940 // Now that we have inputs and outputs of the pattern, inspect the operands
2941 // list for the instruction. This determines the order that operands are
2942 // added to the machine instruction the node corresponds to.
2943 unsigned NumResults = InstResults.size();
2944
2945 // Parse the operands list from the (ops) list, validating it.
2946 assert(I->getArgList().empty() && "Args list should still be empty here!");
2947
2948 // Check that all of the results occur first in the list.
2949 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00002950 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00002951 for (unsigned i = 0; i != NumResults; ++i) {
2952 if (i == CGI.Operands.size())
2953 I->error("'" + InstResults.begin()->first +
2954 "' set but does not appear in operand list!");
2955 const std::string &OpName = CGI.Operands[i].Name;
2956
2957 // Check that it exists in InstResults.
2958 TreePatternNode *RNode = InstResults[OpName];
2959 if (!RNode)
2960 I->error("Operand $" + OpName + " does not exist in operand list!");
2961
Craig Topper3a8eb892015-03-20 05:09:06 +00002962 ResNodes.push_back(RNode);
2963
Craig Topper0d1fb902015-03-10 03:25:04 +00002964 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2965 if (!R)
2966 I->error("Operand $" + OpName + " should be a set destination: all "
2967 "outputs must occur before inputs in operand list!");
2968
2969 if (!checkOperandClass(CGI.Operands[i], R))
2970 I->error("Operand $" + OpName + " class mismatch!");
2971
2972 // Remember the return type.
2973 Results.push_back(CGI.Operands[i].Rec);
2974
2975 // Okay, this one checks out.
2976 InstResults.erase(OpName);
2977 }
2978
2979 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2980 // the copy while we're checking the inputs.
2981 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2982
2983 std::vector<TreePatternNode*> ResultNodeOperands;
2984 std::vector<Record*> Operands;
2985 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2986 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2987 const std::string &OpName = Op.Name;
2988 if (OpName.empty())
2989 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2990
2991 if (!InstInputsCheck.count(OpName)) {
2992 // If this is an operand with a DefaultOps set filled in, we can ignore
2993 // this. When we codegen it, we will do so as always executed.
2994 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2995 // Does it have a non-empty DefaultOps field? If so, ignore this
2996 // operand.
2997 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2998 continue;
2999 }
3000 I->error("Operand $" + OpName +
3001 " does not appear in the instruction pattern");
3002 }
3003 TreePatternNode *InVal = InstInputsCheck[OpName];
3004 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3005
3006 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3007 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3008 if (!checkOperandClass(Op, InRec))
3009 I->error("Operand $" + OpName + "'s register class disagrees"
3010 " between the operand and pattern");
3011 }
3012 Operands.push_back(Op.Rec);
3013
3014 // Construct the result for the dest-pattern operand list.
3015 TreePatternNode *OpNode = InVal->clone();
3016
3017 // No predicate is useful on the result.
3018 OpNode->clearPredicateFns();
3019
3020 // Promote the xform function to be an explicit node if set.
3021 if (Record *Xform = OpNode->getTransformFn()) {
3022 OpNode->setTransformFn(nullptr);
3023 std::vector<TreePatternNode*> Children;
3024 Children.push_back(OpNode);
3025 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3026 }
3027
3028 ResultNodeOperands.push_back(OpNode);
3029 }
3030
3031 if (!InstInputsCheck.empty())
3032 I->error("Input operand $" + InstInputsCheck.begin()->first +
3033 " occurs in pattern but not in operands list!");
3034
3035 TreePatternNode *ResultPattern =
3036 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3037 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003038 // Copy fully inferred output node types to instruction result pattern.
3039 for (unsigned i = 0; i != NumResults; ++i) {
3040 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3041 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3042 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003043
3044 // Create and insert the instruction.
3045 // FIXME: InstImpResults should not be part of DAGInstruction.
3046 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3047 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3048
3049 // Use a temporary tree pattern to infer all types and make sure that the
3050 // constructed result is correct. This depends on the instruction already
3051 // being inserted into the DAGInsts map.
3052 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3053 Temp.InferAllTypes(&I->getNamedNodesMap());
3054
3055 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3056 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3057
3058 return TheInsertedInst;
3059}
3060
Ahmed Bougacha14107512013-10-28 18:07:21 +00003061/// ParseInstructions - Parse all of the instructions, inlining and resolving
3062/// any fragments involved. This populates the Instructions list with fully
3063/// resolved instructions.
3064void CodeGenDAGPatterns::ParseInstructions() {
3065 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3066
3067 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Craig Topper24064772014-04-15 07:20:03 +00003068 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003069
3070 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
3071 LI = Instrs[i]->getValueAsListInit("Pattern");
3072
3073 // If there is no pattern, only collect minimal information about the
3074 // instruction for its operand list. We have to assume that there is one
3075 // result, as we have no detailed info. A pattern which references the
3076 // null_frag operator is as-if no pattern were specified. Normally this
3077 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3078 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003079 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003080 std::vector<Record*> Results;
3081 std::vector<Record*> Operands;
3082
3083 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3084
3085 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003086 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3087 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003088
Craig Topper3a8eb892015-03-20 05:09:06 +00003089 // The rest are inputs.
3090 for (unsigned j = InstInfo.Operands.NumDefs,
3091 e = InstInfo.Operands.size(); j < e; ++j)
3092 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003093 }
3094
3095 // Create and insert the instruction.
3096 std::vector<Record*> ImpResults;
3097 Instructions.insert(std::make_pair(Instrs[i],
Craig Topper24064772014-04-15 07:20:03 +00003098 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003099 continue; // no pattern.
3100 }
3101
3102 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
3103 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3104
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003105 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003106 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003107 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003108
Chris Lattner8cab0212008-01-05 22:25:12 +00003109 // If we can, convert the instructions to be patterns that are matched!
Sean Silvaa4e2c5f2012-09-19 01:47:00 +00003110 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
Benjamin Kramerc2dbd5d2009-08-23 10:39:21 +00003111 Instructions.begin(),
Chris Lattner8cab0212008-01-05 22:25:12 +00003112 E = Instructions.end(); II != E; ++II) {
3113 DAGInstruction &TheInst = II->second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003114 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003115 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003116
3117 // FIXME: Assume only the first tree is the pattern. The others are clobber
3118 // nodes.
3119 TreePatternNode *Pattern = I->getTree(0);
3120 TreePatternNode *SrcPattern;
3121 if (Pattern->getOperator()->getName() == "set") {
3122 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3123 } else{
3124 // Not a set (store or something?)
3125 SrcPattern = Pattern;
3126 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003127
Chris Lattner8cab0212008-01-05 22:25:12 +00003128 Record *Instr = II->first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003129 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003130 PatternToMatch(Instr,
3131 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003132 SrcPattern,
3133 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003134 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003135 Instr->getValueAsInt("AddedComplexity"),
3136 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003137 }
3138}
3139
Chris Lattnera7722b62010-02-23 06:55:24 +00003140
3141typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3142
Jim Grosbach65586fe2010-12-21 16:16:00 +00003143static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003144 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003145 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003146 if (!P->getName().empty()) {
3147 NameRecord &Rec = Names[P->getName()];
3148 // If this is the first instance of the name, remember the node.
3149 if (Rec.second++ == 0)
3150 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003151 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003152 PatternTop->error("repetition of value: $" + P->getName() +
3153 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003154 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003155
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003156 if (!P->isLeaf()) {
3157 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003158 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003159 }
3160}
3161
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003162void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003163 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003164 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003165 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003166 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3167 PrintWarning(Pattern->getRecord()->getLoc(),
3168 Twine("Pattern can never match: ") + Reason);
3169 return;
3170 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003171
Chris Lattner1e634e32010-03-01 22:29:19 +00003172 // If the source pattern's root is a complex pattern, that complex pattern
3173 // must specify the nodes it can potentially match.
3174 if (const ComplexPattern *CP =
3175 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3176 if (CP->getRootNodes().empty())
3177 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3178 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003179
3180
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003181 // Find all of the named values in the input and output, ensure they have the
3182 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003183 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003184 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3185 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003186
3187 // Scan all of the named values in the destination pattern, rejecting them if
3188 // they don't exist in the input pattern.
Chris Lattnera7722b62010-02-23 06:55:24 +00003189 for (std::map<std::string, NameRecord>::iterator
Chris Lattner4b9225b2010-02-23 07:50:58 +00003190 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Craig Topper24064772014-04-15 07:20:03 +00003191 if (SrcNames[I->first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003192 Pattern->error("Pattern has input without matching name in output: $" +
3193 I->first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003194 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003195
Chris Lattnera7722b62010-02-23 06:55:24 +00003196 // Scan all of the named values in the source pattern, rejecting them if the
3197 // name isn't used in the dest, and isn't used to tie two values together.
3198 for (std::map<std::string, NameRecord>::iterator
3199 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
Craig Topper24064772014-04-15 07:20:03 +00003200 if (DstNames[I->first].first == nullptr && SrcNames[I->first].second == 1)
Chris Lattnera7722b62010-02-23 06:55:24 +00003201 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003202
Chris Lattner0c0baa92010-02-23 06:16:51 +00003203 PatternsToMatch.push_back(PTM);
3204}
3205
3206
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003207
3208void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003209 const std::vector<const CodeGenInstruction*> &Instructions =
3210 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003211
3212 // First try to infer flags from the primary instruction pattern, if any.
3213 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003214 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003215 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3216 CodeGenInstruction &InstInfo =
3217 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003218
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003219 // Get the primary instruction pattern.
3220 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3221 if (!Pattern) {
3222 if (InstInfo.hasUndefFlags())
3223 Revisit.push_back(&InstInfo);
3224 continue;
3225 }
3226 InstAnalyzer PatInfo(*this);
3227 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003228 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003229 }
3230
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003231 // Second, look for single-instruction patterns defined outside the
3232 // instruction.
3233 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3234 const PatternToMatch &PTM = *I;
3235
3236 // We can only infer from single-instruction patterns, otherwise we won't
3237 // know which instruction should get the flags.
3238 SmallVector<Record*, 8> PatInstrs;
3239 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3240 if (PatInstrs.size() != 1)
3241 continue;
3242
3243 // Get the single instruction.
3244 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3245
3246 // Only infer properties from the first pattern. We'll verify the others.
3247 if (InstInfo.InferredFrom)
3248 continue;
3249
3250 InstAnalyzer PatInfo(*this);
3251 PatInfo.Analyze(&PTM);
3252 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3253 }
3254
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003255 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003256 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003257
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003258 // Revisit instructions with undefined flags and no pattern.
3259 if (Target.guessInstructionProperties()) {
3260 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3261 CodeGenInstruction &InstInfo = *Revisit[i];
3262 if (InstInfo.InferredFrom)
3263 continue;
3264 // The mayLoad and mayStore flags default to false.
3265 // Conservatively assume hasSideEffects if it wasn't explicit.
3266 if (InstInfo.hasSideEffects_Unset)
3267 InstInfo.hasSideEffects = true;
3268 }
3269 return;
3270 }
3271
3272 // Complain about any flags that are still undefined.
3273 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3274 CodeGenInstruction &InstInfo = *Revisit[i];
3275 if (InstInfo.InferredFrom)
3276 continue;
3277 if (InstInfo.hasSideEffects_Unset)
3278 PrintError(InstInfo.TheDef->getLoc(),
3279 "Can't infer hasSideEffects from patterns");
3280 if (InstInfo.mayStore_Unset)
3281 PrintError(InstInfo.TheDef->getLoc(),
3282 "Can't infer mayStore from patterns");
3283 if (InstInfo.mayLoad_Unset)
3284 PrintError(InstInfo.TheDef->getLoc(),
3285 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003286 }
3287}
3288
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003289
3290/// Verify instruction flags against pattern node properties.
3291void CodeGenDAGPatterns::VerifyInstructionFlags() {
3292 unsigned Errors = 0;
3293 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3294 const PatternToMatch &PTM = *I;
3295 SmallVector<Record*, 8> Instrs;
3296 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3297 if (Instrs.empty())
3298 continue;
3299
3300 // Count the number of instructions with each flag set.
3301 unsigned NumSideEffects = 0;
3302 unsigned NumStores = 0;
3303 unsigned NumLoads = 0;
3304 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3305 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3306 NumSideEffects += InstInfo.hasSideEffects;
3307 NumStores += InstInfo.mayStore;
3308 NumLoads += InstInfo.mayLoad;
3309 }
3310
3311 // Analyze the source pattern.
3312 InstAnalyzer PatInfo(*this);
3313 PatInfo.Analyze(&PTM);
3314
3315 // Collect error messages.
3316 SmallVector<std::string, 4> Msgs;
3317
3318 // Check for missing flags in the output.
3319 // Permit extra flags for now at least.
3320 if (PatInfo.hasSideEffects && !NumSideEffects)
3321 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3322
3323 // Don't verify store flags on instructions with side effects. At least for
3324 // intrinsics, side effects implies mayStore.
3325 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3326 Msgs.push_back("pattern may store, but mayStore isn't set");
3327
3328 // Similarly, mayStore implies mayLoad on intrinsics.
3329 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3330 Msgs.push_back("pattern may load, but mayLoad isn't set");
3331
3332 // Print error messages.
3333 if (Msgs.empty())
3334 continue;
3335 ++Errors;
3336
3337 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3338 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3339 (Instrs.size() == 1 ?
3340 "instruction" : "output instructions"));
3341 // Provide the location of the relevant instruction definitions.
3342 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3343 if (Instrs[i] != PTM.getSrcRecord())
3344 PrintError(Instrs[i]->getLoc(), "defined here");
3345 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3346 if (InstInfo.InferredFrom &&
3347 InstInfo.InferredFrom != InstInfo.TheDef &&
3348 InstInfo.InferredFrom != PTM.getSrcRecord())
3349 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
3350 }
3351 }
3352 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003353 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003354}
3355
Chris Lattnercabe0372010-03-15 06:00:16 +00003356/// Given a pattern result with an unresolved type, see if we can find one
3357/// instruction with an unresolved result type. Force this result type to an
3358/// arbitrary element if it's possible types to converge results.
3359static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3360 if (N->isLeaf())
3361 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003362
Chris Lattnercabe0372010-03-15 06:00:16 +00003363 // Analyze children.
3364 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3365 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3366 return true;
3367
3368 if (!N->getOperator()->isSubClassOf("Instruction"))
3369 return false;
3370
3371 // If this type is already concrete or completely unknown we can't do
3372 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003373 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3374 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3375 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003376
Chris Lattnerf1447252010-03-19 21:37:09 +00003377 // Otherwise, force its type to the first possibility (an arbitrary choice).
3378 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3379 return true;
3380 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003381
Chris Lattnerf1447252010-03-19 21:37:09 +00003382 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003383}
3384
Chris Lattnerab3242f2008-01-06 01:10:31 +00003385void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003386 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3387
3388 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003389 Record *CurPattern = Patterns[i];
David Greeneaf8ee2c2011-07-29 22:43:06 +00003390 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003391
3392 // If the pattern references the null_frag, there's nothing to do.
3393 if (hasNullFragReference(Tree))
3394 continue;
3395
Chris Lattner5c2182e2010-03-27 02:53:27 +00003396 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003397
3398 // Inline pattern fragments into it.
3399 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003400
David Greeneaf8ee2c2011-07-29 22:43:06 +00003401 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003402 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003403
Chris Lattner8cab0212008-01-05 22:25:12 +00003404 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003405 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003406
Chris Lattner8cab0212008-01-05 22:25:12 +00003407 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003408 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003409
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003410 if (Result.getNumTrees() != 1)
3411 Result.error("Cannot handle instructions producing instructions "
3412 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003413
Chris Lattner8cab0212008-01-05 22:25:12 +00003414 bool IterateInference;
3415 bool InferredAllPatternTypes, InferredAllResultTypes;
3416 do {
3417 // Infer as many types as possible. If we cannot infer all of them, we
3418 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003419 InferredAllPatternTypes =
3420 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003421
Chris Lattner8cab0212008-01-05 22:25:12 +00003422 // Infer as many types as possible. If we cannot infer all of them, we
3423 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003424 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003425 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003426
Chris Lattnerfdc20712010-03-18 23:15:10 +00003427 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003428
Chris Lattner8cab0212008-01-05 22:25:12 +00003429 // Apply the type of the result to the source pattern. This helps us
3430 // resolve cases where the input type is known to be a pointer type (which
3431 // is considered resolved), but the result knows it needs to be 32- or
3432 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003433 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003434 Pattern->getTree(0)->getNumTypes());
3435 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003436 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3437 i, Result.getTree(0)->getExtType(i), Result);
3438 IterateInference |= Result.getTree(0)->UpdateNodeType(
3439 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003440 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003441
Chris Lattnercabe0372010-03-15 06:00:16 +00003442 // If our iteration has converged and the input pattern's types are fully
3443 // resolved but the result pattern is not fully resolved, we may have a
3444 // situation where we have two instructions in the result pattern and
3445 // the instructions require a common register class, but don't care about
3446 // what actual MVT is used. This is actually a bug in our modelling:
3447 // output patterns should have register classes, not MVTs.
3448 //
3449 // In any case, to handle this, we just go through and disambiguate some
3450 // arbitrary types to the result pattern's nodes.
3451 if (!IterateInference && InferredAllPatternTypes &&
3452 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003453 IterateInference =
3454 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003455 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003456
Chris Lattner8cab0212008-01-05 22:25:12 +00003457 // Verify that we inferred enough types that we can do something with the
3458 // pattern and result. If these fire the user has to add type casts.
3459 if (!InferredAllPatternTypes)
3460 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003461 if (!InferredAllResultTypes) {
3462 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003463 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003464 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003465
Chris Lattner8cab0212008-01-05 22:25:12 +00003466 // Validate that the input pattern is correct.
3467 std::map<std::string, TreePatternNode*> InstInputs;
3468 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003469 std::vector<Record*> InstImpResults;
3470 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3471 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3472 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003473 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003474
3475 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003476 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003477 std::vector<TreePatternNode*> ResultNodeOperands;
3478 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3479 TreePatternNode *OpNode = DstPattern->getChild(ii);
3480 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003481 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003482 std::vector<TreePatternNode*> Children;
3483 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003484 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003485 }
3486 ResultNodeOperands.push_back(OpNode);
3487 }
David Blaikiecf195302014-11-17 22:55:41 +00003488 DstPattern = Result.getOnlyTree();
3489 if (!DstPattern->isLeaf())
3490 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3491 ResultNodeOperands,
3492 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003493
David Blaikiecf195302014-11-17 22:55:41 +00003494 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3495 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3496
3497 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003498 Temp.InferAllTypes();
3499
Jim Grosbach65586fe2010-12-21 16:16:00 +00003500
Chris Lattner0c0baa92010-02-23 06:16:51 +00003501 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003502 PatternToMatch(CurPattern,
3503 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003504 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003505 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003506 CurPattern->getValueAsInt("AddedComplexity"),
3507 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003508 }
3509}
3510
3511/// CombineChildVariants - Given a bunch of permutations of each child of the
3512/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003513static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003514 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3515 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003516 CodeGenDAGPatterns &CDP,
3517 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003518 // Make sure that each operand has at least one variant to choose from.
3519 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3520 if (ChildVariants[i].empty())
3521 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003522
Chris Lattner8cab0212008-01-05 22:25:12 +00003523 // The end result is an all-pairs construction of the resultant pattern.
3524 std::vector<unsigned> Idxs;
3525 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003526 bool NotDone;
3527 do {
3528#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003529 DEBUG(if (!Idxs.empty()) {
3530 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3531 for (unsigned i = 0; i < Idxs.size(); ++i) {
3532 errs() << Idxs[i] << " ";
3533 }
3534 errs() << "]\n";
3535 });
Scott Michel94420742008-03-05 17:49:05 +00003536#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003537 // Create the variant and add it to the output list.
3538 std::vector<TreePatternNode*> NewChildren;
3539 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3540 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerf1447252010-03-19 21:37:09 +00003541 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3542 Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003543
Chris Lattner8cab0212008-01-05 22:25:12 +00003544 // Copy over properties.
3545 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003546 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003547 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003548 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3549 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003550
Scott Michel94420742008-03-05 17:49:05 +00003551 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003552 std::string ErrString;
3553 if (!R->canPatternMatch(ErrString, CDP)) {
3554 delete R;
3555 } else {
3556 bool AlreadyExists = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003557
Chris Lattner8cab0212008-01-05 22:25:12 +00003558 // Scan to see if this pattern has already been emitted. We can get
3559 // duplication due to things like commuting:
3560 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3561 // which are the same pattern. Ignore the dups.
3562 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003563 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003564 AlreadyExists = true;
3565 break;
3566 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003567
Chris Lattner8cab0212008-01-05 22:25:12 +00003568 if (AlreadyExists)
3569 delete R;
3570 else
3571 OutVariants.push_back(R);
3572 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003573
Scott Michel94420742008-03-05 17:49:05 +00003574 // Increment indices to the next permutation by incrementing the
3575 // indicies from last index backward, e.g., generate the sequence
3576 // [0, 0], [0, 1], [1, 0], [1, 1].
3577 int IdxsIdx;
3578 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3579 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3580 Idxs[IdxsIdx] = 0;
3581 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003582 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003583 }
Scott Michel94420742008-03-05 17:49:05 +00003584 NotDone = (IdxsIdx >= 0);
3585 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003586}
3587
3588/// CombineChildVariants - A helper function for binary operators.
3589///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003590static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003591 const std::vector<TreePatternNode*> &LHS,
3592 const std::vector<TreePatternNode*> &RHS,
3593 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003594 CodeGenDAGPatterns &CDP,
3595 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003596 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3597 ChildVariants.push_back(LHS);
3598 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003599 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003600}
Chris Lattner8cab0212008-01-05 22:25:12 +00003601
3602
3603static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3604 std::vector<TreePatternNode *> &Children) {
3605 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3606 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003607
Chris Lattner8cab0212008-01-05 22:25:12 +00003608 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003609 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003610 N->getTransformFn()) {
3611 Children.push_back(N);
3612 return;
3613 }
3614
3615 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3616 Children.push_back(N->getChild(0));
3617 else
3618 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3619
3620 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3621 Children.push_back(N->getChild(1));
3622 else
3623 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3624}
3625
3626/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3627/// the (potentially recursive) pattern by using algebraic laws.
3628///
3629static void GenerateVariantsOf(TreePatternNode *N,
3630 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003631 CodeGenDAGPatterns &CDP,
3632 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003633 // We cannot permute leaves or ComplexPattern uses.
3634 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003635 OutVariants.push_back(N);
3636 return;
3637 }
3638
3639 // Look up interesting info about the node.
3640 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3641
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003642 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003643 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003644 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003645 std::vector<TreePatternNode*> MaximalChildren;
3646 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3647
3648 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3649 // permutations.
3650 if (MaximalChildren.size() == 3) {
3651 // Find the variants of all of our maximal children.
3652 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003653 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3654 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3655 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003656
Chris Lattner8cab0212008-01-05 22:25:12 +00003657 // There are only two ways we can permute the tree:
3658 // (A op B) op C and A op (B op C)
3659 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003660
Chris Lattner8cab0212008-01-05 22:25:12 +00003661 // Generate legal pair permutations of A/B/C.
3662 std::vector<TreePatternNode*> ABVariants;
3663 std::vector<TreePatternNode*> BAVariants;
3664 std::vector<TreePatternNode*> ACVariants;
3665 std::vector<TreePatternNode*> CAVariants;
3666 std::vector<TreePatternNode*> BCVariants;
3667 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003668 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3669 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3670 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3671 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3672 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3673 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003674
3675 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003676 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3677 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3678 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3679 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3680 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3681 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003682
3683 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003684 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3685 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3686 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3687 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3688 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3689 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003690 return;
3691 }
3692 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003693
Chris Lattner8cab0212008-01-05 22:25:12 +00003694 // Compute permutations of all children.
3695 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3696 ChildVariants.resize(N->getNumChildren());
3697 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003698 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003699
3700 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003701 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003702
3703 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003704 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3705 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3706 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3707 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003708 // Don't count children which are actually register references.
3709 unsigned NC = 0;
3710 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3711 TreePatternNode *Child = N->getChild(i);
3712 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003713 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003714 Record *RR = DI->getDef();
3715 if (RR->isSubClassOf("Register"))
3716 continue;
3717 }
3718 NC++;
3719 }
3720 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003721 if (isCommIntrinsic) {
3722 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3723 // operands are the commutative operands, and there might be more operands
3724 // after those.
3725 assert(NC >= 3 &&
3726 "Commutative intrinsic should have at least 3 childrean!");
3727 std::vector<std::vector<TreePatternNode*> > Variants;
3728 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3729 Variants.push_back(ChildVariants[2]);
3730 Variants.push_back(ChildVariants[1]);
3731 for (unsigned i = 3; i != NC; ++i)
3732 Variants.push_back(ChildVariants[i]);
3733 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3734 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003735 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003736 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003737 }
3738}
3739
3740
3741// GenerateVariants - Generate variants. For example, commutative patterns can
3742// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003743void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003744 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003745
Chris Lattner8cab0212008-01-05 22:25:12 +00003746 // Loop over all of the patterns we've collected, checking to see if we can
3747 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003748 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003749 // the .td file having to contain tons of variants of instructions.
3750 //
3751 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3752 // intentionally do not reconsider these. Any variants of added patterns have
3753 // already been added.
3754 //
3755 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003756 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003757 std::vector<TreePatternNode*> Variants;
Scott Michel94420742008-03-05 17:49:05 +00003758 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003759 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003760 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003761 DEBUG(errs() << "\n");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003762 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3763 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003764
3765 assert(!Variants.empty() && "Must create at least original variant!");
3766 Variants.erase(Variants.begin()); // Remove the original pattern.
3767
3768 if (Variants.empty()) // No variants for this pattern.
3769 continue;
3770
Chris Lattner34822f62009-08-23 04:44:11 +00003771 DEBUG(errs() << "FOUND VARIANTS OF: ";
3772 PatternsToMatch[i].getSrcPattern()->dump();
3773 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003774
3775 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3776 TreePatternNode *Variant = Variants[v];
3777
Chris Lattner34822f62009-08-23 04:44:11 +00003778 DEBUG(errs() << " VAR#" << v << ": ";
3779 Variant->dump();
3780 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003781
Chris Lattner8cab0212008-01-05 22:25:12 +00003782 // Scan to see if an instruction or explicit pattern already matches this.
3783 bool AlreadyExists = false;
3784 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003785 // Skip if the top level predicates do not match.
3786 if (PatternsToMatch[i].getPredicates() !=
3787 PatternsToMatch[p].getPredicates())
3788 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003789 // Check to see if this variant already exists.
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003790 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3791 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003792 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003793 AlreadyExists = true;
3794 break;
3795 }
3796 }
3797 // If we already have it, ignore the variant.
3798 if (AlreadyExists) continue;
3799
3800 // Otherwise, add it to the list of patterns we have.
3801 PatternsToMatch.
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003802 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3803 PatternsToMatch[i].getPredicates(),
Chris Lattner8cab0212008-01-05 22:25:12 +00003804 Variant, PatternsToMatch[i].getDstPattern(),
3805 PatternsToMatch[i].getDstRegs(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003806 PatternsToMatch[i].getAddedComplexity(),
3807 Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003808 }
3809
Chris Lattner34822f62009-08-23 04:44:11 +00003810 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003811 }
3812}