blob: 147f6c9d29572d3d9c7129380650b1c1e0b86742 [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 {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +0000916 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +0000917 exit(1);
918 }
919}
920
921/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000922/// N, and the result number in ResNo.
923static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
924 const SDNodeInfo &NodeInfo,
925 unsigned &ResNo) {
926 unsigned NumResults = NodeInfo.getNumResults();
927 if (OpNo < NumResults) {
928 ResNo = OpNo;
929 return N;
930 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000931
Chris Lattner2db7aba2010-03-19 21:56:21 +0000932 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000933
Chris Lattner2db7aba2010-03-19 21:56:21 +0000934 if (OpNo >= N->getNumChildren()) {
Jim Grosbach65586fe2010-12-21 16:16:00 +0000935 errs() << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000936 << (OpNo+NumResults) << " ";
Chris Lattner8cab0212008-01-05 22:25:12 +0000937 N->dump();
Daniel Dunbar38a22bf2009-07-03 00:10:29 +0000938 errs() << '\n';
Chris Lattner8cab0212008-01-05 22:25:12 +0000939 exit(1);
940 }
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 {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001119 errs() << "Unknown SD Node property '" << PropList[i]->getName()
1120 << "' on node '" << R->getName() << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +00001121 exit(1);
1122 }
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 Topper35b3dbc2015-03-05 07:17:52 +00001199 // FIXME: Should allow access to all the results here.
1200 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001201
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001202 // Add on one implicit def if it has a resolvable type.
1203 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1204 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001205 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001206 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001207
Chris Lattnerf1447252010-03-19 21:37:09 +00001208 if (Operator->isSubClassOf("SDNodeXForm"))
1209 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001210
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001211 if (Operator->isSubClassOf("ValueType"))
1212 return 1; // A type-cast of one result.
1213
Tim Northoverc807a172014-05-20 11:52:46 +00001214 if (Operator->isSubClassOf("ComplexPattern"))
1215 return 1;
1216
Chris Lattnerf1447252010-03-19 21:37:09 +00001217 Operator->dump();
1218 errs() << "Unhandled node in GetNumNodeResults\n";
1219 exit(1);
1220}
1221
1222void TreePatternNode::print(raw_ostream &OS) const {
1223 if (isLeaf())
1224 OS << *getLeafValue();
1225 else
1226 OS << '(' << getOperator()->getName();
1227
1228 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1229 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001230
1231 if (!isLeaf()) {
1232 if (getNumChildren() != 0) {
1233 OS << " ";
1234 getChild(0)->print(OS);
1235 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1236 OS << ", ";
1237 getChild(i)->print(OS);
1238 }
1239 }
1240 OS << ")";
1241 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001242
Dan Gohman6e979022008-10-15 06:17:21 +00001243 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner514e2922011-04-17 21:38:24 +00001244 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001245 if (TransformFn)
1246 OS << "<<X:" << TransformFn->getName() << ">>";
1247 if (!getName().empty())
1248 OS << ":$" << getName();
1249
1250}
1251void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001252 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001253}
1254
Scott Michel94420742008-03-05 17:49:05 +00001255/// isIsomorphicTo - Return true if this node is recursively
1256/// isomorphic to the specified node. For this comparison, the node's
1257/// entire state is considered. The assigned name is ignored, since
1258/// nodes with differing names are considered isomorphic. However, if
1259/// the assigned name is present in the dependent variable set, then
1260/// the assigned name is considered significant and the node is
1261/// isomorphic if the names match.
1262bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1263 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001264 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001265 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001266 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001267 getTransformFn() != N->getTransformFn())
1268 return false;
1269
1270 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001271 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1272 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001273 return ((DI->getDef() == NDI->getDef())
1274 && (DepVars.find(getName()) == DepVars.end()
1275 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001276 }
1277 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001278 return getLeafValue() == N->getLeafValue();
1279 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001280
Chris Lattner8cab0212008-01-05 22:25:12 +00001281 if (N->getOperator() != getOperator() ||
1282 N->getNumChildren() != getNumChildren()) return false;
1283 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001284 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001285 return false;
1286 return true;
1287}
1288
1289/// clone - Make a copy of this tree and all of its children.
1290///
1291TreePatternNode *TreePatternNode::clone() const {
1292 TreePatternNode *New;
1293 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001294 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001295 } else {
1296 std::vector<TreePatternNode*> CChildren;
1297 CChildren.reserve(Children.size());
1298 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1299 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001300 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001301 }
1302 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001303 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001304 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001305 New->setTransformFn(getTransformFn());
1306 return New;
1307}
1308
Chris Lattner53c39ba2010-02-14 22:22:58 +00001309/// RemoveAllTypes - Recursively strip all the types of this tree.
1310void TreePatternNode::RemoveAllTypes() {
Chris Lattnerf1447252010-03-19 21:37:09 +00001311 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1312 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner53c39ba2010-02-14 22:22:58 +00001313 if (isLeaf()) return;
1314 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1315 getChild(i)->RemoveAllTypes();
1316}
1317
1318
Chris Lattner8cab0212008-01-05 22:25:12 +00001319/// SubstituteFormalArguments - Replace the formal arguments in this tree
1320/// with actual values specified by ArgMap.
1321void TreePatternNode::
1322SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1323 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001324
Chris Lattner8cab0212008-01-05 22:25:12 +00001325 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1326 TreePatternNode *Child = getChild(i);
1327 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001328 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001329 // Note that, when substituting into an output pattern, Val might be an
1330 // UnsetInit.
1331 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1332 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001333 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001334 TreePatternNode *NewChild = ArgMap[Child->getName()];
1335 assert(NewChild && "Couldn't find formal argument!");
1336 assert((Child->getPredicateFns().empty() ||
1337 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1338 "Non-empty child predicate clobbered!");
1339 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001340 }
1341 } else {
1342 getChild(i)->SubstituteFormalArguments(ArgMap);
1343 }
1344 }
1345}
1346
1347
1348/// InlinePatternFragments - If this pattern refers to any pattern
1349/// fragments, inline them into place, giving us a pattern without any
1350/// PatFrag references.
1351TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001352 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001353 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001354
1355 if (isLeaf())
1356 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001357 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001358
Chris Lattner8cab0212008-01-05 22:25:12 +00001359 if (!Op->isSubClassOf("PatFrag")) {
1360 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001361 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1362 TreePatternNode *Child = getChild(i);
1363 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1364
1365 assert((Child->getPredicateFns().empty() ||
1366 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1367 "Non-empty child predicate clobbered!");
1368
1369 setChild(i, NewChild);
1370 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001371 return this;
1372 }
1373
1374 // Otherwise, we found a reference to a fragment. First, look up its
1375 // TreePattern record.
1376 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001377
Chris Lattner8cab0212008-01-05 22:25:12 +00001378 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001379 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001380 TP.error("'" + Op->getName() + "' fragment requires " +
1381 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001382 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001383 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001384
1385 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1386
Chris Lattner514e2922011-04-17 21:38:24 +00001387 TreePredicateFn PredFn(Frag);
1388 if (!PredFn.isAlwaysTrue())
1389 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001390
Chris Lattner8cab0212008-01-05 22:25:12 +00001391 // Resolve formal arguments to their actual value.
1392 if (Frag->getNumArgs()) {
1393 // Compute the map of formal to actual arguments.
1394 std::map<std::string, TreePatternNode*> ArgMap;
1395 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1396 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001397
Chris Lattner8cab0212008-01-05 22:25:12 +00001398 FragTree->SubstituteFormalArguments(ArgMap);
1399 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001400
Chris Lattner8cab0212008-01-05 22:25:12 +00001401 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001402 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1403 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001404
1405 // Transfer in the old predicates.
1406 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1407 FragTree->addPredicateFn(getPredicateFns()[i]);
1408
Chris Lattner8cab0212008-01-05 22:25:12 +00001409 // Get a new copy of this fragment to stitch into here.
1410 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001411
Chris Lattner2e253b42008-06-30 03:02:03 +00001412 // The fragment we inlined could have recursive inlining that is needed. See
1413 // if there are any pattern fragments in it and inline them as needed.
1414 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001415}
1416
1417/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001418/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001419/// references from the register file information, for example.
1420///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001421/// When Unnamed is set, return the type of a DAG operand with no name, such as
1422/// the F8RC register class argument in:
1423///
1424/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1425///
1426/// When Unnamed is false, return the type of a named DAG operand such as the
1427/// GPR:$src operand above.
1428///
Chris Lattnerf1447252010-03-19 21:37:09 +00001429static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001430 bool NotRegisters,
1431 bool Unnamed,
1432 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001433 // Check to see if this is a register operand.
1434 if (R->isSubClassOf("RegisterOperand")) {
1435 assert(ResNo == 0 && "Regoperand ref only has one result!");
1436 if (NotRegisters)
1437 return EEVT::TypeSet(); // Unknown.
1438 Record *RegClass = R->getValueAsDef("RegClass");
1439 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1440 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1441 }
1442
Chris Lattnercabe0372010-03-15 06:00:16 +00001443 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001444 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001445 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001446 // An unnamed register class represents itself as an i32 immediate, for
1447 // example on a COPY_TO_REGCLASS instruction.
1448 if (Unnamed)
1449 return EEVT::TypeSet(MVT::i32, TP);
1450
1451 // In a named operand, the register class provides the possible set of
1452 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001453 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001454 return EEVT::TypeSet(); // Unknown.
1455 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1456 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001457 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001458
Chris Lattner6070ee22010-03-23 23:50:31 +00001459 if (R->isSubClassOf("PatFrag")) {
1460 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001461 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001462 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001463 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001464
Chris Lattner6070ee22010-03-23 23:50:31 +00001465 if (R->isSubClassOf("Register")) {
1466 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001467 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001468 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001469 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001470 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001471 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001472
1473 if (R->isSubClassOf("SubRegIndex")) {
1474 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001475 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001476 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001477
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001478 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001479 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001480 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1481 //
1482 // (sext_inreg GPR:$src, i16)
1483 // ~~~
1484 if (Unnamed)
1485 return EEVT::TypeSet(MVT::Other, TP);
1486 // With a name, the ValueType simply provides the type of the named
1487 // variable.
1488 //
1489 // (sext_inreg i32:$src, i16)
1490 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001491 if (NotRegisters)
1492 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001493 return EEVT::TypeSet(getValueType(R), TP);
1494 }
1495
1496 if (R->isSubClassOf("CondCode")) {
1497 assert(ResNo == 0 && "This node only has one result!");
1498 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001499 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001500 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001501
Chris Lattner6070ee22010-03-23 23:50:31 +00001502 if (R->isSubClassOf("ComplexPattern")) {
1503 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001504 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001505 return EEVT::TypeSet(); // Unknown.
1506 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1507 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001508 }
1509 if (R->isSubClassOf("PointerLikeRegClass")) {
1510 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001511 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001512 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001513
Chris Lattner6070ee22010-03-23 23:50:31 +00001514 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1515 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001516 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001517 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001518 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001519
Tim Northoverc807a172014-05-20 11:52:46 +00001520 if (R->isSubClassOf("Operand"))
1521 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1522
Chris Lattner8cab0212008-01-05 22:25:12 +00001523 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001524 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001525}
1526
Chris Lattner89c65662008-01-06 05:36:50 +00001527
1528/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1529/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1530const CodeGenIntrinsic *TreePatternNode::
1531getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1532 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1533 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1534 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001535 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001536
Sean Silva88eb8dd2012-10-10 20:24:47 +00001537 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001538 return &CDP.getIntrinsicInfo(IID);
1539}
1540
Chris Lattner53c39ba2010-02-14 22:22:58 +00001541/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1542/// return the ComplexPattern information, otherwise return null.
1543const ComplexPattern *
1544TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001545 Record *Rec;
1546 if (isLeaf()) {
1547 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1548 if (!DI)
1549 return nullptr;
1550 Rec = DI->getDef();
1551 } else
1552 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001553
Tim Northoverc807a172014-05-20 11:52:46 +00001554 if (!Rec->isSubClassOf("ComplexPattern"))
1555 return nullptr;
1556 return &CGP.getComplexPattern(Rec);
1557}
1558
1559unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1560 // A ComplexPattern specifically declares how many results it fills in.
1561 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1562 return CP->getNumOperands();
1563
1564 // If MIOperandInfo is specified, that gives the count.
1565 if (isLeaf()) {
1566 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1567 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1568 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1569 if (MIOps->getNumArgs())
1570 return MIOps->getNumArgs();
1571 }
1572 }
1573
1574 // Otherwise there is just one result.
1575 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001576}
1577
1578/// NodeHasProperty - Return true if this node has the specified property.
1579bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001580 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001581 if (isLeaf()) {
1582 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1583 return CP->hasProperty(Property);
1584 return false;
1585 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001586
Chris Lattner53c39ba2010-02-14 22:22:58 +00001587 Record *Operator = getOperator();
1588 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001589
Chris Lattner53c39ba2010-02-14 22:22:58 +00001590 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1591}
1592
1593
1594
1595
1596/// TreeHasProperty - Return true if any node in this tree has the specified
1597/// property.
1598bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001599 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001600 if (NodeHasProperty(Property, CGP))
1601 return true;
1602 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1603 if (getChild(i)->TreeHasProperty(Property, CGP))
1604 return true;
1605 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001606}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001607
Evan Cheng49bad4c2008-06-16 20:29:38 +00001608/// isCommutativeIntrinsic - Return true if the node corresponds to a
1609/// commutative intrinsic.
1610bool
1611TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1612 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1613 return Int->isCommutative;
1614 return false;
1615}
1616
Matt Arsenaulteb492162014-11-02 23:46:51 +00001617static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1618 if (!N->isLeaf())
1619 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001620
Matt Arsenaulteb492162014-11-02 23:46:51 +00001621 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1622 if (DI && DI->getDef()->isSubClassOf(Class))
1623 return true;
1624
1625 return false;
1626}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001627
1628static void emitTooManyOperandsError(TreePattern &TP,
1629 StringRef InstName,
1630 unsigned Expected,
1631 unsigned Actual) {
1632 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1633 " operands but expected only " + Twine(Expected) + "!");
1634}
1635
1636static void emitTooFewOperandsError(TreePattern &TP,
1637 StringRef InstName,
1638 unsigned Actual) {
1639 TP.error("Instruction '" + InstName +
1640 "' expects more than the provided " + Twine(Actual) + " operands!");
1641}
1642
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001643/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001644/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001645/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001646bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001647 if (TP.hasError())
1648 return false;
1649
Chris Lattnerab3242f2008-01-06 01:10:31 +00001650 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001651 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001652 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001653 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001654 bool MadeChange = false;
1655 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1656 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001657 NotRegisters,
1658 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001659 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001660 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001661
Sean Silvafb509ed2012-10-10 20:24:43 +00001662 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001663 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001664
Chris Lattnerf1447252010-03-19 21:37:09 +00001665 // Int inits are always integers. :)
1666 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001667
Chris Lattnerf1447252010-03-19 21:37:09 +00001668 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001669 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001670
Chris Lattnerf1447252010-03-19 21:37:09 +00001671 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001672 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1673 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001674
Craig Topper95198f42013-09-25 06:37:18 +00001675 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001676 // Make sure that the value is representable for this type.
1677 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001678
Richard Smith228e6d42012-08-24 23:29:28 +00001679 // Check that the value doesn't use more bits than we have. It must either
1680 // be a sign- or zero-extended equivalent of the original.
1681 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1682 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001683 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001684
Richard Smith228e6d42012-08-24 23:29:28 +00001685 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001686 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001687 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001688 }
1689 return false;
1690 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001691
Chris Lattner8cab0212008-01-05 22:25:12 +00001692 // special handling for set, which isn't really an SDNode.
1693 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001694 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1695 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001696 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001697
Chris Lattnerf1447252010-03-19 21:37:09 +00001698 TreePatternNode *SetVal = getChild(NC-1);
1699 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1700
Elena Demikhovsky09954792015-03-01 08:23:41 +00001701 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001702 TreePatternNode *Child = getChild(i);
1703 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001704
Chris Lattner8cab0212008-01-05 22:25:12 +00001705 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001706 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1707 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001708 }
1709 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001710 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001711
Chris Lattner5c2182e2010-03-27 02:53:27 +00001712 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001713 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1714
Chris Lattner8cab0212008-01-05 22:25:12 +00001715 bool MadeChange = false;
1716 for (unsigned i = 0; i < getNumChildren(); ++i)
1717 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001718 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001719 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001720
Chris Lattneree820ac2010-02-23 05:51:07 +00001721 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001722 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001723
Chris Lattner8cab0212008-01-05 22:25:12 +00001724 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001725 unsigned NumRetVTs = Int->IS.RetVTs.size();
1726 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001727
Bill Wendling91821472008-11-13 09:08:33 +00001728 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001729 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001730
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001731 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001732 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001733 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001734 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001735 return false;
1736 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001737
1738 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001739 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001740
Chris Lattnerf1447252010-03-19 21:37:09 +00001741 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1742 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001743
Chris Lattnerf1447252010-03-19 21:37:09 +00001744 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1745 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1746 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001747 }
1748 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001749 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001750
Chris Lattneree820ac2010-02-23 05:51:07 +00001751 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001752 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001753
Chris Lattner135091b2010-03-28 08:48:47 +00001754 // Check that the number of operands is sane. Negative operands -> varargs.
1755 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001756 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001757 TP.error(getOperator()->getName() + " node requires exactly " +
1758 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001759 return false;
1760 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001761
Chris Lattner8cab0212008-01-05 22:25:12 +00001762 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1763 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1764 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001765 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001766 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001767
Chris Lattneree820ac2010-02-23 05:51:07 +00001768 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001769 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001770 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001771 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001772
Chris Lattnerd44966f2010-03-27 19:15:02 +00001773 bool MadeChange = false;
1774
1775 // Apply the result types to the node, these come from the things in the
1776 // (outs) list of the instruction.
Craig Topper35b3dbc2015-03-05 07:17:52 +00001777 // FIXME: Cap at one result so far.
1778 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001779 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1780 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001781
Chris Lattnerd44966f2010-03-27 19:15:02 +00001782 // If the instruction has implicit defs, we apply the first one as a result.
1783 // FIXME: This sucks, it should apply all implicit defs.
1784 if (!InstInfo.ImplicitDefs.empty()) {
1785 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001786
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001787 // FIXME: Generalize to multiple possible types and multiple possible
1788 // ImplicitDefs.
1789 MVT::SimpleValueType VT =
1790 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001791
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001792 if (VT != MVT::Other)
1793 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001794 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001795
Chris Lattnercabe0372010-03-15 06:00:16 +00001796 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1797 // be the same.
1798 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001799 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1800 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1801 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001802 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1803 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1804 // variadic.
1805
1806 unsigned NChild = getNumChildren();
1807 if (NChild < 3) {
1808 TP.error("REG_SEQUENCE requires at least 3 operands!");
1809 return false;
1810 }
1811
1812 if (NChild % 2 == 0) {
1813 TP.error("REG_SEQUENCE requires an odd number of operands!");
1814 return false;
1815 }
1816
1817 if (!isOperandClass(getChild(0), "RegisterClass")) {
1818 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1819 return false;
1820 }
1821
1822 for (unsigned I = 1; I < NChild; I += 2) {
1823 TreePatternNode *SubIdxChild = getChild(I + 1);
1824 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1825 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1826 itostr(I + 1) + "!");
1827 return false;
1828 }
1829 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001830 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001831
1832 unsigned ChildNo = 0;
1833 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1834 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001835
Chris Lattner8cab0212008-01-05 22:25:12 +00001836 // If the instruction expects a predicate or optional def operand, we
1837 // codegen this by setting the operand to it's default value if it has a
1838 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001839 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001840 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1841 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001842
Chris Lattner8cab0212008-01-05 22:25:12 +00001843 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001844 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001845 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001846 return false;
1847 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001848
Chris Lattner8cab0212008-01-05 22:25:12 +00001849 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001850 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001851
1852 // If the operand has sub-operands, they may be provided by distinct
1853 // child patterns, so attempt to match each sub-operand separately.
1854 if (OperandNode->isSubClassOf("Operand")) {
1855 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1856 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1857 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001858 // a single ComplexPattern-related Operand.
1859
1860 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001861 // Match first sub-operand against the child we already have.
1862 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1863 MadeChange |=
1864 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1865
1866 // And the remaining sub-operands against subsequent children.
1867 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1868 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001869 emitTooFewOperandsError(TP, getOperator()->getName(),
1870 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001871 return false;
1872 }
1873 Child = getChild(ChildNo++);
1874
1875 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1876 MadeChange |=
1877 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1878 }
1879 continue;
1880 }
1881 }
1882 }
1883
1884 // If we didn't match by pieces above, attempt to match the whole
1885 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001886 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001887 }
Christopher Lamba7312392008-03-11 09:33:47 +00001888
Matt Arsenaulteb492162014-11-02 23:46:51 +00001889 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001890 emitTooManyOperandsError(TP, getOperator()->getName(),
1891 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001892 return false;
1893 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001894
Ulrich Weigande618abd2013-03-19 19:51:09 +00001895 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1896 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001897 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001898 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001899
Tim Northoverc807a172014-05-20 11:52:46 +00001900 if (getOperator()->isSubClassOf("ComplexPattern")) {
1901 bool MadeChange = false;
1902
1903 for (unsigned i = 0; i < getNumChildren(); ++i)
1904 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1905
1906 return MadeChange;
1907 }
1908
Chris Lattneree820ac2010-02-23 05:51:07 +00001909 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001910
Chris Lattneree820ac2010-02-23 05:51:07 +00001911 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001912 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001913 TP.error("Node transform '" + getOperator()->getName() +
1914 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001915 return false;
1916 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001917
Chris Lattnercabe0372010-03-15 06:00:16 +00001918 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1919
Jim Grosbach65586fe2010-12-21 16:16:00 +00001920
Chris Lattneree820ac2010-02-23 05:51:07 +00001921 // If either the output or input of the xform does not have exact
1922 // type info. We assume they must be the same. Otherwise, it is perfectly
1923 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001924#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001925 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001926 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1927 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001928 return MadeChange;
1929 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001930#endif
1931 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001932}
1933
1934/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1935/// RHS of a commutative operation, not the on LHS.
1936static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1937 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1938 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001939 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001940 return true;
1941 return false;
1942}
1943
1944
1945/// canPatternMatch - If it is impossible for this pattern to match on this
1946/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001947/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001948/// that can never possibly work), and to prevent the pattern permuter from
1949/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001950bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001951 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001952 if (isLeaf()) return true;
1953
1954 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1955 if (!getChild(i)->canPatternMatch(Reason, CDP))
1956 return false;
1957
1958 // If this is an intrinsic, handle cases that would make it not match. For
1959 // example, if an operand is required to be an immediate.
1960 if (getOperator()->isSubClassOf("Intrinsic")) {
1961 // TODO:
1962 return true;
1963 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001964
Tim Northoverc807a172014-05-20 11:52:46 +00001965 if (getOperator()->isSubClassOf("ComplexPattern"))
1966 return true;
1967
Chris Lattner8cab0212008-01-05 22:25:12 +00001968 // If this node is a commutative operator, check that the LHS isn't an
1969 // immediate.
1970 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001971 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1972 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001973 // Scan all of the operands of the node and make sure that only the last one
1974 // is a constant node, unless the RHS also is.
1975 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001976 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1977 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001978 if (OnlyOnRHSOfCommutative(getChild(i))) {
1979 Reason="Immediate value must be on the RHS of commutative operators!";
1980 return false;
1981 }
1982 }
1983 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001984
Chris Lattner8cab0212008-01-05 22:25:12 +00001985 return true;
1986}
1987
1988//===----------------------------------------------------------------------===//
1989// TreePattern implementation
1990//
1991
David Greeneaf8ee2c2011-07-29 22:43:06 +00001992TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001993 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1994 isInputPattern(isInput), HasError(false) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001995 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001996 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001997}
1998
David Greeneaf8ee2c2011-07-29 22:43:06 +00001999TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002000 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2001 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002002 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002003}
2004
David Blaikiecf195302014-11-17 22:55:41 +00002005TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002006 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2007 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00002008 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002009}
2010
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002011void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002012 if (HasError)
2013 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002014 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002015 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2016 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002017}
2018
Chris Lattnercabe0372010-03-15 06:00:16 +00002019void TreePattern::ComputeNamedNodes() {
2020 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002021 ComputeNamedNodes(Trees[i]);
Chris Lattnercabe0372010-03-15 06:00:16 +00002022}
2023
2024void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2025 if (!N->getName().empty())
2026 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002027
Chris Lattnercabe0372010-03-15 06:00:16 +00002028 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2029 ComputeNamedNodes(N->getChild(i));
2030}
2031
David Blaikiecf195302014-11-17 22:55:41 +00002032
2033TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002034 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002035 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002036
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002037 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002038 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002039 /// (foo GPR, imm) -> (foo GPR, (imm))
2040 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002041 return ParseTreePattern(
2042 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002043 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002044 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002045
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002046 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002047 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002048 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002049 if (OpName.empty())
2050 error("'node' argument requires a name to match with operand list");
2051 Args.push_back(OpName);
2052 }
2053
2054 Res->setName(OpName);
2055 return Res;
2056 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002057
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002058 // ?:$name or just $name.
2059 if (TheInit == UnsetInit::get()) {
2060 if (OpName.empty())
2061 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002062 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002063 Args.push_back(OpName);
2064 Res->setName(OpName);
2065 return Res;
2066 }
2067
Sean Silvafb509ed2012-10-10 20:24:43 +00002068 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002069 if (!OpName.empty())
2070 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002071 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002072 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002073
Sean Silvafb509ed2012-10-10 20:24:43 +00002074 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002075 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002076 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002077 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002078 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002079 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002080 }
2081
Sean Silvafb509ed2012-10-10 20:24:43 +00002082 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002083 if (!Dag) {
2084 TheInit->dump();
2085 error("Pattern has unexpected init kind!");
2086 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002087 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002088 if (!OpDef) error("Pattern has unexpected operator type!");
2089 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002090
Chris Lattner8cab0212008-01-05 22:25:12 +00002091 if (Operator->isSubClassOf("ValueType")) {
2092 // If the operator is a ValueType, then this must be "type cast" of a leaf
2093 // node.
2094 if (Dag->getNumArgs() != 1)
2095 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002096
David Blaikiecf195302014-11-17 22:55:41 +00002097 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002098
Chris Lattner8cab0212008-01-05 22:25:12 +00002099 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002100 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2101 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002102
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002103 if (!OpName.empty())
2104 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002105 return New;
2106 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002107
Chris Lattner8cab0212008-01-05 22:25:12 +00002108 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002109 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002110 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002111 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002112 !Operator->isSubClassOf("SDNodeXForm") &&
2113 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002114 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002115 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002116 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002117 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002118
Chris Lattner8cab0212008-01-05 22:25:12 +00002119 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002120 if (isInputPattern) {
2121 if (Operator->isSubClassOf("Instruction") ||
2122 Operator->isSubClassOf("SDNodeXForm"))
2123 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2124 } else {
2125 if (Operator->isSubClassOf("Intrinsic"))
2126 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002127
Chris Lattner2e9eae12010-03-28 06:57:56 +00002128 if (Operator->isSubClassOf("SDNode") &&
2129 Operator->getName() != "imm" &&
2130 Operator->getName() != "fpimm" &&
2131 Operator->getName() != "tglobaltlsaddr" &&
2132 Operator->getName() != "tconstpool" &&
2133 Operator->getName() != "tjumptable" &&
2134 Operator->getName() != "tframeindex" &&
2135 Operator->getName() != "texternalsym" &&
2136 Operator->getName() != "tblockaddress" &&
2137 Operator->getName() != "tglobaladdr" &&
2138 Operator->getName() != "bb" &&
2139 Operator->getName() != "vt")
2140 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2141 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002142
Chris Lattner8cab0212008-01-05 22:25:12 +00002143 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002144
2145 // Parse all the operands.
2146 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002147 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002148
Chris Lattner8cab0212008-01-05 22:25:12 +00002149 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002150 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002151 // convert the intrinsic name to a number.
2152 if (Operator->isSubClassOf("Intrinsic")) {
2153 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2154 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2155
2156 // If this intrinsic returns void, it must have side-effects and thus a
2157 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002158 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002159 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002160 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002161 // Has side-effects, requires chain.
2162 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002163 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002164 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002165
David Greenee32ebf22011-07-29 19:07:07 +00002166 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002167 Children.insert(Children.begin(), IIDNode);
2168 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002169
Tim Northoverc807a172014-05-20 11:52:46 +00002170 if (Operator->isSubClassOf("ComplexPattern")) {
2171 for (unsigned i = 0; i < Children.size(); ++i) {
2172 TreePatternNode *Child = Children[i];
2173
2174 if (Child->getName().empty())
2175 error("All arguments to a ComplexPattern must be named");
2176
2177 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2178 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2179 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2180 auto OperandId = std::make_pair(Operator, i);
2181 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2182 if (PrevOp != ComplexPatternOperands.end()) {
2183 if (PrevOp->getValue() != OperandId)
2184 error("All ComplexPattern operands must appear consistently: "
2185 "in the same order in just one ComplexPattern instance.");
2186 } else
2187 ComplexPatternOperands[Child->getName()] = OperandId;
2188 }
2189 }
2190
Chris Lattnerf1447252010-03-19 21:37:09 +00002191 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002192 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002193 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002194
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002195 if (!Dag->getName().empty()) {
2196 assert(Result->getName().empty());
2197 Result->setName(Dag->getName());
2198 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002199 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002200}
2201
Chris Lattnera787c9e2010-03-28 08:38:32 +00002202/// SimplifyTree - See if we can simplify this tree to eliminate something that
2203/// will never match in favor of something obvious that will. This is here
2204/// strictly as a convenience to target authors because it allows them to write
2205/// more type generic things and have useless type casts fold away.
2206///
2207/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002208static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002209 if (N->isLeaf())
2210 return false;
2211
2212 // If we have a bitconvert with a resolved type and if the source and
2213 // destination types are the same, then the bitconvert is useless, remove it.
2214 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002215 N->getExtType(0).isConcrete() &&
2216 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2217 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002218 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002219 SimplifyTree(N);
2220 return true;
2221 }
2222
2223 // Walk all children.
2224 bool MadeChange = false;
2225 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002226 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002227 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002228 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002229 }
2230 return MadeChange;
2231}
2232
2233
2234
Chris Lattner8cab0212008-01-05 22:25:12 +00002235/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002236/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002237/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002238bool TreePattern::
2239InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2240 if (NamedNodes.empty())
2241 ComputeNamedNodes();
2242
Chris Lattner8cab0212008-01-05 22:25:12 +00002243 bool MadeChange = true;
2244 while (MadeChange) {
2245 MadeChange = false;
Chris Lattnera787c9e2010-03-28 08:38:32 +00002246 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002247 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002248 MadeChange |= SimplifyTree(Trees[i]);
2249 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002250
2251 // If there are constraints on our named nodes, apply them.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002252 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattnercabe0372010-03-15 06:00:16 +00002253 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2254 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002255
Chris Lattnercabe0372010-03-15 06:00:16 +00002256 // If we have input named node types, propagate their types to the named
2257 // values here.
2258 if (InNamedTypes) {
Jim Grosbach37b80932014-07-09 18:55:49 +00002259 if (!InNamedTypes->count(I->getKey())) {
2260 error("Node '" + std::string(I->getKey()) +
2261 "' in output pattern but not input pattern");
2262 return true;
2263 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002264
2265 const SmallVectorImpl<TreePatternNode*> &InNodes =
2266 InNamedTypes->find(I->getKey())->second;
2267
2268 // The input types should be fully resolved by now.
2269 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2270 // If this node is a register class, and it is the root of the pattern
2271 // then we're mapping something onto an input register. We allow
2272 // changing the type of the input register in this case. This allows
2273 // us to match things like:
2274 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
David Blaikiecf195302014-11-17 22:55:41 +00002275 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002276 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002277 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2278 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002279 continue;
2280 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002281
Daniel Dunbard177edf2010-03-21 01:38:21 +00002282 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002283 InNodes[0]->getNumTypes() == 1 &&
2284 "FIXME: cannot name multiple result nodes yet");
2285 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2286 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002287 }
2288 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002289
Chris Lattnercabe0372010-03-15 06:00:16 +00002290 // If there are multiple nodes with the same name, they must all have the
2291 // same type.
2292 if (I->second.size() > 1) {
2293 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002294 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002295 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002296 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002297
Chris Lattnerf1447252010-03-19 21:37:09 +00002298 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2299 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002300 }
2301 }
2302 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002303 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002304
Chris Lattner8cab0212008-01-05 22:25:12 +00002305 bool HasUnresolvedTypes = false;
2306 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2307 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2308 return !HasUnresolvedTypes;
2309}
2310
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002311void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002312 OS << getRecord()->getName();
2313 if (!Args.empty()) {
2314 OS << "(" << Args[0];
2315 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2316 OS << ", " << Args[i];
2317 OS << ")";
2318 }
2319 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002320
Chris Lattner8cab0212008-01-05 22:25:12 +00002321 if (Trees.size() > 1)
2322 OS << "[\n";
2323 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2324 OS << "\t";
2325 Trees[i]->print(OS);
2326 OS << "\n";
2327 }
2328
2329 if (Trees.size() > 1)
2330 OS << "]\n";
2331}
2332
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002333void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002334
2335//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002336// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002337//
2338
Jim Grosbach65586fe2010-12-21 16:16:00 +00002339CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002340 Records(R), Target(R) {
2341
Dale Johannesenb842d522009-02-05 01:49:45 +00002342 Intrinsics = LoadIntrinsics(Records, false);
2343 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002344 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002345 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002346 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002347 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002348 ParseDefaultOperands();
2349 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002350 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002351 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002352
Chris Lattner8cab0212008-01-05 22:25:12 +00002353 // Generate variants. For example, commutative patterns can match
2354 // multiple ways. Add them to PatternsToMatch as well.
2355 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002356
2357 // Infer instruction flags. For example, we can detect loads,
2358 // stores, and side effects in many cases by examining an
2359 // instruction's pattern.
2360 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002361
2362 // Verify that instruction flags match the patterns.
2363 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002364}
2365
Chris Lattnerab3242f2008-01-06 01:10:31 +00002366Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002367 Record *N = Records.getDef(Name);
2368 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002369 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +00002370 exit(1);
2371 }
2372 return N;
2373}
2374
2375// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002376void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002377 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2378 while (!Nodes.empty()) {
2379 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2380 Nodes.pop_back();
2381 }
2382
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002383 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002384 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2385 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2386 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2387}
2388
2389/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2390/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002391void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002392 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2393 while (!Xforms.empty()) {
2394 Record *XFormNode = Xforms.back();
2395 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002396 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002397 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002398
2399 Xforms.pop_back();
2400 }
2401}
2402
Chris Lattnerab3242f2008-01-06 01:10:31 +00002403void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002404 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2405 while (!AMs.empty()) {
2406 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2407 AMs.pop_back();
2408 }
2409}
2410
2411
2412/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2413/// file, building up the PatternFragments map. After we've collected them all,
2414/// inline fragments together as necessary, so that there are no references left
2415/// inside a pattern fragment to a pattern fragment.
2416///
Hal Finkel2756dc12014-02-28 00:26:56 +00002417void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002418 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002419
Chris Lattnere7170df2008-01-05 22:43:57 +00002420 // First step, parse all of the fragments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002421 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002422 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2423 continue;
2424
David Greeneaf8ee2c2011-07-29 22:43:06 +00002425 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002426 TreePattern *P =
David Blaikie3c6ca232014-11-13 21:40:02 +00002427 (PatternFragments[Fragments[i]] = llvm::make_unique<TreePattern>(
2428 Fragments[i], Tree, !Fragments[i]->isSubClassOf("OutPatFrag"),
2429 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002430
Chris Lattnere7170df2008-01-05 22:43:57 +00002431 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002432 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002433 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002434
Chris Lattnere7170df2008-01-05 22:43:57 +00002435 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002436 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002437
Chris Lattner8cab0212008-01-05 22:25:12 +00002438 // Parse the operands list.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002439 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002440 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002441 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002442 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002443 if (!OpsOp ||
2444 (OpsOp->getDef()->getName() != "ops" &&
2445 OpsOp->getDef()->getName() != "outs" &&
2446 OpsOp->getDef()->getName() != "ins"))
2447 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002448
2449 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002450 Args.clear();
2451 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002452 if (!isa<DefInit>(OpsList->getArg(j)) ||
2453 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002454 P->error("Operands list should all be 'node' values.");
2455 if (OpsList->getArgName(j).empty())
2456 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002457 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002458 P->error("'" + OpsList->getArgName(j) +
2459 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002460 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002461 Args.push_back(OpsList->getArgName(j));
2462 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002463
Chris Lattnere7170df2008-01-05 22:43:57 +00002464 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002465 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002466 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002467
Chris Lattnere7170df2008-01-05 22:43:57 +00002468 // If there is a code init for this fragment, keep track of the fact that
2469 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002470 TreePredicateFn PredFn(P);
2471 if (!PredFn.isAlwaysTrue())
2472 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002473
Chris Lattner8cab0212008-01-05 22:25:12 +00002474 // If there is a node transformation corresponding to this, keep track of
2475 // it.
2476 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2477 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2478 P->getOnlyTree()->setTransformFn(Transform);
2479 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002480
Chris Lattner8cab0212008-01-05 22:25:12 +00002481 // Now that we've parsed all of the tree fragments, do a closure on them so
2482 // that there are not references to PatFrags left inside of them.
Chris Lattner2e253b42008-06-30 03:02:03 +00002483 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002484 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2485 continue;
2486
David Blaikie3c6ca232014-11-13 21:40:02 +00002487 TreePattern &ThePat = *PatternFragments[Fragments[i]];
2488 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002489
Chris Lattner8cab0212008-01-05 22:25:12 +00002490 // Infer as many types as possible. Don't worry about it if we don't infer
2491 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002492 ThePat.InferAllTypes();
2493 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002494
Chris Lattner8cab0212008-01-05 22:25:12 +00002495 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002496 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002497 }
2498}
2499
Chris Lattnerab3242f2008-01-06 01:10:31 +00002500void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002501 std::vector<Record*> DefaultOps;
2502 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002503
2504 // Find some SDNode.
2505 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002506 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002507
Tom Stellardb7246a72012-09-06 14:15:52 +00002508 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2509 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002510
Tom Stellardb7246a72012-09-06 14:15:52 +00002511 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2512 // SomeSDnode so that we can parse this.
2513 std::vector<std::pair<Init*, std::string> > Ops;
2514 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2515 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2516 DefaultInfo->getArgName(op)));
2517 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002518
Tom Stellardb7246a72012-09-06 14:15:52 +00002519 // Create a TreePattern to parse this.
2520 TreePattern P(DefaultOps[i], DI, false, *this);
2521 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002522
Tom Stellardb7246a72012-09-06 14:15:52 +00002523 // Copy the operands over into a DAGDefaultOperand.
2524 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002525
Tom Stellardb7246a72012-09-06 14:15:52 +00002526 TreePatternNode *T = P.getTree(0);
2527 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2528 TreePatternNode *TPN = T->getChild(op);
2529 while (TPN->ApplyTypeConstraints(P, false))
2530 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002531
Tom Stellardb7246a72012-09-06 14:15:52 +00002532 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002533 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2534 DefaultOps[i]->getName() +
2535 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002536 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002537 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002538 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002539
2540 // Insert it into the DefaultOperands map so we can find it later.
2541 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002542 }
2543}
2544
2545/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2546/// instruction input. Return true if this is a real use.
2547static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002548 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002549 // No name -> not interesting.
2550 if (Pat->getName().empty()) {
2551 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002552 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002553 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2554 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002555 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002556 }
2557 return false;
2558 }
2559
2560 Record *Rec;
2561 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002562 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002563 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2564 Rec = DI->getDef();
2565 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002566 Rec = Pat->getOperator();
2567 }
2568
2569 // SRCVALUE nodes are ignored.
2570 if (Rec->getName() == "srcvalue")
2571 return false;
2572
2573 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2574 if (!Slot) {
2575 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002576 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002577 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002578 Record *SlotRec;
2579 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002580 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002581 } else {
2582 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2583 SlotRec = Slot->getOperator();
2584 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002585
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002586 // Ensure that the inputs agree if we've already seen this input.
2587 if (Rec != SlotRec)
2588 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002589 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002590 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002591 return true;
2592}
2593
2594/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2595/// part of "I", the instruction), computing the set of inputs and outputs of
2596/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002597void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002598FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2599 std::map<std::string, TreePatternNode*> &InstInputs,
2600 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002601 std::vector<Record*> &InstImpResults) {
2602 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002603 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002604 if (!isUse && Pat->getTransformFn())
2605 I->error("Cannot specify a transform function for a non-input value!");
2606 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002607 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002608
Chris Lattnerf2d70992010-02-17 06:53:36 +00002609 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002610 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2611 TreePatternNode *Dest = Pat->getChild(i);
2612 if (!Dest->isLeaf())
2613 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002614
Sean Silvafb509ed2012-10-10 20:24:43 +00002615 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002616 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2617 I->error("implicitly defined value should be a register!");
2618 InstImpResults.push_back(Val->getDef());
2619 }
2620 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002621 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002622
Chris Lattnerf2d70992010-02-17 06:53:36 +00002623 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002624 // If this is not a set, verify that the children nodes are not void typed,
2625 // and recurse.
2626 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002627 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002628 I->error("Cannot have void nodes inside of patterns!");
2629 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002630 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002631 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002632
Chris Lattner8cab0212008-01-05 22:25:12 +00002633 // If this is a non-leaf node with no children, treat it basically as if
2634 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002635 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002636
Chris Lattner8cab0212008-01-05 22:25:12 +00002637 if (!isUse && Pat->getTransformFn())
2638 I->error("Cannot specify a transform function for a non-input value!");
2639 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002640 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002641
Chris Lattner8cab0212008-01-05 22:25:12 +00002642 // Otherwise, this is a set, validate and collect instruction results.
2643 if (Pat->getNumChildren() == 0)
2644 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002645
Chris Lattner8cab0212008-01-05 22:25:12 +00002646 if (Pat->getTransformFn())
2647 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002648
Chris Lattner8cab0212008-01-05 22:25:12 +00002649 // Check the set destinations.
2650 unsigned NumDests = Pat->getNumChildren()-1;
2651 for (unsigned i = 0; i != NumDests; ++i) {
2652 TreePatternNode *Dest = Pat->getChild(i);
2653 if (!Dest->isLeaf())
2654 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002655
Sean Silvafb509ed2012-10-10 20:24:43 +00002656 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002657 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002658 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002659 continue;
2660 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002661
2662 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002663 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002664 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002665 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002666 if (Dest->getName().empty())
2667 I->error("set destination must have a name!");
2668 if (InstResults.count(Dest->getName()))
2669 I->error("cannot set '" + Dest->getName() +"' multiple times");
2670 InstResults[Dest->getName()] = Dest;
2671 } else if (Val->getDef()->isSubClassOf("Register")) {
2672 InstImpResults.push_back(Val->getDef());
2673 } else {
2674 I->error("set destination should be a register!");
2675 }
2676 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002677
Chris Lattner8cab0212008-01-05 22:25:12 +00002678 // Verify and collect info from the computation.
2679 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002680 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002681}
2682
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002683//===----------------------------------------------------------------------===//
2684// Instruction Analysis
2685//===----------------------------------------------------------------------===//
2686
2687class InstAnalyzer {
2688 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002689public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002690 bool hasSideEffects;
2691 bool mayStore;
2692 bool mayLoad;
2693 bool isBitcast;
2694 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002695
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002696 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2697 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2698 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002699
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002700 void Analyze(const TreePattern *Pat) {
2701 // Assume only the first tree is the pattern. The others are clobber nodes.
2702 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002703 }
2704
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002705 void Analyze(const PatternToMatch *Pat) {
2706 AnalyzeNode(Pat->getSrcPattern());
2707 }
2708
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002709private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002710 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002711 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002712 return false;
2713
2714 if (N->getNumChildren() != 2)
2715 return false;
2716
2717 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002718 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002719 return false;
2720
2721 const TreePatternNode *N1 = N->getChild(1);
2722 if (N1->isLeaf())
2723 return false;
2724 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2725 return false;
2726
2727 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2728 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2729 return false;
2730 return OpInfo.getEnumName() == "ISD::BITCAST";
2731 }
2732
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002733public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002734 void AnalyzeNode(const TreePatternNode *N) {
2735 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002736 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002737 Record *LeafRec = DI->getDef();
2738 // Handle ComplexPattern leaves.
2739 if (LeafRec->isSubClassOf("ComplexPattern")) {
2740 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2741 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2742 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002743 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002744 }
2745 }
2746 return;
2747 }
2748
2749 // Analyze children.
2750 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2751 AnalyzeNode(N->getChild(i));
2752
2753 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002754 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002755 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002756 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002757 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002758
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002759 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002760 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2761 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2762 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2763 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002764
2765 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2766 // If this is an intrinsic, analyze it.
2767 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2768 mayLoad = true;// These may load memory.
2769
Dan Gohmanddb2d652010-08-05 23:36:21 +00002770 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002771 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2772
Dan Gohmanddb2d652010-08-05 23:36:21 +00002773 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002774 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002775 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002776 }
2777 }
2778
2779};
2780
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002781static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002782 const InstAnalyzer &PatInfo,
2783 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002784 bool Error = false;
2785
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002786 // Remember where InstInfo got its flags.
2787 if (InstInfo.hasUndefFlags())
2788 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002789
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002790 // Check explicitly set flags for consistency.
2791 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2792 !InstInfo.hasSideEffects_Unset) {
2793 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2794 // the pattern has no side effects. That could be useful for div/rem
2795 // instructions that may trap.
2796 if (!InstInfo.hasSideEffects) {
2797 Error = true;
2798 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2799 Twine(InstInfo.hasSideEffects));
2800 }
2801 }
2802
2803 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2804 Error = true;
2805 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2806 Twine(InstInfo.mayStore));
2807 }
2808
2809 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2810 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2811 // Some targets translate imediates to loads.
2812 if (!InstInfo.mayLoad) {
2813 Error = true;
2814 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2815 Twine(InstInfo.mayLoad));
2816 }
2817 }
2818
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002819 // Transfer inferred flags.
2820 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2821 InstInfo.mayStore |= PatInfo.mayStore;
2822 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002823
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002824 // These flags are silently added without any verification.
2825 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002826
2827 // Don't infer isVariadic. This flag means something different on SDNodes and
2828 // instructions. For example, a CALL SDNode is variadic because it has the
2829 // call arguments as operands, but a CALL instruction is not variadic - it
2830 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002831
2832 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002833}
2834
Jim Grosbach514410b2012-07-17 00:47:06 +00002835/// hasNullFragReference - Return true if the DAG has any reference to the
2836/// null_frag operator.
2837static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002838 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002839 if (!OpDef) return false;
2840 Record *Operator = OpDef->getDef();
2841
2842 // If this is the null fragment, return true.
2843 if (Operator->getName() == "null_frag") return true;
2844 // If any of the arguments reference the null fragment, return true.
2845 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002846 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002847 if (Arg && hasNullFragReference(Arg))
2848 return true;
2849 }
2850
2851 return false;
2852}
2853
2854/// hasNullFragReference - Return true if any DAG in the list references
2855/// the null_frag operator.
2856static bool hasNullFragReference(ListInit *LI) {
2857 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002858 DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002859 assert(DI && "non-dag in an instruction Pattern list?!");
2860 if (hasNullFragReference(DI))
2861 return true;
2862 }
2863 return false;
2864}
2865
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002866/// Get all the instructions in a tree.
2867static void
2868getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2869 if (Tree->isLeaf())
2870 return;
2871 if (Tree->getOperator()->isSubClassOf("Instruction"))
2872 Instrs.push_back(Tree->getOperator());
2873 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2874 getInstructionsInTree(Tree->getChild(i), Instrs);
2875}
2876
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002877/// Check the class of a pattern leaf node against the instruction operand it
2878/// represents.
2879static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2880 Record *Leaf) {
2881 if (OI.Rec == Leaf)
2882 return true;
2883
2884 // Allow direct value types to be used in instruction set patterns.
2885 // The type will be checked later.
2886 if (Leaf->isSubClassOf("ValueType"))
2887 return true;
2888
2889 // Patterns can also be ComplexPattern instances.
2890 if (Leaf->isSubClassOf("ComplexPattern"))
2891 return true;
2892
2893 return false;
2894}
2895
Ahmed Bougacha14107512013-10-28 18:07:21 +00002896const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2897 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002898
Craig Topper0d1fb902015-03-10 03:25:04 +00002899 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002900
Craig Topper0d1fb902015-03-10 03:25:04 +00002901 // Parse the instruction.
2902 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2903 // Inline pattern fragments into it.
2904 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002905
Craig Topper0d1fb902015-03-10 03:25:04 +00002906 // Infer as many types as possible. If we cannot infer all of them, we can
2907 // never do anything with this instruction pattern: report it to the user.
2908 if (!I->InferAllTypes())
2909 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002910
Craig Topper0d1fb902015-03-10 03:25:04 +00002911 // InstInputs - Keep track of all of the inputs of the instruction, along
2912 // with the record they are declared as.
2913 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002914
Craig Topper0d1fb902015-03-10 03:25:04 +00002915 // InstResults - Keep track of all the virtual registers that are 'set'
2916 // in the instruction, including what reg class they are.
2917 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002918
Craig Topper0d1fb902015-03-10 03:25:04 +00002919 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002920
Craig Topper0d1fb902015-03-10 03:25:04 +00002921 // Verify that the top-level forms in the instruction are of void type, and
2922 // fill in the InstResults map.
2923 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2924 TreePatternNode *Pat = I->getTree(j);
2925 if (Pat->getNumTypes() != 0)
2926 I->error("Top-level forms in instruction pattern should have"
2927 " void types");
Chris Lattner8cab0212008-01-05 22:25:12 +00002928
Craig Topper0d1fb902015-03-10 03:25:04 +00002929 // Find inputs and outputs, and verify the structure of the uses/defs.
2930 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2931 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002932 }
2933
Craig Topper0d1fb902015-03-10 03:25:04 +00002934 // Now that we have inputs and outputs of the pattern, inspect the operands
2935 // list for the instruction. This determines the order that operands are
2936 // added to the machine instruction the node corresponds to.
2937 unsigned NumResults = InstResults.size();
2938
2939 // Parse the operands list from the (ops) list, validating it.
2940 assert(I->getArgList().empty() && "Args list should still be empty here!");
2941
2942 // Check that all of the results occur first in the list.
2943 std::vector<Record*> Results;
2944 TreePatternNode *Res0Node = nullptr;
2945 for (unsigned i = 0; i != NumResults; ++i) {
2946 if (i == CGI.Operands.size())
2947 I->error("'" + InstResults.begin()->first +
2948 "' set but does not appear in operand list!");
2949 const std::string &OpName = CGI.Operands[i].Name;
2950
2951 // Check that it exists in InstResults.
2952 TreePatternNode *RNode = InstResults[OpName];
2953 if (!RNode)
2954 I->error("Operand $" + OpName + " does not exist in operand list!");
2955
2956 if (i == 0)
2957 Res0Node = RNode;
2958 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2959 if (!R)
2960 I->error("Operand $" + OpName + " should be a set destination: all "
2961 "outputs must occur before inputs in operand list!");
2962
2963 if (!checkOperandClass(CGI.Operands[i], R))
2964 I->error("Operand $" + OpName + " class mismatch!");
2965
2966 // Remember the return type.
2967 Results.push_back(CGI.Operands[i].Rec);
2968
2969 // Okay, this one checks out.
2970 InstResults.erase(OpName);
2971 }
2972
2973 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2974 // the copy while we're checking the inputs.
2975 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2976
2977 std::vector<TreePatternNode*> ResultNodeOperands;
2978 std::vector<Record*> Operands;
2979 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2980 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2981 const std::string &OpName = Op.Name;
2982 if (OpName.empty())
2983 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2984
2985 if (!InstInputsCheck.count(OpName)) {
2986 // If this is an operand with a DefaultOps set filled in, we can ignore
2987 // this. When we codegen it, we will do so as always executed.
2988 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2989 // Does it have a non-empty DefaultOps field? If so, ignore this
2990 // operand.
2991 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2992 continue;
2993 }
2994 I->error("Operand $" + OpName +
2995 " does not appear in the instruction pattern");
2996 }
2997 TreePatternNode *InVal = InstInputsCheck[OpName];
2998 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2999
3000 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3001 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3002 if (!checkOperandClass(Op, InRec))
3003 I->error("Operand $" + OpName + "'s register class disagrees"
3004 " between the operand and pattern");
3005 }
3006 Operands.push_back(Op.Rec);
3007
3008 // Construct the result for the dest-pattern operand list.
3009 TreePatternNode *OpNode = InVal->clone();
3010
3011 // No predicate is useful on the result.
3012 OpNode->clearPredicateFns();
3013
3014 // Promote the xform function to be an explicit node if set.
3015 if (Record *Xform = OpNode->getTransformFn()) {
3016 OpNode->setTransformFn(nullptr);
3017 std::vector<TreePatternNode*> Children;
3018 Children.push_back(OpNode);
3019 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3020 }
3021
3022 ResultNodeOperands.push_back(OpNode);
3023 }
3024
3025 if (!InstInputsCheck.empty())
3026 I->error("Input operand $" + InstInputsCheck.begin()->first +
3027 " occurs in pattern but not in operands list!");
3028
3029 TreePatternNode *ResultPattern =
3030 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3031 GetNumNodeResults(I->getRecord(), *this));
3032 // Copy fully inferred output node type to instruction result pattern.
3033 for (unsigned i = 0; i != NumResults; ++i)
3034 ResultPattern->setType(i, Res0Node->getExtType(i));
3035
3036 // Create and insert the instruction.
3037 // FIXME: InstImpResults should not be part of DAGInstruction.
3038 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3039 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3040
3041 // Use a temporary tree pattern to infer all types and make sure that the
3042 // constructed result is correct. This depends on the instruction already
3043 // being inserted into the DAGInsts map.
3044 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3045 Temp.InferAllTypes(&I->getNamedNodesMap());
3046
3047 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3048 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3049
3050 return TheInsertedInst;
3051}
3052
Ahmed Bougacha14107512013-10-28 18:07:21 +00003053/// ParseInstructions - Parse all of the instructions, inlining and resolving
3054/// any fragments involved. This populates the Instructions list with fully
3055/// resolved instructions.
3056void CodeGenDAGPatterns::ParseInstructions() {
3057 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3058
3059 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Craig Topper24064772014-04-15 07:20:03 +00003060 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003061
3062 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
3063 LI = Instrs[i]->getValueAsListInit("Pattern");
3064
3065 // If there is no pattern, only collect minimal information about the
3066 // instruction for its operand list. We have to assume that there is one
3067 // result, as we have no detailed info. A pattern which references the
3068 // null_frag operator is as-if no pattern were specified. Normally this
3069 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3070 // null_frag.
3071 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
3072 std::vector<Record*> Results;
3073 std::vector<Record*> Operands;
3074
3075 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3076
3077 if (InstInfo.Operands.size() != 0) {
3078 if (InstInfo.Operands.NumDefs == 0) {
3079 // These produce no results
3080 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
3081 Operands.push_back(InstInfo.Operands[j].Rec);
3082 } else {
3083 // Assume the first operand is the result.
3084 Results.push_back(InstInfo.Operands[0].Rec);
3085
3086 // The rest are inputs.
3087 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
3088 Operands.push_back(InstInfo.Operands[j].Rec);
3089 }
3090 }
3091
3092 // Create and insert the instruction.
3093 std::vector<Record*> ImpResults;
3094 Instructions.insert(std::make_pair(Instrs[i],
Craig Topper24064772014-04-15 07:20:03 +00003095 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003096 continue; // no pattern.
3097 }
3098
3099 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
3100 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3101
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003102 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003103 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003104 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003105
Chris Lattner8cab0212008-01-05 22:25:12 +00003106 // If we can, convert the instructions to be patterns that are matched!
Sean Silvaa4e2c5f2012-09-19 01:47:00 +00003107 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
Benjamin Kramerc2dbd5d2009-08-23 10:39:21 +00003108 Instructions.begin(),
Chris Lattner8cab0212008-01-05 22:25:12 +00003109 E = Instructions.end(); II != E; ++II) {
3110 DAGInstruction &TheInst = II->second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003111 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003112 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003113
3114 // FIXME: Assume only the first tree is the pattern. The others are clobber
3115 // nodes.
3116 TreePatternNode *Pattern = I->getTree(0);
3117 TreePatternNode *SrcPattern;
3118 if (Pattern->getOperator()->getName() == "set") {
3119 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3120 } else{
3121 // Not a set (store or something?)
3122 SrcPattern = Pattern;
3123 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003124
Chris Lattner8cab0212008-01-05 22:25:12 +00003125 Record *Instr = II->first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003126 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003127 PatternToMatch(Instr,
3128 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003129 SrcPattern,
3130 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003131 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003132 Instr->getValueAsInt("AddedComplexity"),
3133 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003134 }
3135}
3136
Chris Lattnera7722b62010-02-23 06:55:24 +00003137
3138typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3139
Jim Grosbach65586fe2010-12-21 16:16:00 +00003140static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003141 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003142 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003143 if (!P->getName().empty()) {
3144 NameRecord &Rec = Names[P->getName()];
3145 // If this is the first instance of the name, remember the node.
3146 if (Rec.second++ == 0)
3147 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003148 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003149 PatternTop->error("repetition of value: $" + P->getName() +
3150 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003151 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003152
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003153 if (!P->isLeaf()) {
3154 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003155 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003156 }
3157}
3158
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003159void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003160 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003161 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003162 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003163 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3164 PrintWarning(Pattern->getRecord()->getLoc(),
3165 Twine("Pattern can never match: ") + Reason);
3166 return;
3167 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003168
Chris Lattner1e634e32010-03-01 22:29:19 +00003169 // If the source pattern's root is a complex pattern, that complex pattern
3170 // must specify the nodes it can potentially match.
3171 if (const ComplexPattern *CP =
3172 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3173 if (CP->getRootNodes().empty())
3174 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3175 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003176
3177
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003178 // Find all of the named values in the input and output, ensure they have the
3179 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003180 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003181 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3182 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003183
3184 // Scan all of the named values in the destination pattern, rejecting them if
3185 // they don't exist in the input pattern.
Chris Lattnera7722b62010-02-23 06:55:24 +00003186 for (std::map<std::string, NameRecord>::iterator
Chris Lattner4b9225b2010-02-23 07:50:58 +00003187 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Craig Topper24064772014-04-15 07:20:03 +00003188 if (SrcNames[I->first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003189 Pattern->error("Pattern has input without matching name in output: $" +
3190 I->first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003191 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003192
Chris Lattnera7722b62010-02-23 06:55:24 +00003193 // Scan all of the named values in the source pattern, rejecting them if the
3194 // name isn't used in the dest, and isn't used to tie two values together.
3195 for (std::map<std::string, NameRecord>::iterator
3196 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
Craig Topper24064772014-04-15 07:20:03 +00003197 if (DstNames[I->first].first == nullptr && SrcNames[I->first].second == 1)
Chris Lattnera7722b62010-02-23 06:55:24 +00003198 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003199
Chris Lattner0c0baa92010-02-23 06:16:51 +00003200 PatternsToMatch.push_back(PTM);
3201}
3202
3203
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003204
3205void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003206 const std::vector<const CodeGenInstruction*> &Instructions =
3207 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003208
3209 // First try to infer flags from the primary instruction pattern, if any.
3210 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003211 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003212 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3213 CodeGenInstruction &InstInfo =
3214 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003215
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003216 // Get the primary instruction pattern.
3217 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3218 if (!Pattern) {
3219 if (InstInfo.hasUndefFlags())
3220 Revisit.push_back(&InstInfo);
3221 continue;
3222 }
3223 InstAnalyzer PatInfo(*this);
3224 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003225 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003226 }
3227
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003228 // Second, look for single-instruction patterns defined outside the
3229 // instruction.
3230 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3231 const PatternToMatch &PTM = *I;
3232
3233 // We can only infer from single-instruction patterns, otherwise we won't
3234 // know which instruction should get the flags.
3235 SmallVector<Record*, 8> PatInstrs;
3236 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3237 if (PatInstrs.size() != 1)
3238 continue;
3239
3240 // Get the single instruction.
3241 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3242
3243 // Only infer properties from the first pattern. We'll verify the others.
3244 if (InstInfo.InferredFrom)
3245 continue;
3246
3247 InstAnalyzer PatInfo(*this);
3248 PatInfo.Analyze(&PTM);
3249 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3250 }
3251
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003252 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003253 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003254
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003255 // Revisit instructions with undefined flags and no pattern.
3256 if (Target.guessInstructionProperties()) {
3257 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3258 CodeGenInstruction &InstInfo = *Revisit[i];
3259 if (InstInfo.InferredFrom)
3260 continue;
3261 // The mayLoad and mayStore flags default to false.
3262 // Conservatively assume hasSideEffects if it wasn't explicit.
3263 if (InstInfo.hasSideEffects_Unset)
3264 InstInfo.hasSideEffects = true;
3265 }
3266 return;
3267 }
3268
3269 // Complain about any flags that are still undefined.
3270 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3271 CodeGenInstruction &InstInfo = *Revisit[i];
3272 if (InstInfo.InferredFrom)
3273 continue;
3274 if (InstInfo.hasSideEffects_Unset)
3275 PrintError(InstInfo.TheDef->getLoc(),
3276 "Can't infer hasSideEffects from patterns");
3277 if (InstInfo.mayStore_Unset)
3278 PrintError(InstInfo.TheDef->getLoc(),
3279 "Can't infer mayStore from patterns");
3280 if (InstInfo.mayLoad_Unset)
3281 PrintError(InstInfo.TheDef->getLoc(),
3282 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003283 }
3284}
3285
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003286
3287/// Verify instruction flags against pattern node properties.
3288void CodeGenDAGPatterns::VerifyInstructionFlags() {
3289 unsigned Errors = 0;
3290 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3291 const PatternToMatch &PTM = *I;
3292 SmallVector<Record*, 8> Instrs;
3293 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3294 if (Instrs.empty())
3295 continue;
3296
3297 // Count the number of instructions with each flag set.
3298 unsigned NumSideEffects = 0;
3299 unsigned NumStores = 0;
3300 unsigned NumLoads = 0;
3301 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3302 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3303 NumSideEffects += InstInfo.hasSideEffects;
3304 NumStores += InstInfo.mayStore;
3305 NumLoads += InstInfo.mayLoad;
3306 }
3307
3308 // Analyze the source pattern.
3309 InstAnalyzer PatInfo(*this);
3310 PatInfo.Analyze(&PTM);
3311
3312 // Collect error messages.
3313 SmallVector<std::string, 4> Msgs;
3314
3315 // Check for missing flags in the output.
3316 // Permit extra flags for now at least.
3317 if (PatInfo.hasSideEffects && !NumSideEffects)
3318 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3319
3320 // Don't verify store flags on instructions with side effects. At least for
3321 // intrinsics, side effects implies mayStore.
3322 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3323 Msgs.push_back("pattern may store, but mayStore isn't set");
3324
3325 // Similarly, mayStore implies mayLoad on intrinsics.
3326 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3327 Msgs.push_back("pattern may load, but mayLoad isn't set");
3328
3329 // Print error messages.
3330 if (Msgs.empty())
3331 continue;
3332 ++Errors;
3333
3334 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3335 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3336 (Instrs.size() == 1 ?
3337 "instruction" : "output instructions"));
3338 // Provide the location of the relevant instruction definitions.
3339 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3340 if (Instrs[i] != PTM.getSrcRecord())
3341 PrintError(Instrs[i]->getLoc(), "defined here");
3342 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3343 if (InstInfo.InferredFrom &&
3344 InstInfo.InferredFrom != InstInfo.TheDef &&
3345 InstInfo.InferredFrom != PTM.getSrcRecord())
3346 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
3347 }
3348 }
3349 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003350 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003351}
3352
Chris Lattnercabe0372010-03-15 06:00:16 +00003353/// Given a pattern result with an unresolved type, see if we can find one
3354/// instruction with an unresolved result type. Force this result type to an
3355/// arbitrary element if it's possible types to converge results.
3356static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3357 if (N->isLeaf())
3358 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003359
Chris Lattnercabe0372010-03-15 06:00:16 +00003360 // Analyze children.
3361 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3362 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3363 return true;
3364
3365 if (!N->getOperator()->isSubClassOf("Instruction"))
3366 return false;
3367
3368 // If this type is already concrete or completely unknown we can't do
3369 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003370 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3371 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3372 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003373
Chris Lattnerf1447252010-03-19 21:37:09 +00003374 // Otherwise, force its type to the first possibility (an arbitrary choice).
3375 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3376 return true;
3377 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003378
Chris Lattnerf1447252010-03-19 21:37:09 +00003379 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003380}
3381
Chris Lattnerab3242f2008-01-06 01:10:31 +00003382void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003383 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3384
3385 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003386 Record *CurPattern = Patterns[i];
David Greeneaf8ee2c2011-07-29 22:43:06 +00003387 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003388
3389 // If the pattern references the null_frag, there's nothing to do.
3390 if (hasNullFragReference(Tree))
3391 continue;
3392
Chris Lattner5c2182e2010-03-27 02:53:27 +00003393 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003394
3395 // Inline pattern fragments into it.
3396 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003397
David Greeneaf8ee2c2011-07-29 22:43:06 +00003398 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner8cab0212008-01-05 22:25:12 +00003399 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003400
Chris Lattner8cab0212008-01-05 22:25:12 +00003401 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003402 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003403
Chris Lattner8cab0212008-01-05 22:25:12 +00003404 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003405 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003406
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003407 if (Result.getNumTrees() != 1)
3408 Result.error("Cannot handle instructions producing instructions "
3409 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003410
Chris Lattner8cab0212008-01-05 22:25:12 +00003411 bool IterateInference;
3412 bool InferredAllPatternTypes, InferredAllResultTypes;
3413 do {
3414 // Infer as many types as possible. If we cannot infer all of them, we
3415 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003416 InferredAllPatternTypes =
3417 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003418
Chris Lattner8cab0212008-01-05 22:25:12 +00003419 // Infer as many types as possible. If we cannot infer all of them, we
3420 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003421 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003422 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003423
Chris Lattnerfdc20712010-03-18 23:15:10 +00003424 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003425
Chris Lattner8cab0212008-01-05 22:25:12 +00003426 // Apply the type of the result to the source pattern. This helps us
3427 // resolve cases where the input type is known to be a pointer type (which
3428 // is considered resolved), but the result knows it needs to be 32- or
3429 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003430 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003431 Pattern->getTree(0)->getNumTypes());
3432 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003433 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3434 i, Result.getTree(0)->getExtType(i), Result);
3435 IterateInference |= Result.getTree(0)->UpdateNodeType(
3436 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003437 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003438
Chris Lattnercabe0372010-03-15 06:00:16 +00003439 // If our iteration has converged and the input pattern's types are fully
3440 // resolved but the result pattern is not fully resolved, we may have a
3441 // situation where we have two instructions in the result pattern and
3442 // the instructions require a common register class, but don't care about
3443 // what actual MVT is used. This is actually a bug in our modelling:
3444 // output patterns should have register classes, not MVTs.
3445 //
3446 // In any case, to handle this, we just go through and disambiguate some
3447 // arbitrary types to the result pattern's nodes.
3448 if (!IterateInference && InferredAllPatternTypes &&
3449 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003450 IterateInference =
3451 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003452 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003453
Chris Lattner8cab0212008-01-05 22:25:12 +00003454 // Verify that we inferred enough types that we can do something with the
3455 // pattern and result. If these fire the user has to add type casts.
3456 if (!InferredAllPatternTypes)
3457 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003458 if (!InferredAllResultTypes) {
3459 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003460 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003461 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003462
Chris Lattner8cab0212008-01-05 22:25:12 +00003463 // Validate that the input pattern is correct.
3464 std::map<std::string, TreePatternNode*> InstInputs;
3465 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003466 std::vector<Record*> InstImpResults;
3467 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3468 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3469 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003470 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003471
3472 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003473 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003474 std::vector<TreePatternNode*> ResultNodeOperands;
3475 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3476 TreePatternNode *OpNode = DstPattern->getChild(ii);
3477 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003478 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003479 std::vector<TreePatternNode*> Children;
3480 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003481 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003482 }
3483 ResultNodeOperands.push_back(OpNode);
3484 }
David Blaikiecf195302014-11-17 22:55:41 +00003485 DstPattern = Result.getOnlyTree();
3486 if (!DstPattern->isLeaf())
3487 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3488 ResultNodeOperands,
3489 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003490
David Blaikiecf195302014-11-17 22:55:41 +00003491 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3492 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3493
3494 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003495 Temp.InferAllTypes();
3496
Jim Grosbach65586fe2010-12-21 16:16:00 +00003497
Chris Lattner0c0baa92010-02-23 06:16:51 +00003498 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003499 PatternToMatch(CurPattern,
3500 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003501 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003502 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003503 CurPattern->getValueAsInt("AddedComplexity"),
3504 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003505 }
3506}
3507
3508/// CombineChildVariants - Given a bunch of permutations of each child of the
3509/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003510static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003511 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3512 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003513 CodeGenDAGPatterns &CDP,
3514 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003515 // Make sure that each operand has at least one variant to choose from.
3516 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3517 if (ChildVariants[i].empty())
3518 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003519
Chris Lattner8cab0212008-01-05 22:25:12 +00003520 // The end result is an all-pairs construction of the resultant pattern.
3521 std::vector<unsigned> Idxs;
3522 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003523 bool NotDone;
3524 do {
3525#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003526 DEBUG(if (!Idxs.empty()) {
3527 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3528 for (unsigned i = 0; i < Idxs.size(); ++i) {
3529 errs() << Idxs[i] << " ";
3530 }
3531 errs() << "]\n";
3532 });
Scott Michel94420742008-03-05 17:49:05 +00003533#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003534 // Create the variant and add it to the output list.
3535 std::vector<TreePatternNode*> NewChildren;
3536 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3537 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerf1447252010-03-19 21:37:09 +00003538 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3539 Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003540
Chris Lattner8cab0212008-01-05 22:25:12 +00003541 // Copy over properties.
3542 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003543 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003544 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003545 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3546 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003547
Scott Michel94420742008-03-05 17:49:05 +00003548 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003549 std::string ErrString;
3550 if (!R->canPatternMatch(ErrString, CDP)) {
3551 delete R;
3552 } else {
3553 bool AlreadyExists = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003554
Chris Lattner8cab0212008-01-05 22:25:12 +00003555 // Scan to see if this pattern has already been emitted. We can get
3556 // duplication due to things like commuting:
3557 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3558 // which are the same pattern. Ignore the dups.
3559 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003560 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003561 AlreadyExists = true;
3562 break;
3563 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003564
Chris Lattner8cab0212008-01-05 22:25:12 +00003565 if (AlreadyExists)
3566 delete R;
3567 else
3568 OutVariants.push_back(R);
3569 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003570
Scott Michel94420742008-03-05 17:49:05 +00003571 // Increment indices to the next permutation by incrementing the
3572 // indicies from last index backward, e.g., generate the sequence
3573 // [0, 0], [0, 1], [1, 0], [1, 1].
3574 int IdxsIdx;
3575 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3576 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3577 Idxs[IdxsIdx] = 0;
3578 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003579 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003580 }
Scott Michel94420742008-03-05 17:49:05 +00003581 NotDone = (IdxsIdx >= 0);
3582 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003583}
3584
3585/// CombineChildVariants - A helper function for binary operators.
3586///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003587static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003588 const std::vector<TreePatternNode*> &LHS,
3589 const std::vector<TreePatternNode*> &RHS,
3590 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003591 CodeGenDAGPatterns &CDP,
3592 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003593 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3594 ChildVariants.push_back(LHS);
3595 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003596 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003597}
Chris Lattner8cab0212008-01-05 22:25:12 +00003598
3599
3600static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3601 std::vector<TreePatternNode *> &Children) {
3602 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3603 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003604
Chris Lattner8cab0212008-01-05 22:25:12 +00003605 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003606 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003607 N->getTransformFn()) {
3608 Children.push_back(N);
3609 return;
3610 }
3611
3612 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3613 Children.push_back(N->getChild(0));
3614 else
3615 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3616
3617 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3618 Children.push_back(N->getChild(1));
3619 else
3620 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3621}
3622
3623/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3624/// the (potentially recursive) pattern by using algebraic laws.
3625///
3626static void GenerateVariantsOf(TreePatternNode *N,
3627 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003628 CodeGenDAGPatterns &CDP,
3629 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003630 // We cannot permute leaves or ComplexPattern uses.
3631 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003632 OutVariants.push_back(N);
3633 return;
3634 }
3635
3636 // Look up interesting info about the node.
3637 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3638
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003639 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003640 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003641 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003642 std::vector<TreePatternNode*> MaximalChildren;
3643 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3644
3645 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3646 // permutations.
3647 if (MaximalChildren.size() == 3) {
3648 // Find the variants of all of our maximal children.
3649 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003650 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3651 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3652 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003653
Chris Lattner8cab0212008-01-05 22:25:12 +00003654 // There are only two ways we can permute the tree:
3655 // (A op B) op C and A op (B op C)
3656 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003657
Chris Lattner8cab0212008-01-05 22:25:12 +00003658 // Generate legal pair permutations of A/B/C.
3659 std::vector<TreePatternNode*> ABVariants;
3660 std::vector<TreePatternNode*> BAVariants;
3661 std::vector<TreePatternNode*> ACVariants;
3662 std::vector<TreePatternNode*> CAVariants;
3663 std::vector<TreePatternNode*> BCVariants;
3664 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003665 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3666 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3667 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3668 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3669 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3670 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003671
3672 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003673 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3674 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3675 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3676 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3677 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3678 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003679
3680 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003681 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3682 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3683 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3684 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3685 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3686 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003687 return;
3688 }
3689 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003690
Chris Lattner8cab0212008-01-05 22:25:12 +00003691 // Compute permutations of all children.
3692 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3693 ChildVariants.resize(N->getNumChildren());
3694 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003695 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003696
3697 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003698 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003699
3700 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003701 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3702 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3703 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3704 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003705 // Don't count children which are actually register references.
3706 unsigned NC = 0;
3707 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3708 TreePatternNode *Child = N->getChild(i);
3709 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003710 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003711 Record *RR = DI->getDef();
3712 if (RR->isSubClassOf("Register"))
3713 continue;
3714 }
3715 NC++;
3716 }
3717 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003718 if (isCommIntrinsic) {
3719 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3720 // operands are the commutative operands, and there might be more operands
3721 // after those.
3722 assert(NC >= 3 &&
3723 "Commutative intrinsic should have at least 3 childrean!");
3724 std::vector<std::vector<TreePatternNode*> > Variants;
3725 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3726 Variants.push_back(ChildVariants[2]);
3727 Variants.push_back(ChildVariants[1]);
3728 for (unsigned i = 3; i != NC; ++i)
3729 Variants.push_back(ChildVariants[i]);
3730 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3731 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003732 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003733 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003734 }
3735}
3736
3737
3738// GenerateVariants - Generate variants. For example, commutative patterns can
3739// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003740void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003741 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003742
Chris Lattner8cab0212008-01-05 22:25:12 +00003743 // Loop over all of the patterns we've collected, checking to see if we can
3744 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003745 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003746 // the .td file having to contain tons of variants of instructions.
3747 //
3748 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3749 // intentionally do not reconsider these. Any variants of added patterns have
3750 // already been added.
3751 //
3752 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003753 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003754 std::vector<TreePatternNode*> Variants;
Scott Michel94420742008-03-05 17:49:05 +00003755 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003756 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003757 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003758 DEBUG(errs() << "\n");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003759 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3760 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003761
3762 assert(!Variants.empty() && "Must create at least original variant!");
3763 Variants.erase(Variants.begin()); // Remove the original pattern.
3764
3765 if (Variants.empty()) // No variants for this pattern.
3766 continue;
3767
Chris Lattner34822f62009-08-23 04:44:11 +00003768 DEBUG(errs() << "FOUND VARIANTS OF: ";
3769 PatternsToMatch[i].getSrcPattern()->dump();
3770 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003771
3772 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3773 TreePatternNode *Variant = Variants[v];
3774
Chris Lattner34822f62009-08-23 04:44:11 +00003775 DEBUG(errs() << " VAR#" << v << ": ";
3776 Variant->dump();
3777 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003778
Chris Lattner8cab0212008-01-05 22:25:12 +00003779 // Scan to see if an instruction or explicit pattern already matches this.
3780 bool AlreadyExists = false;
3781 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003782 // Skip if the top level predicates do not match.
3783 if (PatternsToMatch[i].getPredicates() !=
3784 PatternsToMatch[p].getPredicates())
3785 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003786 // Check to see if this variant already exists.
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003787 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3788 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003789 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003790 AlreadyExists = true;
3791 break;
3792 }
3793 }
3794 // If we already have it, ignore the variant.
3795 if (AlreadyExists) continue;
3796
3797 // Otherwise, add it to the list of patterns we have.
3798 PatternsToMatch.
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003799 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3800 PatternsToMatch[i].getPredicates(),
Chris Lattner8cab0212008-01-05 22:25:12 +00003801 Variant, PatternsToMatch[i].getDstPattern(),
3802 PatternsToMatch[i].getDstRegs(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003803 PatternsToMatch[i].getAddedComplexity(),
3804 Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003805 }
3806
Chris Lattner34822f62009-08-23 04:44:11 +00003807 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003808 }
3809}