blob: 415511123d2803f6f0a5d05fbe32214f262c49c9 [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
Craig Topper306cb122015-11-22 20:46:24 +000087 for (MVT::SimpleValueType VT : LegalTypes)
88 if (!Pred || Pred(VT))
89 TypeVec.push_back(VT);
Chris Lattner6d765eb2010-03-19 17:41:26 +000090
91 // If we have nothing that matches the predicate, bail out.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000092 if (TypeVec.empty()) {
Chris Lattner6d765eb2010-03-19 17:41:26 +000093 TP.error("Type inference contradiction found, no " +
Jim Grosbach65586fe2010-12-21 16:16:00 +000094 std::string(PredicateName) + " types found");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000095 return false;
96 }
Chris Lattner6d765eb2010-03-19 17:41:26 +000097 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
99
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000103
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000104 return true;
105}
Chris Lattnercabe0372010-03-15 06:00:16 +0000106
107/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108/// integer value type.
109bool EEVT::TypeSet::hasIntegerTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000110 return std::any_of(TypeVec.begin(), TypeVec.end(), isInteger);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000111}
Chris Lattnercabe0372010-03-15 06:00:16 +0000112
113/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
114/// a floating point value type.
115bool EEVT::TypeSet::hasFloatingPointTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000116 return std::any_of(TypeVec.begin(), TypeVec.end(), isFloatingPoint);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000117}
Chris Lattnercabe0372010-03-15 06:00:16 +0000118
Craig Topper74169dc2014-01-28 04:49:01 +0000119/// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
120bool EEVT::TypeSet::hasScalarTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000121 return std::any_of(TypeVec.begin(), TypeVec.end(), isScalar);
Craig Topper74169dc2014-01-28 04:49:01 +0000122}
123
Chris Lattnercabe0372010-03-15 06:00:16 +0000124/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
125/// value type.
126bool EEVT::TypeSet::hasVectorTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000127 return std::any_of(TypeVec.begin(), TypeVec.end(), isVector);
Chris Lattner8cab0212008-01-05 22:25:12 +0000128}
Bob Wilson2cd5da82009-08-11 01:14:02 +0000129
Chris Lattnercabe0372010-03-15 06:00:16 +0000130
131std::string EEVT::TypeSet::getName() const {
Chris Lattnerda5b4ad2010-03-19 01:14:27 +0000132 if (TypeVec.empty()) return "<empty>";
Jim Grosbach65586fe2010-12-21 16:16:00 +0000133
Chris Lattnercabe0372010-03-15 06:00:16 +0000134 std::string Result;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000135
Chris Lattnercabe0372010-03-15 06:00:16 +0000136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
137 std::string VTName = llvm::getEnumName(TypeVec[i]);
138 // Strip off MVT:: prefix if present.
139 if (VTName.substr(0,5) == "MVT::")
140 VTName = VTName.substr(5);
141 if (i) Result += ':';
142 Result += VTName;
143 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000144
Chris Lattnercabe0372010-03-15 06:00:16 +0000145 if (TypeVec.size() == 1)
146 return Result;
147 return "{" + Result + "}";
Bob Wilson2cd5da82009-08-11 01:14:02 +0000148}
Chris Lattnercabe0372010-03-15 06:00:16 +0000149
150/// MergeInTypeInfo - This merges in type information from the specified
151/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000152/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattnercabe0372010-03-15 06:00:16 +0000153bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000154 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattnercabe0372010-03-15 06:00:16 +0000155 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000156
Chris Lattnercabe0372010-03-15 06:00:16 +0000157 if (isCompletelyUnknown()) {
158 *this = InVT;
159 return true;
160 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000161
Craig Topperd2177de2015-11-23 07:19:08 +0000162 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000163
Chris Lattnercabe0372010-03-15 06:00:16 +0000164 // Handle the abstract cases, seeing if we can resolve them better.
165 switch (TypeVec[0]) {
166 default: break;
167 case MVT::iPTR:
168 case MVT::iPTRAny:
169 if (InVT.hasIntegerTypes()) {
170 EEVT::TypeSet InCopy(InVT);
171 InCopy.EnforceInteger(TP);
172 InCopy.EnforceScalar(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000173
Chris Lattnercabe0372010-03-15 06:00:16 +0000174 if (InCopy.isConcrete()) {
175 // If the RHS has one integer type, upgrade iPTR to i32.
176 TypeVec[0] = InVT.TypeVec[0];
177 return true;
178 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000179
Chris Lattnercabe0372010-03-15 06:00:16 +0000180 // If the input has multiple scalar integers, this doesn't add any info.
181 if (!InCopy.isCompletelyUnknown())
182 return false;
183 }
184 break;
185 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000186
Chris Lattnercabe0372010-03-15 06:00:16 +0000187 // If the input constraint is iAny/iPTR and this is an integer type list,
188 // remove non-integer types from the list.
189 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
190 hasIntegerTypes()) {
191 bool MadeChange = EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000192
Chris Lattnercabe0372010-03-15 06:00:16 +0000193 // If we're merging in iPTR/iPTRAny and the node currently has a list of
194 // multiple different integer types, replace them with a single iPTR.
195 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
196 TypeVec.size() != 1) {
Craig Topper4856c812015-11-24 08:20:41 +0000197 TypeVec.assign(1, InVT.TypeVec[0]);
Chris Lattnercabe0372010-03-15 06:00:16 +0000198 MadeChange = true;
199 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000200
Chris Lattnercabe0372010-03-15 06:00:16 +0000201 return MadeChange;
202 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000203
Chris Lattnercabe0372010-03-15 06:00:16 +0000204 // If this is a type list and the RHS is a typelist as well, eliminate entries
205 // from this list that aren't in the other one.
206 bool MadeChange = false;
207 TypeSet InputSet(*this);
208
209 for (unsigned i = 0; i != TypeVec.size(); ++i) {
Craig Toppercbdc27e2015-11-22 19:27:02 +0000210 if (std::find(InVT.TypeVec.begin(), InVT.TypeVec.end(), TypeVec[i]) !=
211 InVT.TypeVec.end())
212 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000213
Chris Lattnercabe0372010-03-15 06:00:16 +0000214 TypeVec.erase(TypeVec.begin()+i--);
215 MadeChange = true;
216 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000217
Chris Lattnercabe0372010-03-15 06:00:16 +0000218 // If we removed all of our types, we have a type contradiction.
219 if (!TypeVec.empty())
220 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000221
Chris Lattnercabe0372010-03-15 06:00:16 +0000222 // FIXME: Really want an SMLoc here!
223 TP.error("Type inference contradiction found, merging '" +
224 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000225 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000226}
227
228/// EnforceInteger - Remove all non-integer types from this set.
229bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000230 if (TP.hasError())
231 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000232 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000233 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000234 return FillWithPossibleTypes(TP, isInteger, "integer");
Craig Topperd2177de2015-11-23 07:19:08 +0000235
Chris Lattnercabe0372010-03-15 06:00:16 +0000236 if (!hasFloatingPointTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000237 return false;
238
239 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000240
Chris Lattnercabe0372010-03-15 06:00:16 +0000241 // Filter out all the fp types.
Craig Topperde2d7592015-11-23 07:19:10 +0000242 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
243 std::not1(std::ptr_fun(isInteger))),
244 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000245
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000246 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000247 TP.error("Type inference contradiction found, '" +
248 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000249 return false;
250 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000251 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000252}
253
254/// EnforceFloatingPoint - Remove all integer types from this set.
255bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000256 if (TP.hasError())
257 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000258 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000259 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000260 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
261
Chris Lattnercabe0372010-03-15 06:00:16 +0000262 if (!hasIntegerTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000263 return false;
264
265 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000266
Craig Topperde2d7592015-11-23 07:19:10 +0000267 // Filter out all the integer types.
268 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
269 std::not1(std::ptr_fun(isFloatingPoint))),
270 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000271
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000272 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000273 TP.error("Type inference contradiction found, '" +
274 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000275 return false;
276 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000277 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000278}
279
280/// EnforceScalar - Remove all vector types from this.
281bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000282 if (TP.hasError())
283 return false;
284
Chris Lattnercabe0372010-03-15 06:00:16 +0000285 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000286 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000287 return FillWithPossibleTypes(TP, isScalar, "scalar");
288
Chris Lattnercabe0372010-03-15 06:00:16 +0000289 if (!hasVectorTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000290 return false;
291
292 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000293
Chris Lattnercabe0372010-03-15 06:00:16 +0000294 // Filter out all the vector types.
Craig Topperde2d7592015-11-23 07:19:10 +0000295 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
296 std::not1(std::ptr_fun(isScalar))),
297 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000298
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000299 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000300 TP.error("Type inference contradiction found, '" +
301 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000302 return false;
303 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000304 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000305}
306
307/// EnforceVector - Remove all vector types from this.
308bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000309 if (TP.hasError())
310 return false;
311
Chris Lattner6d765eb2010-03-19 17:41:26 +0000312 // If we know nothing, then get the full set.
313 if (TypeVec.empty())
314 return FillWithPossibleTypes(TP, isVector, "vector");
315
Chris Lattnercabe0372010-03-15 06:00:16 +0000316 TypeSet InputSet(*this);
317 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000318
Chris Lattnercabe0372010-03-15 06:00:16 +0000319 // Filter out all the scalar types.
Craig Topperde2d7592015-11-23 07:19:10 +0000320 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
321 std::not1(std::ptr_fun(isVector))),
322 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000323
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000324 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000325 TP.error("Type inference contradiction found, '" +
326 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000327 return false;
328 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000329 return MadeChange;
330}
331
332
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000333
Craig Topper74169dc2014-01-28 04:49:01 +0000334/// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000335/// this should be based on the element type. Update this and other based on
Craig Topper74169dc2014-01-28 04:49:01 +0000336/// this information.
Chris Lattnercabe0372010-03-15 06:00:16 +0000337bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000338 if (TP.hasError())
339 return false;
340
Chris Lattnercabe0372010-03-15 06:00:16 +0000341 // Both operands must be integer or FP, but we don't care which.
342 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000343
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000344 if (isCompletelyUnknown())
345 MadeChange = FillWithPossibleTypes(TP);
346
347 if (Other.isCompletelyUnknown())
348 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000349
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000350 // If one side is known to be integer or known to be FP but the other side has
351 // no information, get at least the type integrality info in there.
352 if (!hasFloatingPointTypes())
353 MadeChange |= Other.EnforceInteger(TP);
354 else if (!hasIntegerTypes())
355 MadeChange |= Other.EnforceFloatingPoint(TP);
356 if (!Other.hasFloatingPointTypes())
357 MadeChange |= EnforceInteger(TP);
358 else if (!Other.hasIntegerTypes())
359 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000360
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000361 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
362 "Should have a type list now");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000363
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000364 // If one contains vectors but the other doesn't pull vectors out.
365 if (!hasVectorTypes())
366 MadeChange |= Other.EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000367 else if (!hasScalarTypes())
368 MadeChange |= Other.EnforceVector(TP);
Craig Topper6dbcb942014-01-25 05:17:38 +0000369 if (!Other.hasVectorTypes())
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000370 MadeChange |= EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000371 else if (!Other.hasScalarTypes())
372 MadeChange |= EnforceVector(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000373
Craig Topper74169dc2014-01-28 04:49:01 +0000374 // This code does not currently handle nodes which have multiple types,
375 // where some types are integer, and some are fp. Assert that this is not
376 // the case.
377 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
378 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
379 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
380
381 if (TP.hasError())
382 return false;
383
Craig Topper7bbd37b2015-03-10 03:25:07 +0000384 // Okay, find the smallest type from current set and remove anything the
385 // same or smaller from the other set. We need to ensure that the scalar
386 // type size is smaller than the scalar size of the smallest type. For
387 // vectors, we also need to make sure that the total size is no larger than
388 // the size of the smallest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000389 TypeSet InputSet(Other);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000390 MVT Smallest = TypeVec[0];
Craig Topper74169dc2014-01-28 04:49:01 +0000391 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000392 MVT OtherVT = Other.TypeVec[i];
393 // Don't compare vector and non-vector types.
394 if (OtherVT.isVector() != Smallest.isVector())
395 continue;
396 // The getSizeInBits() check here is only needed for vectors, but is
397 // a subset of the scalar check for scalars so no need to qualify.
398 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
399 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000400 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
401 MadeChange = true;
402 }
403 }
404
405 if (Other.TypeVec.empty()) {
406 TP.error("Type inference contradiction found, '" + InputSet.getName() +
407 "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000408 return false;
409 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000410
Craig Topper7bbd37b2015-03-10 03:25:07 +0000411 // Okay, find the largest type from the other set and remove anything the
412 // same or smaller from the current set. We need to ensure that the scalar
413 // type size is larger than the scalar size of the largest type. For
414 // vectors, we also need to make sure that the total size is no smaller than
415 // the size of the largest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000416 InputSet = TypeSet(*this);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000417 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
Craig Topper74169dc2014-01-28 04:49:01 +0000418 for (unsigned i = 0; i != TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000419 MVT OtherVT = TypeVec[i];
420 // Don't compare vector and non-vector types.
421 if (OtherVT.isVector() != Largest.isVector())
422 continue;
423 // The getSizeInBits() check here is only needed for vectors, but is
424 // a subset of the scalar check for scalars so no need to qualify.
425 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
426 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000427 TypeVec.erase(TypeVec.begin()+i--);
428 MadeChange = true;
David Greene433c6182011-02-01 19:12:32 +0000429 }
David Greene433c6182011-02-01 19:12:32 +0000430 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000431
Craig Topper74169dc2014-01-28 04:49:01 +0000432 if (TypeVec.empty()) {
433 TP.error("Type inference contradiction found, '" + InputSet.getName() +
434 "' has nothing smaller than '" + Other.getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000435 return false;
436 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000437
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000438 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000439}
440
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000441/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000442/// whose element is specified by VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000443bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
444 TreePattern &TP) {
445 bool MadeChange = false;
446
447 MadeChange |= EnforceVector(TP);
448
449 TypeSet InputSet(*this);
450
451 // Filter out all the types which don't have the right element type.
452 for (unsigned i = 0; i != TypeVec.size(); ++i) {
453 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
454 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
455 TypeVec.erase(TypeVec.begin()+i--);
456 MadeChange = true;
457 }
458 }
459
460 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
461 TP.error("Type inference contradiction found, forcing '" +
462 InputSet.getName() + "' to have a vector element");
463 return false;
464 }
465
466 return MadeChange;
467}
468
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000469/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Craig Topper0be34582015-03-05 07:11:34 +0000470/// whose element is specified by VTOperand.
Chris Lattner57ebf632010-03-24 00:01:16 +0000471bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000472 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000473 if (TP.hasError())
474 return false;
475
Chris Lattner57ebf632010-03-24 00:01:16 +0000476 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000477 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000478 MadeChange |= EnforceVector(TP);
479 MadeChange |= VTOperand.EnforceScalar(TP);
480
481 // If we know the vector type, it forces the scalar to agree.
482 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000483 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000484 IVT = IVT.getVectorElementType();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000485 return MadeChange |
Craig Topper95198f42013-09-25 06:37:18 +0000486 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000487 }
488
489 // If the scalar type is known, filter out vector types whose element types
490 // disagree.
491 if (!VTOperand.isConcrete())
492 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000493
Chris Lattner57ebf632010-03-24 00:01:16 +0000494 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000495
Chris Lattner57ebf632010-03-24 00:01:16 +0000496 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000497
Chris Lattner57ebf632010-03-24 00:01:16 +0000498 // Filter out all the types which don't have the right element type.
499 for (unsigned i = 0; i != TypeVec.size(); ++i) {
500 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
Craig Topper95198f42013-09-25 06:37:18 +0000501 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000502 TypeVec.erase(TypeVec.begin()+i--);
503 MadeChange = true;
504 }
Chris Lattner57ebf632010-03-24 00:01:16 +0000505 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000506
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000507 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattnercabe0372010-03-15 06:00:16 +0000508 TP.error("Type inference contradiction found, forcing '" +
509 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000510 return false;
511 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000512 return MadeChange;
513}
514
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000515/// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
David Greene127fd1d2011-01-24 20:53:18 +0000516/// vector type specified by VTOperand.
517bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
518 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000519 if (TP.hasError())
520 return false;
521
David Greene127fd1d2011-01-24 20:53:18 +0000522 // "This" must be a vector and "VTOperand" must be a vector.
523 bool MadeChange = false;
524 MadeChange |= EnforceVector(TP);
525 MadeChange |= VTOperand.EnforceVector(TP);
526
Craig Topper6e1faaf2014-01-25 17:40:33 +0000527 // If one side is known to be integer or known to be FP but the other side has
528 // no information, get at least the type integrality info in there.
529 if (!hasFloatingPointTypes())
530 MadeChange |= VTOperand.EnforceInteger(TP);
531 else if (!hasIntegerTypes())
532 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
533 if (!VTOperand.hasFloatingPointTypes())
534 MadeChange |= EnforceInteger(TP);
535 else if (!VTOperand.hasIntegerTypes())
536 MadeChange |= EnforceFloatingPoint(TP);
537
538 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
539 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000540
541 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000542 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000543 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000544 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000545 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000546 IVT = IVT.getVectorElementType();
547
Craig Topper95198f42013-09-25 06:37:18 +0000548 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000549 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000550
551 // Only keep types that have less elements than VTOperand.
552 TypeSet InputSet(VTOperand);
553
554 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
555 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
556 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
557 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
558 MadeChange = true;
559 }
560 }
561 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
562 TP.error("Type inference contradiction found, forcing '" +
563 InputSet.getName() + "' to have less vector elements than '" +
564 getName() + "'");
565 return false;
566 }
David Greene127fd1d2011-01-24 20:53:18 +0000567 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000568 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000569 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000570 IVT = IVT.getVectorElementType();
571
Craig Topper95198f42013-09-25 06:37:18 +0000572 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000573 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000574
575 // Only keep types that have more elements than 'this'.
576 TypeSet InputSet(*this);
577
578 for (unsigned i = 0; i != TypeVec.size(); ++i) {
579 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
580 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
581 TypeVec.erase(TypeVec.begin()+i--);
582 MadeChange = true;
583 }
584 }
585 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
586 TP.error("Type inference contradiction found, forcing '" +
587 InputSet.getName() + "' to have more vector elements than '" +
588 VTOperand.getName() + "'");
589 return false;
590 }
David Greene127fd1d2011-01-24 20:53:18 +0000591 }
592
593 return MadeChange;
594}
595
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000596/// EnforceVectorSameNumElts - 'this' is now constrained to
Craig Topper0be34582015-03-05 07:11:34 +0000597/// be a vector with same num elements as VTOperand.
598bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
599 TreePattern &TP) {
600 if (TP.hasError())
601 return false;
602
603 // "This" must be a vector and "VTOperand" must be a vector.
604 bool MadeChange = false;
605 MadeChange |= EnforceVector(TP);
606 MadeChange |= VTOperand.EnforceVector(TP);
607
608 // If we know one of the vector types, it forces the other type to agree.
609 if (isConcrete()) {
610 MVT IVT = getConcrete();
611 unsigned NumElems = IVT.getVectorNumElements();
612
613 // Only keep types that have same elements as VTOperand.
614 TypeSet InputSet(VTOperand);
615
616 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
617 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
618 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
619 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
620 MadeChange = true;
621 }
622 }
623 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
624 TP.error("Type inference contradiction found, forcing '" +
625 InputSet.getName() + "' to have same number elements as '" +
626 getName() + "'");
627 return false;
628 }
629 } else if (VTOperand.isConcrete()) {
630 MVT IVT = VTOperand.getConcrete();
631 unsigned NumElems = IVT.getVectorNumElements();
632
633 // Only keep types that have same elements as 'this'.
634 TypeSet InputSet(*this);
635
636 for (unsigned i = 0; i != TypeVec.size(); ++i) {
637 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
638 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
639 TypeVec.erase(TypeVec.begin()+i--);
640 MadeChange = true;
641 }
642 }
643 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
644 TP.error("Type inference contradiction found, forcing '" +
645 InputSet.getName() + "' to have same number elements than '" +
646 VTOperand.getName() + "'");
647 return false;
648 }
649 }
650
651 return MadeChange;
652}
653
Chris Lattnercabe0372010-03-15 06:00:16 +0000654//===----------------------------------------------------------------------===//
655// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000656
Scott Michel94420742008-03-05 17:49:05 +0000657/// Dependent variable map for CodeGenDAGPattern variant generation
658typedef std::map<std::string, int> DepVarMap;
659
Chris Lattner514e2922011-04-17 21:38:24 +0000660static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000661 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000662 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000663 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000664 } else {
665 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
666 FindDepVarsOf(N->getChild(i), DepMap);
667 }
668}
Chris Lattner514e2922011-04-17 21:38:24 +0000669
670/// Find dependent variables within child patterns
671static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000672 DepVarMap depcounts;
673 FindDepVarsOf(N, depcounts);
Craig Topper306cb122015-11-22 20:46:24 +0000674 for (const std::pair<std::string, int> &Pair : depcounts) {
675 if (Pair.second > 1)
676 DepVars.insert(Pair.first);
Scott Michel94420742008-03-05 17:49:05 +0000677 }
678}
679
Daniel Dunbarba66a812010-10-08 02:07:22 +0000680#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000681/// Dump the dependent variable set:
682static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000683 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000684 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000685 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000686 DEBUG(errs() << "[ ");
Craig Topper306cb122015-11-22 20:46:24 +0000687 for (const std::string &DepVar : DepVars) {
688 DEBUG(errs() << DepVar << " ");
Scott Michel94420742008-03-05 17:49:05 +0000689 }
Chris Lattner34822f62009-08-23 04:44:11 +0000690 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000691 }
692}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000693#endif
694
Chris Lattner514e2922011-04-17 21:38:24 +0000695
696//===----------------------------------------------------------------------===//
697// TreePredicateFn Implementation
698//===----------------------------------------------------------------------===//
699
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000700/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
701TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
702 assert((getPredCode().empty() || getImmCode().empty()) &&
703 ".td file corrupt: can't have a node predicate *and* an imm predicate");
704}
705
Chris Lattner514e2922011-04-17 21:38:24 +0000706std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000707 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000708}
709
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000710std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000711 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000712}
713
Chris Lattner514e2922011-04-17 21:38:24 +0000714
715/// isAlwaysTrue - Return true if this is a noop predicate.
716bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000717 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000718}
719
720/// Return the name to use in the generated code to reference this, this is
721/// "Predicate_foo" if from a pattern fragment "foo".
722std::string TreePredicateFn::getFnName() const {
723 return "Predicate_" + PatFragRec->getRecord()->getName();
724}
725
726/// getCodeToRunOnSDNode - Return the code for the function body that
727/// evaluates this predicate. The argument is expected to be in "Node",
728/// not N. This handles casting and conversion to a concrete node type as
729/// appropriate.
730std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000731 // Handle immediate predicates first.
732 std::string ImmCode = getImmCode();
733 if (!ImmCode.empty()) {
734 std::string Result =
735 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000736 return Result + ImmCode;
737 }
738
739 // Handle arbitrary node predicates.
740 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000741 std::string ClassName;
742 if (PatFragRec->getOnlyTree()->isLeaf())
743 ClassName = "SDNode";
744 else {
745 Record *Op = PatFragRec->getOnlyTree()->getOperator();
746 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
747 }
748 std::string Result;
749 if (ClassName == "SDNode")
750 Result = " SDNode *N = Node;\n";
751 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000752 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000753
754 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000755}
756
Chris Lattner8cab0212008-01-05 22:25:12 +0000757//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000758// PatternToMatch implementation
759//
760
Chris Lattner05925fe2010-03-29 01:40:38 +0000761
762/// getPatternSize - Return the 'size' of this pattern. We want to match large
763/// patterns before small ones. This is used to determine the size of a
764/// pattern.
765static unsigned getPatternSize(const TreePatternNode *P,
766 const CodeGenDAGPatterns &CGP) {
767 unsigned Size = 3; // The node itself.
768 // If the root node is a ConstantSDNode, increases its size.
769 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000770 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000771 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000772
Chris Lattner05925fe2010-03-29 01:40:38 +0000773 // FIXME: This is a hack to statically increase the priority of patterns
774 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
775 // Later we can allow complexity / cost for each pattern to be (optionally)
776 // specified. To get best possible pattern match we'll need to dynamically
777 // calculate the complexity of all patterns a dag can potentially map to.
778 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000779 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000780 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000781
Tim Northoverc807a172014-05-20 11:52:46 +0000782 // We don't want to count any children twice, so return early.
783 return Size;
784 }
785
Chris Lattner05925fe2010-03-29 01:40:38 +0000786 // If this node has some predicate function that must match, it adds to the
787 // complexity of this node.
788 if (!P->getPredicateFns().empty())
789 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000790
Chris Lattner05925fe2010-03-29 01:40:38 +0000791 // Count children in the count if they are also nodes.
792 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
793 TreePatternNode *Child = P->getChild(i);
794 if (!Child->isLeaf() && Child->getNumTypes() &&
795 Child->getType(0) != MVT::Other)
796 Size += getPatternSize(Child, CGP);
797 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000798 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000799 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
800 else if (Child->getComplexPatternInfo(CGP))
801 Size += getPatternSize(Child, CGP);
802 else if (!Child->getPredicateFns().empty())
803 ++Size;
804 }
805 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000806
Chris Lattner05925fe2010-03-29 01:40:38 +0000807 return Size;
808}
809
810/// Compute the complexity metric for the input pattern. This roughly
811/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000812int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000813getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
814 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
815}
816
817
Dan Gohman49e19e92008-08-22 00:20:26 +0000818/// getPredicateCheck - Return a single string containing all of this
819/// pattern's predicates concatenated with "&&" operators.
820///
821std::string PatternToMatch::getPredicateCheck() const {
822 std::string PredicateCheck;
Craig Topperef0578a2015-06-02 04:15:51 +0000823 for (Init *I : Predicates->getValues()) {
824 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000825 Record *Def = Pred->getDef();
826 if (!Def->isSubClassOf("Predicate")) {
827#ifndef NDEBUG
828 Def->dump();
829#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000830 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000831 }
832 if (!PredicateCheck.empty())
833 PredicateCheck += " && ";
834 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
835 }
836 }
837
838 return PredicateCheck;
839}
840
841//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000842// SDTypeConstraint implementation
843//
844
845SDTypeConstraint::SDTypeConstraint(Record *R) {
846 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000847
Chris Lattner8cab0212008-01-05 22:25:12 +0000848 if (R->isSubClassOf("SDTCisVT")) {
849 ConstraintType = SDTCisVT;
850 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000851 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000852 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000853
Chris Lattner8cab0212008-01-05 22:25:12 +0000854 } else if (R->isSubClassOf("SDTCisPtrTy")) {
855 ConstraintType = SDTCisPtrTy;
856 } else if (R->isSubClassOf("SDTCisInt")) {
857 ConstraintType = SDTCisInt;
858 } else if (R->isSubClassOf("SDTCisFP")) {
859 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000860 } else if (R->isSubClassOf("SDTCisVec")) {
861 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000862 } else if (R->isSubClassOf("SDTCisSameAs")) {
863 ConstraintType = SDTCisSameAs;
864 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
865 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
866 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000867 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000868 R->getValueAsInt("OtherOperandNum");
869 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
870 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000871 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000872 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000873 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
874 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000875 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000876 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
877 ConstraintType = SDTCisSubVecOfVec;
878 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
879 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000880 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
881 ConstraintType = SDTCVecEltisVT;
882 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
883 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
884 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
885 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
886 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
887 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
888 "as SDTCVecEltisVT");
889 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
890 ConstraintType = SDTCisSameNumEltsAs;
891 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
892 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000893 } else {
James Y Knighte452e272015-05-11 22:17:13 +0000894 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +0000895 }
896}
897
898/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000899/// N, and the result number in ResNo.
900static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
901 const SDNodeInfo &NodeInfo,
902 unsigned &ResNo) {
903 unsigned NumResults = NodeInfo.getNumResults();
904 if (OpNo < NumResults) {
905 ResNo = OpNo;
906 return N;
907 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000908
Chris Lattner2db7aba2010-03-19 21:56:21 +0000909 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000910
Chris Lattner2db7aba2010-03-19 21:56:21 +0000911 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +0000912 std::string S;
913 raw_string_ostream OS(S);
914 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000915 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +0000916 N->print(OS);
917 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +0000918 }
919
Chris Lattner2db7aba2010-03-19 21:56:21 +0000920 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000921}
922
923/// ApplyTypeConstraint - Given a node in a pattern, apply this type
924/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000925/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000926bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
927 const SDNodeInfo &NodeInfo,
928 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000929 if (TP.hasError())
930 return false;
931
Chris Lattner2db7aba2010-03-19 21:56:21 +0000932 unsigned ResNo = 0; // The result number being referenced.
933 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000934
Chris Lattner8cab0212008-01-05 22:25:12 +0000935 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000936 case SDTCisVT:
937 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000938 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000939 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000940 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000941 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000942 case SDTCisInt:
943 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000944 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000945 case SDTCisFP:
946 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000947 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000948 case SDTCisVec:
949 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000950 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000951 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000952 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000953 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000954 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +0000955 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
956 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000957 }
958 case SDTCisVTSmallerThanOp: {
959 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
960 // have an integer type that is smaller than the VT.
961 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +0000962 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +0000963 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000964 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000965 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000966 return false;
967 }
Owen Anderson9f944592009-08-11 20:47:22 +0000968 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +0000969 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000970
Chris Lattner38c99662010-03-24 00:06:46 +0000971 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000972
Chris Lattner2db7aba2010-03-19 21:56:21 +0000973 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000974 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000975 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
976 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +0000977
Chris Lattner38c99662010-03-24 00:06:46 +0000978 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000979 }
980 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000981 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000982 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000983 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
984 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000985 return NodeToApply->getExtType(ResNo).
986 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000987 }
Nate Begeman17bedbc2008-02-09 01:37:05 +0000988 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000989 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +0000990 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000991 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
992 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000993
Chris Lattner57ebf632010-03-24 00:01:16 +0000994 // Filter vector types out of VecOperand that don't have the right element
995 // type.
996 return VecOperand->getExtType(VResNo).
997 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +0000998 }
David Greene127fd1d2011-01-24 20:53:18 +0000999 case SDTCisSubVecOfVec: {
1000 unsigned VResNo = 0;
1001 TreePatternNode *BigVecOperand =
1002 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1003 VResNo);
1004
1005 // Filter vector types out of BigVecOperand that don't have the
1006 // right subvector type.
1007 return BigVecOperand->getExtType(VResNo).
1008 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1009 }
Craig Topper0be34582015-03-05 07:11:34 +00001010 case SDTCVecEltisVT: {
1011 return NodeToApply->getExtType(ResNo).
1012 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1013 }
1014 case SDTCisSameNumEltsAs: {
1015 unsigned OResNo = 0;
1016 TreePatternNode *OtherNode =
1017 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1018 N, NodeInfo, OResNo);
1019 return OtherNode->getExtType(OResNo).
1020 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1021 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001022 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001023 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001024}
1025
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001026// Update the node type to match an instruction operand or result as specified
1027// in the ins or outs lists on the instruction definition. Return true if the
1028// type was actually changed.
1029bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1030 Record *Operand,
1031 TreePattern &TP) {
1032 // The 'unknown' operand indicates that types should be inferred from the
1033 // context.
1034 if (Operand->isSubClassOf("unknown_class"))
1035 return false;
1036
1037 // The Operand class specifies a type directly.
1038 if (Operand->isSubClassOf("Operand"))
1039 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1040 TP);
1041
1042 // PointerLikeRegClass has a type that is determined at runtime.
1043 if (Operand->isSubClassOf("PointerLikeRegClass"))
1044 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1045
1046 // Both RegisterClass and RegisterOperand operands derive their types from a
1047 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001048 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001049 if (Operand->isSubClassOf("RegisterClass"))
1050 RC = Operand;
1051 else if (Operand->isSubClassOf("RegisterOperand"))
1052 RC = Operand->getValueAsDef("RegClass");
1053
1054 assert(RC && "Unknown operand type");
1055 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1056 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1057}
1058
1059
Chris Lattner8cab0212008-01-05 22:25:12 +00001060//===----------------------------------------------------------------------===//
1061// SDNodeInfo implementation
1062//
1063SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1064 EnumName = R->getValueAsString("Opcode");
1065 SDClassName = R->getValueAsString("SDClass");
1066 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1067 NumResults = TypeProfile->getValueAsInt("NumResults");
1068 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001069
Chris Lattner8cab0212008-01-05 22:25:12 +00001070 // Parse the properties.
1071 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001072 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1073 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001074 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001075 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001076 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001077 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001078 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001079 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001080 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001081 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001082 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001083 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001084 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001085 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001086 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001087 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001088 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001089 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001090 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001091 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001092 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001093 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001094 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001095 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001096 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001097 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001098 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001099 }
1100 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001101
1102
Chris Lattner8cab0212008-01-05 22:25:12 +00001103 // Parse the type constraints.
1104 std::vector<Record*> ConstraintList =
1105 TypeProfile->getValueAsListOfDefs("Constraints");
1106 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1107}
1108
Chris Lattner99e53b32010-02-28 00:22:30 +00001109/// getKnownType - If the type constraints on this node imply a fixed type
1110/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001111/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001112MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001113 unsigned NumResults = getNumResults();
1114 assert(NumResults <= 1 &&
1115 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001116 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001117
Craig Topper306cb122015-11-22 20:46:24 +00001118 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001119 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001120 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001121 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001122
Craig Topper306cb122015-11-22 20:46:24 +00001123 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001124 default: break;
1125 case SDTypeConstraint::SDTCisVT:
Craig Topper306cb122015-11-22 20:46:24 +00001126 return Constraint.x.SDTCisVT_Info.VT;
Chris Lattner99e53b32010-02-28 00:22:30 +00001127 case SDTypeConstraint::SDTCisPtrTy:
1128 return MVT::iPTR;
1129 }
1130 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001131 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001132}
1133
Chris Lattner8cab0212008-01-05 22:25:12 +00001134//===----------------------------------------------------------------------===//
1135// TreePatternNode implementation
1136//
1137
1138TreePatternNode::~TreePatternNode() {
1139#if 0 // FIXME: implement refcounted tree nodes!
1140 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1141 delete getChild(i);
1142#endif
1143}
1144
Chris Lattnerf1447252010-03-19 21:37:09 +00001145static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1146 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001147 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001148 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001149
Chris Lattner2109cb42010-03-22 20:56:36 +00001150 if (Operator->isSubClassOf("Intrinsic"))
1151 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001152
Chris Lattnerf1447252010-03-19 21:37:09 +00001153 if (Operator->isSubClassOf("SDNode"))
1154 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001155
Chris Lattnerf1447252010-03-19 21:37:09 +00001156 if (Operator->isSubClassOf("PatFrag")) {
1157 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1158 // the forward reference case where one pattern fragment references another
1159 // before it is processed.
1160 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1161 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001162
Chris Lattnerf1447252010-03-19 21:37:09 +00001163 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001164 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001165 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001166 if (Tree)
1167 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1168 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001169 assert(Op && "Invalid Fragment");
1170 return GetNumNodeResults(Op, CDP);
1171 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001172
Chris Lattnerf1447252010-03-19 21:37:09 +00001173 if (Operator->isSubClassOf("Instruction")) {
1174 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001175
Craig Topper3a8eb892015-03-20 05:09:06 +00001176 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1177
1178 // Subtract any defaulted outputs.
1179 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1180 Record *OperandNode = InstInfo.Operands[i].Rec;
1181
1182 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1183 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1184 --NumDefsToAdd;
1185 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001186
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001187 // Add on one implicit def if it has a resolvable type.
1188 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1189 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001190 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001191 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001192
Chris Lattnerf1447252010-03-19 21:37:09 +00001193 if (Operator->isSubClassOf("SDNodeXForm"))
1194 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001195
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001196 if (Operator->isSubClassOf("ValueType"))
1197 return 1; // A type-cast of one result.
1198
Tim Northoverc807a172014-05-20 11:52:46 +00001199 if (Operator->isSubClassOf("ComplexPattern"))
1200 return 1;
1201
Chris Lattnerf1447252010-03-19 21:37:09 +00001202 Operator->dump();
James Y Knighte452e272015-05-11 22:17:13 +00001203 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001204}
1205
1206void TreePatternNode::print(raw_ostream &OS) const {
1207 if (isLeaf())
1208 OS << *getLeafValue();
1209 else
1210 OS << '(' << getOperator()->getName();
1211
1212 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1213 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001214
1215 if (!isLeaf()) {
1216 if (getNumChildren() != 0) {
1217 OS << " ";
1218 getChild(0)->print(OS);
1219 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1220 OS << ", ";
1221 getChild(i)->print(OS);
1222 }
1223 }
1224 OS << ")";
1225 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001226
Craig Topper306cb122015-11-22 20:46:24 +00001227 for (const TreePredicateFn &Pred : PredicateFns)
1228 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001229 if (TransformFn)
1230 OS << "<<X:" << TransformFn->getName() << ">>";
1231 if (!getName().empty())
1232 OS << ":$" << getName();
1233
1234}
1235void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001236 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001237}
1238
Scott Michel94420742008-03-05 17:49:05 +00001239/// isIsomorphicTo - Return true if this node is recursively
1240/// isomorphic to the specified node. For this comparison, the node's
1241/// entire state is considered. The assigned name is ignored, since
1242/// nodes with differing names are considered isomorphic. However, if
1243/// the assigned name is present in the dependent variable set, then
1244/// the assigned name is considered significant and the node is
1245/// isomorphic if the names match.
1246bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1247 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001248 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001249 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001250 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001251 getTransformFn() != N->getTransformFn())
1252 return false;
1253
1254 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001255 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1256 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001257 return ((DI->getDef() == NDI->getDef())
1258 && (DepVars.find(getName()) == DepVars.end()
1259 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001260 }
1261 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001262 return getLeafValue() == N->getLeafValue();
1263 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001264
Chris Lattner8cab0212008-01-05 22:25:12 +00001265 if (N->getOperator() != getOperator() ||
1266 N->getNumChildren() != getNumChildren()) return false;
1267 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001268 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001269 return false;
1270 return true;
1271}
1272
1273/// clone - Make a copy of this tree and all of its children.
1274///
1275TreePatternNode *TreePatternNode::clone() const {
1276 TreePatternNode *New;
1277 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001278 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001279 } else {
1280 std::vector<TreePatternNode*> CChildren;
1281 CChildren.reserve(Children.size());
1282 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1283 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001284 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001285 }
1286 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001287 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001288 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001289 New->setTransformFn(getTransformFn());
1290 return New;
1291}
1292
Chris Lattner53c39ba2010-02-14 22:22:58 +00001293/// RemoveAllTypes - Recursively strip all the types of this tree.
1294void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001295 // Reset to unknown type.
1296 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001297 if (isLeaf()) return;
1298 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1299 getChild(i)->RemoveAllTypes();
1300}
1301
1302
Chris Lattner8cab0212008-01-05 22:25:12 +00001303/// SubstituteFormalArguments - Replace the formal arguments in this tree
1304/// with actual values specified by ArgMap.
1305void TreePatternNode::
1306SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1307 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001308
Chris Lattner8cab0212008-01-05 22:25:12 +00001309 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1310 TreePatternNode *Child = getChild(i);
1311 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001312 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001313 // Note that, when substituting into an output pattern, Val might be an
1314 // UnsetInit.
1315 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1316 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001317 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001318 TreePatternNode *NewChild = ArgMap[Child->getName()];
1319 assert(NewChild && "Couldn't find formal argument!");
1320 assert((Child->getPredicateFns().empty() ||
1321 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1322 "Non-empty child predicate clobbered!");
1323 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001324 }
1325 } else {
1326 getChild(i)->SubstituteFormalArguments(ArgMap);
1327 }
1328 }
1329}
1330
1331
1332/// InlinePatternFragments - If this pattern refers to any pattern
1333/// fragments, inline them into place, giving us a pattern without any
1334/// PatFrag references.
1335TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001336 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001337 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001338
1339 if (isLeaf())
1340 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001341 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001342
Chris Lattner8cab0212008-01-05 22:25:12 +00001343 if (!Op->isSubClassOf("PatFrag")) {
1344 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001345 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1346 TreePatternNode *Child = getChild(i);
1347 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1348
1349 assert((Child->getPredicateFns().empty() ||
1350 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1351 "Non-empty child predicate clobbered!");
1352
1353 setChild(i, NewChild);
1354 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001355 return this;
1356 }
1357
1358 // Otherwise, we found a reference to a fragment. First, look up its
1359 // TreePattern record.
1360 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001361
Chris Lattner8cab0212008-01-05 22:25:12 +00001362 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001363 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001364 TP.error("'" + Op->getName() + "' fragment requires " +
1365 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001366 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001367 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001368
1369 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1370
Chris Lattner514e2922011-04-17 21:38:24 +00001371 TreePredicateFn PredFn(Frag);
1372 if (!PredFn.isAlwaysTrue())
1373 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001374
Chris Lattner8cab0212008-01-05 22:25:12 +00001375 // Resolve formal arguments to their actual value.
1376 if (Frag->getNumArgs()) {
1377 // Compute the map of formal to actual arguments.
1378 std::map<std::string, TreePatternNode*> ArgMap;
1379 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1380 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001381
Chris Lattner8cab0212008-01-05 22:25:12 +00001382 FragTree->SubstituteFormalArguments(ArgMap);
1383 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001384
Chris Lattner8cab0212008-01-05 22:25:12 +00001385 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001386 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1387 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001388
1389 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001390 for (const TreePredicateFn &Pred : getPredicateFns())
1391 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001392
Chris Lattner8cab0212008-01-05 22:25:12 +00001393 // Get a new copy of this fragment to stitch into here.
1394 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001395
Chris Lattner2e253b42008-06-30 03:02:03 +00001396 // The fragment we inlined could have recursive inlining that is needed. See
1397 // if there are any pattern fragments in it and inline them as needed.
1398 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001399}
1400
1401/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001402/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001403/// references from the register file information, for example.
1404///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001405/// When Unnamed is set, return the type of a DAG operand with no name, such as
1406/// the F8RC register class argument in:
1407///
1408/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1409///
1410/// When Unnamed is false, return the type of a named DAG operand such as the
1411/// GPR:$src operand above.
1412///
Chris Lattnerf1447252010-03-19 21:37:09 +00001413static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001414 bool NotRegisters,
1415 bool Unnamed,
1416 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001417 // Check to see if this is a register operand.
1418 if (R->isSubClassOf("RegisterOperand")) {
1419 assert(ResNo == 0 && "Regoperand ref only has one result!");
1420 if (NotRegisters)
1421 return EEVT::TypeSet(); // Unknown.
1422 Record *RegClass = R->getValueAsDef("RegClass");
1423 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1424 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1425 }
1426
Chris Lattnercabe0372010-03-15 06:00:16 +00001427 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001428 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001429 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001430 // An unnamed register class represents itself as an i32 immediate, for
1431 // example on a COPY_TO_REGCLASS instruction.
1432 if (Unnamed)
1433 return EEVT::TypeSet(MVT::i32, TP);
1434
1435 // In a named operand, the register class provides the possible set of
1436 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001437 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001438 return EEVT::TypeSet(); // Unknown.
1439 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1440 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001441 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001442
Chris Lattner6070ee22010-03-23 23:50:31 +00001443 if (R->isSubClassOf("PatFrag")) {
1444 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001445 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001446 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001447 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001448
Chris Lattner6070ee22010-03-23 23:50:31 +00001449 if (R->isSubClassOf("Register")) {
1450 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001451 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001452 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001453 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001454 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001455 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001456
1457 if (R->isSubClassOf("SubRegIndex")) {
1458 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001459 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001460 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001461
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001462 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001463 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001464 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1465 //
1466 // (sext_inreg GPR:$src, i16)
1467 // ~~~
1468 if (Unnamed)
1469 return EEVT::TypeSet(MVT::Other, TP);
1470 // With a name, the ValueType simply provides the type of the named
1471 // variable.
1472 //
1473 // (sext_inreg i32:$src, i16)
1474 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001475 if (NotRegisters)
1476 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001477 return EEVT::TypeSet(getValueType(R), TP);
1478 }
1479
1480 if (R->isSubClassOf("CondCode")) {
1481 assert(ResNo == 0 && "This node only has one result!");
1482 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001483 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001484 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001485
Chris Lattner6070ee22010-03-23 23:50:31 +00001486 if (R->isSubClassOf("ComplexPattern")) {
1487 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001488 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001489 return EEVT::TypeSet(); // Unknown.
1490 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1491 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001492 }
1493 if (R->isSubClassOf("PointerLikeRegClass")) {
1494 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001495 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001496 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001497
Chris Lattner6070ee22010-03-23 23:50:31 +00001498 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1499 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001500 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001501 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001502 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001503
Tim Northoverc807a172014-05-20 11:52:46 +00001504 if (R->isSubClassOf("Operand"))
1505 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1506
Chris Lattner8cab0212008-01-05 22:25:12 +00001507 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001508 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001509}
1510
Chris Lattner89c65662008-01-06 05:36:50 +00001511
1512/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1513/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1514const CodeGenIntrinsic *TreePatternNode::
1515getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1516 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1517 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1518 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001519 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001520
Sean Silva88eb8dd2012-10-10 20:24:47 +00001521 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001522 return &CDP.getIntrinsicInfo(IID);
1523}
1524
Chris Lattner53c39ba2010-02-14 22:22:58 +00001525/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1526/// return the ComplexPattern information, otherwise return null.
1527const ComplexPattern *
1528TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001529 Record *Rec;
1530 if (isLeaf()) {
1531 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1532 if (!DI)
1533 return nullptr;
1534 Rec = DI->getDef();
1535 } else
1536 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001537
Tim Northoverc807a172014-05-20 11:52:46 +00001538 if (!Rec->isSubClassOf("ComplexPattern"))
1539 return nullptr;
1540 return &CGP.getComplexPattern(Rec);
1541}
1542
1543unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1544 // A ComplexPattern specifically declares how many results it fills in.
1545 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1546 return CP->getNumOperands();
1547
1548 // If MIOperandInfo is specified, that gives the count.
1549 if (isLeaf()) {
1550 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1551 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1552 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1553 if (MIOps->getNumArgs())
1554 return MIOps->getNumArgs();
1555 }
1556 }
1557
1558 // Otherwise there is just one result.
1559 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001560}
1561
1562/// NodeHasProperty - Return true if this node has the specified property.
1563bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001564 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001565 if (isLeaf()) {
1566 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1567 return CP->hasProperty(Property);
1568 return false;
1569 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001570
Chris Lattner53c39ba2010-02-14 22:22:58 +00001571 Record *Operator = getOperator();
1572 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001573
Chris Lattner53c39ba2010-02-14 22:22:58 +00001574 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1575}
1576
1577
1578
1579
1580/// TreeHasProperty - Return true if any node in this tree has the specified
1581/// property.
1582bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001583 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001584 if (NodeHasProperty(Property, CGP))
1585 return true;
1586 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1587 if (getChild(i)->TreeHasProperty(Property, CGP))
1588 return true;
1589 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001590}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001591
Evan Cheng49bad4c2008-06-16 20:29:38 +00001592/// isCommutativeIntrinsic - Return true if the node corresponds to a
1593/// commutative intrinsic.
1594bool
1595TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1596 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1597 return Int->isCommutative;
1598 return false;
1599}
1600
Matt Arsenaulteb492162014-11-02 23:46:51 +00001601static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1602 if (!N->isLeaf())
1603 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001604
Matt Arsenaulteb492162014-11-02 23:46:51 +00001605 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1606 if (DI && DI->getDef()->isSubClassOf(Class))
1607 return true;
1608
1609 return false;
1610}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001611
1612static void emitTooManyOperandsError(TreePattern &TP,
1613 StringRef InstName,
1614 unsigned Expected,
1615 unsigned Actual) {
1616 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1617 " operands but expected only " + Twine(Expected) + "!");
1618}
1619
1620static void emitTooFewOperandsError(TreePattern &TP,
1621 StringRef InstName,
1622 unsigned Actual) {
1623 TP.error("Instruction '" + InstName +
1624 "' expects more than the provided " + Twine(Actual) + " operands!");
1625}
1626
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001627/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001628/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001629/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001630bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001631 if (TP.hasError())
1632 return false;
1633
Chris Lattnerab3242f2008-01-06 01:10:31 +00001634 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001635 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001636 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001637 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001638 bool MadeChange = false;
1639 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1640 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001641 NotRegisters,
1642 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001643 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001644 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001645
Sean Silvafb509ed2012-10-10 20:24:43 +00001646 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001647 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001648
Chris Lattnerf1447252010-03-19 21:37:09 +00001649 // Int inits are always integers. :)
1650 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001651
Chris Lattnerf1447252010-03-19 21:37:09 +00001652 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001653 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001654
Chris Lattnerf1447252010-03-19 21:37:09 +00001655 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001656 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1657 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001658
Craig Topper95198f42013-09-25 06:37:18 +00001659 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001660 // Make sure that the value is representable for this type.
1661 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001662
Richard Smith228e6d42012-08-24 23:29:28 +00001663 // Check that the value doesn't use more bits than we have. It must either
1664 // be a sign- or zero-extended equivalent of the original.
1665 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1666 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001667 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001668
Richard Smith228e6d42012-08-24 23:29:28 +00001669 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001670 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001671 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001672 }
1673 return false;
1674 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001675
Chris Lattner8cab0212008-01-05 22:25:12 +00001676 // special handling for set, which isn't really an SDNode.
1677 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001678 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1679 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001680 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001681
Chris Lattnerf1447252010-03-19 21:37:09 +00001682 TreePatternNode *SetVal = getChild(NC-1);
1683 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1684
Elena Demikhovsky09954792015-03-01 08:23:41 +00001685 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001686 TreePatternNode *Child = getChild(i);
1687 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001688
Chris Lattner8cab0212008-01-05 22:25:12 +00001689 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001690 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1691 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001692 }
1693 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001694 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001695
Chris Lattner5c2182e2010-03-27 02:53:27 +00001696 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001697 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1698
Chris Lattner8cab0212008-01-05 22:25:12 +00001699 bool MadeChange = false;
1700 for (unsigned i = 0; i < getNumChildren(); ++i)
1701 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001702 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001703 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001704
Chris Lattneree820ac2010-02-23 05:51:07 +00001705 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001706 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001707
Chris Lattner8cab0212008-01-05 22:25:12 +00001708 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001709 unsigned NumRetVTs = Int->IS.RetVTs.size();
1710 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001711
Bill Wendling91821472008-11-13 09:08:33 +00001712 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001713 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001714
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001715 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001716 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001717 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001718 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001719 return false;
1720 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001721
1722 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001723 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001724
Chris Lattnerf1447252010-03-19 21:37:09 +00001725 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1726 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001727
Chris Lattnerf1447252010-03-19 21:37:09 +00001728 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1729 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1730 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001731 }
1732 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001733 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001734
Chris Lattneree820ac2010-02-23 05:51:07 +00001735 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001736 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001737
Chris Lattner135091b2010-03-28 08:48:47 +00001738 // Check that the number of operands is sane. Negative operands -> varargs.
1739 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001740 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001741 TP.error(getOperator()->getName() + " node requires exactly " +
1742 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001743 return false;
1744 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001745
Chris Lattner8cab0212008-01-05 22:25:12 +00001746 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1747 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1748 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001749 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001750 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001751
Chris Lattneree820ac2010-02-23 05:51:07 +00001752 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001753 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001754 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001755 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001756
Chris Lattnerd44966f2010-03-27 19:15:02 +00001757 bool MadeChange = false;
1758
1759 // Apply the result types to the node, these come from the things in the
1760 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001761 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1762 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001763 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1764 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001765
Chris Lattnerd44966f2010-03-27 19:15:02 +00001766 // If the instruction has implicit defs, we apply the first one as a result.
1767 // FIXME: This sucks, it should apply all implicit defs.
1768 if (!InstInfo.ImplicitDefs.empty()) {
1769 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001770
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001771 // FIXME: Generalize to multiple possible types and multiple possible
1772 // ImplicitDefs.
1773 MVT::SimpleValueType VT =
1774 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001775
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001776 if (VT != MVT::Other)
1777 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001778 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001779
Chris Lattnercabe0372010-03-15 06:00:16 +00001780 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1781 // be the same.
1782 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001783 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1784 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1785 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001786 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1787 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1788 // variadic.
1789
1790 unsigned NChild = getNumChildren();
1791 if (NChild < 3) {
1792 TP.error("REG_SEQUENCE requires at least 3 operands!");
1793 return false;
1794 }
1795
1796 if (NChild % 2 == 0) {
1797 TP.error("REG_SEQUENCE requires an odd number of operands!");
1798 return false;
1799 }
1800
1801 if (!isOperandClass(getChild(0), "RegisterClass")) {
1802 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1803 return false;
1804 }
1805
1806 for (unsigned I = 1; I < NChild; I += 2) {
1807 TreePatternNode *SubIdxChild = getChild(I + 1);
1808 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1809 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1810 itostr(I + 1) + "!");
1811 return false;
1812 }
1813 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001814 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001815
1816 unsigned ChildNo = 0;
1817 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1818 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001819
Chris Lattner8cab0212008-01-05 22:25:12 +00001820 // If the instruction expects a predicate or optional def operand, we
1821 // codegen this by setting the operand to it's default value if it has a
1822 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001823 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001824 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1825 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001826
Chris Lattner8cab0212008-01-05 22:25:12 +00001827 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001828 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001829 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001830 return false;
1831 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001832
Chris Lattner8cab0212008-01-05 22:25:12 +00001833 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001834 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001835
1836 // If the operand has sub-operands, they may be provided by distinct
1837 // child patterns, so attempt to match each sub-operand separately.
1838 if (OperandNode->isSubClassOf("Operand")) {
1839 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1840 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1841 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001842 // a single ComplexPattern-related Operand.
1843
1844 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001845 // Match first sub-operand against the child we already have.
1846 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1847 MadeChange |=
1848 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1849
1850 // And the remaining sub-operands against subsequent children.
1851 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1852 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001853 emitTooFewOperandsError(TP, getOperator()->getName(),
1854 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001855 return false;
1856 }
1857 Child = getChild(ChildNo++);
1858
1859 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1860 MadeChange |=
1861 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1862 }
1863 continue;
1864 }
1865 }
1866 }
1867
1868 // If we didn't match by pieces above, attempt to match the whole
1869 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001870 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001871 }
Christopher Lamba7312392008-03-11 09:33:47 +00001872
Matt Arsenaulteb492162014-11-02 23:46:51 +00001873 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001874 emitTooManyOperandsError(TP, getOperator()->getName(),
1875 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001876 return false;
1877 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001878
Ulrich Weigande618abd2013-03-19 19:51:09 +00001879 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1880 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001881 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001882 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001883
Tim Northoverc807a172014-05-20 11:52:46 +00001884 if (getOperator()->isSubClassOf("ComplexPattern")) {
1885 bool MadeChange = false;
1886
1887 for (unsigned i = 0; i < getNumChildren(); ++i)
1888 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1889
1890 return MadeChange;
1891 }
1892
Chris Lattneree820ac2010-02-23 05:51:07 +00001893 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001894
Chris Lattneree820ac2010-02-23 05:51:07 +00001895 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001896 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001897 TP.error("Node transform '" + getOperator()->getName() +
1898 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001899 return false;
1900 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001901
Chris Lattnercabe0372010-03-15 06:00:16 +00001902 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1903
Jim Grosbach65586fe2010-12-21 16:16:00 +00001904
Chris Lattneree820ac2010-02-23 05:51:07 +00001905 // If either the output or input of the xform does not have exact
1906 // type info. We assume they must be the same. Otherwise, it is perfectly
1907 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001908#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001909 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001910 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1911 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001912 return MadeChange;
1913 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001914#endif
1915 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001916}
1917
1918/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1919/// RHS of a commutative operation, not the on LHS.
1920static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1921 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1922 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001923 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001924 return true;
1925 return false;
1926}
1927
1928
1929/// canPatternMatch - If it is impossible for this pattern to match on this
1930/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001931/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001932/// that can never possibly work), and to prevent the pattern permuter from
1933/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001934bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001935 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001936 if (isLeaf()) return true;
1937
1938 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1939 if (!getChild(i)->canPatternMatch(Reason, CDP))
1940 return false;
1941
1942 // If this is an intrinsic, handle cases that would make it not match. For
1943 // example, if an operand is required to be an immediate.
1944 if (getOperator()->isSubClassOf("Intrinsic")) {
1945 // TODO:
1946 return true;
1947 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001948
Tim Northoverc807a172014-05-20 11:52:46 +00001949 if (getOperator()->isSubClassOf("ComplexPattern"))
1950 return true;
1951
Chris Lattner8cab0212008-01-05 22:25:12 +00001952 // If this node is a commutative operator, check that the LHS isn't an
1953 // immediate.
1954 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001955 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1956 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001957 // Scan all of the operands of the node and make sure that only the last one
1958 // is a constant node, unless the RHS also is.
1959 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001960 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1961 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001962 if (OnlyOnRHSOfCommutative(getChild(i))) {
1963 Reason="Immediate value must be on the RHS of commutative operators!";
1964 return false;
1965 }
1966 }
1967 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001968
Chris Lattner8cab0212008-01-05 22:25:12 +00001969 return true;
1970}
1971
1972//===----------------------------------------------------------------------===//
1973// TreePattern implementation
1974//
1975
David Greeneaf8ee2c2011-07-29 22:43:06 +00001976TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001977 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1978 isInputPattern(isInput), HasError(false) {
Craig Topperef0578a2015-06-02 04:15:51 +00001979 for (Init *I : RawPat->getValues())
1980 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001981}
1982
David Greeneaf8ee2c2011-07-29 22:43:06 +00001983TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001984 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1985 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001986 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001987}
1988
David Blaikiecf195302014-11-17 22:55:41 +00001989TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001990 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1991 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00001992 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00001993}
1994
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00001995void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001996 if (HasError)
1997 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001998 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001999 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2000 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002001}
2002
Chris Lattnercabe0372010-03-15 06:00:16 +00002003void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002004 for (TreePatternNode *Tree : Trees)
2005 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002006}
2007
2008void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2009 if (!N->getName().empty())
2010 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002011
Chris Lattnercabe0372010-03-15 06:00:16 +00002012 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2013 ComputeNamedNodes(N->getChild(i));
2014}
2015
David Blaikiecf195302014-11-17 22:55:41 +00002016
2017TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002018 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002019 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002020
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002021 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002022 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002023 /// (foo GPR, imm) -> (foo GPR, (imm))
2024 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002025 return ParseTreePattern(
2026 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002027 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002028 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002029
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002030 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002031 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002032 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002033 if (OpName.empty())
2034 error("'node' argument requires a name to match with operand list");
2035 Args.push_back(OpName);
2036 }
2037
2038 Res->setName(OpName);
2039 return Res;
2040 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002041
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002042 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002043 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002044 if (OpName.empty())
2045 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002046 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002047 Args.push_back(OpName);
2048 Res->setName(OpName);
2049 return Res;
2050 }
2051
Sean Silvafb509ed2012-10-10 20:24:43 +00002052 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002053 if (!OpName.empty())
2054 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002055 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002056 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002057
Sean Silvafb509ed2012-10-10 20:24:43 +00002058 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002059 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002060 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002061 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002062 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002063 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002064 }
2065
Sean Silvafb509ed2012-10-10 20:24:43 +00002066 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002067 if (!Dag) {
2068 TheInit->dump();
2069 error("Pattern has unexpected init kind!");
2070 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002071 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002072 if (!OpDef) error("Pattern has unexpected operator type!");
2073 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002074
Chris Lattner8cab0212008-01-05 22:25:12 +00002075 if (Operator->isSubClassOf("ValueType")) {
2076 // If the operator is a ValueType, then this must be "type cast" of a leaf
2077 // node.
2078 if (Dag->getNumArgs() != 1)
2079 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002080
David Blaikiecf195302014-11-17 22:55:41 +00002081 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002082
Chris Lattner8cab0212008-01-05 22:25:12 +00002083 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002084 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2085 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002086
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002087 if (!OpName.empty())
2088 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002089 return New;
2090 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002091
Chris Lattner8cab0212008-01-05 22:25:12 +00002092 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002093 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002094 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002095 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002096 !Operator->isSubClassOf("SDNodeXForm") &&
2097 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002098 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002099 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002100 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002101 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002102
Chris Lattner8cab0212008-01-05 22:25:12 +00002103 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002104 if (isInputPattern) {
2105 if (Operator->isSubClassOf("Instruction") ||
2106 Operator->isSubClassOf("SDNodeXForm"))
2107 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2108 } else {
2109 if (Operator->isSubClassOf("Intrinsic"))
2110 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002111
Chris Lattner2e9eae12010-03-28 06:57:56 +00002112 if (Operator->isSubClassOf("SDNode") &&
2113 Operator->getName() != "imm" &&
2114 Operator->getName() != "fpimm" &&
2115 Operator->getName() != "tglobaltlsaddr" &&
2116 Operator->getName() != "tconstpool" &&
2117 Operator->getName() != "tjumptable" &&
2118 Operator->getName() != "tframeindex" &&
2119 Operator->getName() != "texternalsym" &&
2120 Operator->getName() != "tblockaddress" &&
2121 Operator->getName() != "tglobaladdr" &&
2122 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002123 Operator->getName() != "vt" &&
2124 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002125 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2126 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002127
Chris Lattner8cab0212008-01-05 22:25:12 +00002128 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002129
2130 // Parse all the operands.
2131 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002132 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002133
Chris Lattner8cab0212008-01-05 22:25:12 +00002134 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002135 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002136 // convert the intrinsic name to a number.
2137 if (Operator->isSubClassOf("Intrinsic")) {
2138 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2139 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2140
2141 // If this intrinsic returns void, it must have side-effects and thus a
2142 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002143 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002144 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002145 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002146 // Has side-effects, requires chain.
2147 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002148 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002149 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002150
David Greenee32ebf22011-07-29 19:07:07 +00002151 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002152 Children.insert(Children.begin(), IIDNode);
2153 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002154
Tim Northoverc807a172014-05-20 11:52:46 +00002155 if (Operator->isSubClassOf("ComplexPattern")) {
2156 for (unsigned i = 0; i < Children.size(); ++i) {
2157 TreePatternNode *Child = Children[i];
2158
2159 if (Child->getName().empty())
2160 error("All arguments to a ComplexPattern must be named");
2161
2162 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2163 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2164 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2165 auto OperandId = std::make_pair(Operator, i);
2166 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2167 if (PrevOp != ComplexPatternOperands.end()) {
2168 if (PrevOp->getValue() != OperandId)
2169 error("All ComplexPattern operands must appear consistently: "
2170 "in the same order in just one ComplexPattern instance.");
2171 } else
2172 ComplexPatternOperands[Child->getName()] = OperandId;
2173 }
2174 }
2175
Chris Lattnerf1447252010-03-19 21:37:09 +00002176 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002177 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002178 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002179
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002180 if (!Dag->getName().empty()) {
2181 assert(Result->getName().empty());
2182 Result->setName(Dag->getName());
2183 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002184 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002185}
2186
Chris Lattnera787c9e2010-03-28 08:38:32 +00002187/// SimplifyTree - See if we can simplify this tree to eliminate something that
2188/// will never match in favor of something obvious that will. This is here
2189/// strictly as a convenience to target authors because it allows them to write
2190/// more type generic things and have useless type casts fold away.
2191///
2192/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002193static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002194 if (N->isLeaf())
2195 return false;
2196
2197 // If we have a bitconvert with a resolved type and if the source and
2198 // destination types are the same, then the bitconvert is useless, remove it.
2199 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002200 N->getExtType(0).isConcrete() &&
2201 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2202 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002203 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002204 SimplifyTree(N);
2205 return true;
2206 }
2207
2208 // Walk all children.
2209 bool MadeChange = false;
2210 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002211 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002212 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002213 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002214 }
2215 return MadeChange;
2216}
2217
2218
2219
Chris Lattner8cab0212008-01-05 22:25:12 +00002220/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002221/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002222/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002223bool TreePattern::
2224InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2225 if (NamedNodes.empty())
2226 ComputeNamedNodes();
2227
Chris Lattner8cab0212008-01-05 22:25:12 +00002228 bool MadeChange = true;
2229 while (MadeChange) {
2230 MadeChange = false;
Craig Topper306cb122015-11-22 20:46:24 +00002231 for (TreePatternNode *Tree : Trees) {
2232 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2233 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002234 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002235
2236 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002237 for (auto &Entry : NamedNodes) {
2238 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002239
Chris Lattnercabe0372010-03-15 06:00:16 +00002240 // If we have input named node types, propagate their types to the named
2241 // values here.
2242 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002243 if (!InNamedTypes->count(Entry.getKey())) {
2244 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002245 "' in output pattern but not input pattern");
2246 return true;
2247 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002248
2249 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002250 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002251
2252 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002253 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002254 // If this node is a register class, and it is the root of the pattern
2255 // then we're mapping something onto an input register. We allow
2256 // changing the type of the input register in this case. This allows
2257 // us to match things like:
2258 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002259 if (Node == Trees[0] && Node->isLeaf()) {
2260 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002261 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2262 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002263 continue;
2264 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002265
Craig Topper306cb122015-11-22 20:46:24 +00002266 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002267 InNodes[0]->getNumTypes() == 1 &&
2268 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002269 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2270 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002271 }
2272 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002273
Chris Lattnercabe0372010-03-15 06:00:16 +00002274 // If there are multiple nodes with the same name, they must all have the
2275 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002276 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002277 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002278 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002279 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002280 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002281
Chris Lattnerf1447252010-03-19 21:37:09 +00002282 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2283 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002284 }
2285 }
2286 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002287 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002288
Chris Lattner8cab0212008-01-05 22:25:12 +00002289 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002290 for (const TreePatternNode *Tree : Trees)
2291 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
Chris Lattner8cab0212008-01-05 22:25:12 +00002292 return !HasUnresolvedTypes;
2293}
2294
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002295void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002296 OS << getRecord()->getName();
2297 if (!Args.empty()) {
2298 OS << "(" << Args[0];
2299 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2300 OS << ", " << Args[i];
2301 OS << ")";
2302 }
2303 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002304
Chris Lattner8cab0212008-01-05 22:25:12 +00002305 if (Trees.size() > 1)
2306 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002307 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002308 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002309 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002310 OS << "\n";
2311 }
2312
2313 if (Trees.size() > 1)
2314 OS << "]\n";
2315}
2316
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002317void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002318
2319//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002320// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002321//
2322
Jim Grosbach65586fe2010-12-21 16:16:00 +00002323CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002324 Records(R), Target(R) {
2325
Dale Johannesenb842d522009-02-05 01:49:45 +00002326 Intrinsics = LoadIntrinsics(Records, false);
2327 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002328 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002329 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002330 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002331 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002332 ParseDefaultOperands();
2333 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002334 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002335 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002336
Chris Lattner8cab0212008-01-05 22:25:12 +00002337 // Generate variants. For example, commutative patterns can match
2338 // multiple ways. Add them to PatternsToMatch as well.
2339 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002340
2341 // Infer instruction flags. For example, we can detect loads,
2342 // stores, and side effects in many cases by examining an
2343 // instruction's pattern.
2344 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002345
2346 // Verify that instruction flags match the patterns.
2347 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002348}
2349
Chris Lattnerab3242f2008-01-06 01:10:31 +00002350Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002351 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002352 if (!N || !N->isSubClassOf("SDNode"))
2353 PrintFatalError("Error getting SDNode '" + Name + "'!");
2354
Chris Lattner8cab0212008-01-05 22:25:12 +00002355 return N;
2356}
2357
2358// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002359void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002360 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2361 while (!Nodes.empty()) {
2362 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2363 Nodes.pop_back();
2364 }
2365
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002366 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002367 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2368 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2369 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2370}
2371
2372/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2373/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002374void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002375 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2376 while (!Xforms.empty()) {
2377 Record *XFormNode = Xforms.back();
2378 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002379 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002380 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002381
2382 Xforms.pop_back();
2383 }
2384}
2385
Chris Lattnerab3242f2008-01-06 01:10:31 +00002386void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002387 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2388 while (!AMs.empty()) {
2389 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2390 AMs.pop_back();
2391 }
2392}
2393
2394
2395/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2396/// file, building up the PatternFragments map. After we've collected them all,
2397/// inline fragments together as necessary, so that there are no references left
2398/// inside a pattern fragment to a pattern fragment.
2399///
Hal Finkel2756dc12014-02-28 00:26:56 +00002400void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002401 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002402
Chris Lattnere7170df2008-01-05 22:43:57 +00002403 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002404 for (Record *Frag : Fragments) {
2405 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002406 continue;
2407
Craig Topper306cb122015-11-22 20:46:24 +00002408 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002409 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002410 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2411 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002412 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002413
Chris Lattnere7170df2008-01-05 22:43:57 +00002414 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002415 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002416 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002417
Chris Lattnere7170df2008-01-05 22:43:57 +00002418 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002419 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002420
Chris Lattner8cab0212008-01-05 22:25:12 +00002421 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002422 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002423 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002424 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002425 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002426 if (!OpsOp ||
2427 (OpsOp->getDef()->getName() != "ops" &&
2428 OpsOp->getDef()->getName() != "outs" &&
2429 OpsOp->getDef()->getName() != "ins"))
2430 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002431
2432 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002433 Args.clear();
2434 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002435 if (!isa<DefInit>(OpsList->getArg(j)) ||
2436 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002437 P->error("Operands list should all be 'node' values.");
2438 if (OpsList->getArgName(j).empty())
2439 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002440 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002441 P->error("'" + OpsList->getArgName(j) +
2442 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002443 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002444 Args.push_back(OpsList->getArgName(j));
2445 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002446
Chris Lattnere7170df2008-01-05 22:43:57 +00002447 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002448 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002449 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002450
Chris Lattnere7170df2008-01-05 22:43:57 +00002451 // If there is a code init for this fragment, keep track of the fact that
2452 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002453 TreePredicateFn PredFn(P);
2454 if (!PredFn.isAlwaysTrue())
2455 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002456
Chris Lattner8cab0212008-01-05 22:25:12 +00002457 // If there is a node transformation corresponding to this, keep track of
2458 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002459 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002460 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2461 P->getOnlyTree()->setTransformFn(Transform);
2462 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002463
Chris Lattner8cab0212008-01-05 22:25:12 +00002464 // Now that we've parsed all of the tree fragments, do a closure on them so
2465 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002466 for (Record *Frag : Fragments) {
2467 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002468 continue;
2469
Craig Topper306cb122015-11-22 20:46:24 +00002470 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002471 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002472
Chris Lattner8cab0212008-01-05 22:25:12 +00002473 // Infer as many types as possible. Don't worry about it if we don't infer
2474 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002475 ThePat.InferAllTypes();
2476 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002477
Chris Lattner8cab0212008-01-05 22:25:12 +00002478 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002479 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002480 }
2481}
2482
Chris Lattnerab3242f2008-01-06 01:10:31 +00002483void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002484 std::vector<Record*> DefaultOps;
2485 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002486
2487 // Find some SDNode.
2488 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002489 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002490
Tom Stellardb7246a72012-09-06 14:15:52 +00002491 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2492 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002493
Tom Stellardb7246a72012-09-06 14:15:52 +00002494 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2495 // SomeSDnode so that we can parse this.
2496 std::vector<std::pair<Init*, std::string> > Ops;
2497 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2498 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2499 DefaultInfo->getArgName(op)));
2500 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002501
Tom Stellardb7246a72012-09-06 14:15:52 +00002502 // Create a TreePattern to parse this.
2503 TreePattern P(DefaultOps[i], DI, false, *this);
2504 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002505
Tom Stellardb7246a72012-09-06 14:15:52 +00002506 // Copy the operands over into a DAGDefaultOperand.
2507 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002508
Tom Stellardb7246a72012-09-06 14:15:52 +00002509 TreePatternNode *T = P.getTree(0);
2510 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2511 TreePatternNode *TPN = T->getChild(op);
2512 while (TPN->ApplyTypeConstraints(P, false))
2513 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002514
Tom Stellardb7246a72012-09-06 14:15:52 +00002515 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002516 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2517 DefaultOps[i]->getName() +
2518 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002519 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002520 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002521 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002522
2523 // Insert it into the DefaultOperands map so we can find it later.
2524 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002525 }
2526}
2527
2528/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2529/// instruction input. Return true if this is a real use.
2530static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002531 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002532 // No name -> not interesting.
2533 if (Pat->getName().empty()) {
2534 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002535 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002536 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2537 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002538 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002539 }
2540 return false;
2541 }
2542
2543 Record *Rec;
2544 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002545 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002546 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2547 Rec = DI->getDef();
2548 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002549 Rec = Pat->getOperator();
2550 }
2551
2552 // SRCVALUE nodes are ignored.
2553 if (Rec->getName() == "srcvalue")
2554 return false;
2555
2556 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2557 if (!Slot) {
2558 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002559 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002560 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002561 Record *SlotRec;
2562 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002563 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002564 } else {
2565 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2566 SlotRec = Slot->getOperator();
2567 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002568
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002569 // Ensure that the inputs agree if we've already seen this input.
2570 if (Rec != SlotRec)
2571 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002572 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002573 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002574 return true;
2575}
2576
2577/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2578/// part of "I", the instruction), computing the set of inputs and outputs of
2579/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002580void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002581FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2582 std::map<std::string, TreePatternNode*> &InstInputs,
2583 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002584 std::vector<Record*> &InstImpResults) {
2585 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002586 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002587 if (!isUse && Pat->getTransformFn())
2588 I->error("Cannot specify a transform function for a non-input value!");
2589 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002590 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002591
Chris Lattnerf2d70992010-02-17 06:53:36 +00002592 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002593 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2594 TreePatternNode *Dest = Pat->getChild(i);
2595 if (!Dest->isLeaf())
2596 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002597
Sean Silvafb509ed2012-10-10 20:24:43 +00002598 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002599 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2600 I->error("implicitly defined value should be a register!");
2601 InstImpResults.push_back(Val->getDef());
2602 }
2603 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002604 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002605
Chris Lattnerf2d70992010-02-17 06:53:36 +00002606 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002607 // If this is not a set, verify that the children nodes are not void typed,
2608 // and recurse.
2609 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002610 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002611 I->error("Cannot have void nodes inside of patterns!");
2612 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002613 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002614 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002615
Chris Lattner8cab0212008-01-05 22:25:12 +00002616 // If this is a non-leaf node with no children, treat it basically as if
2617 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002618 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002619
Chris Lattner8cab0212008-01-05 22:25:12 +00002620 if (!isUse && Pat->getTransformFn())
2621 I->error("Cannot specify a transform function for a non-input value!");
2622 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002623 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002624
Chris Lattner8cab0212008-01-05 22:25:12 +00002625 // Otherwise, this is a set, validate and collect instruction results.
2626 if (Pat->getNumChildren() == 0)
2627 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002628
Chris Lattner8cab0212008-01-05 22:25:12 +00002629 if (Pat->getTransformFn())
2630 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002631
Chris Lattner8cab0212008-01-05 22:25:12 +00002632 // Check the set destinations.
2633 unsigned NumDests = Pat->getNumChildren()-1;
2634 for (unsigned i = 0; i != NumDests; ++i) {
2635 TreePatternNode *Dest = Pat->getChild(i);
2636 if (!Dest->isLeaf())
2637 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002638
Sean Silvafb509ed2012-10-10 20:24:43 +00002639 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002640 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002641 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002642 continue;
2643 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002644
2645 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002646 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002647 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002648 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002649 if (Dest->getName().empty())
2650 I->error("set destination must have a name!");
2651 if (InstResults.count(Dest->getName()))
2652 I->error("cannot set '" + Dest->getName() +"' multiple times");
2653 InstResults[Dest->getName()] = Dest;
2654 } else if (Val->getDef()->isSubClassOf("Register")) {
2655 InstImpResults.push_back(Val->getDef());
2656 } else {
2657 I->error("set destination should be a register!");
2658 }
2659 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002660
Chris Lattner8cab0212008-01-05 22:25:12 +00002661 // Verify and collect info from the computation.
2662 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002663 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002664}
2665
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002666//===----------------------------------------------------------------------===//
2667// Instruction Analysis
2668//===----------------------------------------------------------------------===//
2669
2670class InstAnalyzer {
2671 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002672public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002673 bool hasSideEffects;
2674 bool mayStore;
2675 bool mayLoad;
2676 bool isBitcast;
2677 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002678
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002679 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2680 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2681 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002682
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002683 void Analyze(const TreePattern *Pat) {
2684 // Assume only the first tree is the pattern. The others are clobber nodes.
2685 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002686 }
2687
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002688 void Analyze(const PatternToMatch *Pat) {
2689 AnalyzeNode(Pat->getSrcPattern());
2690 }
2691
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002692private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002693 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002694 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002695 return false;
2696
2697 if (N->getNumChildren() != 2)
2698 return false;
2699
2700 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002701 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002702 return false;
2703
2704 const TreePatternNode *N1 = N->getChild(1);
2705 if (N1->isLeaf())
2706 return false;
2707 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2708 return false;
2709
2710 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2711 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2712 return false;
2713 return OpInfo.getEnumName() == "ISD::BITCAST";
2714 }
2715
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002716public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002717 void AnalyzeNode(const TreePatternNode *N) {
2718 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002719 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002720 Record *LeafRec = DI->getDef();
2721 // Handle ComplexPattern leaves.
2722 if (LeafRec->isSubClassOf("ComplexPattern")) {
2723 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2724 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2725 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002726 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002727 }
2728 }
2729 return;
2730 }
2731
2732 // Analyze children.
2733 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2734 AnalyzeNode(N->getChild(i));
2735
2736 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002737 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002738 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002739 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002740 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002741
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002742 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002743 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2744 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2745 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2746 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002747
2748 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2749 // If this is an intrinsic, analyze it.
2750 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2751 mayLoad = true;// These may load memory.
2752
Dan Gohmanddb2d652010-08-05 23:36:21 +00002753 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002754 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2755
Dan Gohmanddb2d652010-08-05 23:36:21 +00002756 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002757 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002758 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002759 }
2760 }
2761
2762};
2763
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002764static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002765 const InstAnalyzer &PatInfo,
2766 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002767 bool Error = false;
2768
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002769 // Remember where InstInfo got its flags.
2770 if (InstInfo.hasUndefFlags())
2771 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002772
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002773 // Check explicitly set flags for consistency.
2774 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2775 !InstInfo.hasSideEffects_Unset) {
2776 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2777 // the pattern has no side effects. That could be useful for div/rem
2778 // instructions that may trap.
2779 if (!InstInfo.hasSideEffects) {
2780 Error = true;
2781 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2782 Twine(InstInfo.hasSideEffects));
2783 }
2784 }
2785
2786 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2787 Error = true;
2788 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2789 Twine(InstInfo.mayStore));
2790 }
2791
2792 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2793 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00002794 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002795 if (!InstInfo.mayLoad) {
2796 Error = true;
2797 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2798 Twine(InstInfo.mayLoad));
2799 }
2800 }
2801
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002802 // Transfer inferred flags.
2803 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2804 InstInfo.mayStore |= PatInfo.mayStore;
2805 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002806
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002807 // These flags are silently added without any verification.
2808 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002809
2810 // Don't infer isVariadic. This flag means something different on SDNodes and
2811 // instructions. For example, a CALL SDNode is variadic because it has the
2812 // call arguments as operands, but a CALL instruction is not variadic - it
2813 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002814
2815 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002816}
2817
Jim Grosbach514410b2012-07-17 00:47:06 +00002818/// hasNullFragReference - Return true if the DAG has any reference to the
2819/// null_frag operator.
2820static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002821 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002822 if (!OpDef) return false;
2823 Record *Operator = OpDef->getDef();
2824
2825 // If this is the null fragment, return true.
2826 if (Operator->getName() == "null_frag") return true;
2827 // If any of the arguments reference the null fragment, return true.
2828 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002829 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002830 if (Arg && hasNullFragReference(Arg))
2831 return true;
2832 }
2833
2834 return false;
2835}
2836
2837/// hasNullFragReference - Return true if any DAG in the list references
2838/// the null_frag operator.
2839static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00002840 for (Init *I : LI->getValues()) {
2841 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00002842 assert(DI && "non-dag in an instruction Pattern list?!");
2843 if (hasNullFragReference(DI))
2844 return true;
2845 }
2846 return false;
2847}
2848
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002849/// Get all the instructions in a tree.
2850static void
2851getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2852 if (Tree->isLeaf())
2853 return;
2854 if (Tree->getOperator()->isSubClassOf("Instruction"))
2855 Instrs.push_back(Tree->getOperator());
2856 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2857 getInstructionsInTree(Tree->getChild(i), Instrs);
2858}
2859
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002860/// Check the class of a pattern leaf node against the instruction operand it
2861/// represents.
2862static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2863 Record *Leaf) {
2864 if (OI.Rec == Leaf)
2865 return true;
2866
2867 // Allow direct value types to be used in instruction set patterns.
2868 // The type will be checked later.
2869 if (Leaf->isSubClassOf("ValueType"))
2870 return true;
2871
2872 // Patterns can also be ComplexPattern instances.
2873 if (Leaf->isSubClassOf("ComplexPattern"))
2874 return true;
2875
2876 return false;
2877}
2878
Ahmed Bougacha14107512013-10-28 18:07:21 +00002879const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2880 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002881
Craig Topper0d1fb902015-03-10 03:25:04 +00002882 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002883
Craig Topper0d1fb902015-03-10 03:25:04 +00002884 // Parse the instruction.
2885 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2886 // Inline pattern fragments into it.
2887 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002888
Craig Topper0d1fb902015-03-10 03:25:04 +00002889 // Infer as many types as possible. If we cannot infer all of them, we can
2890 // never do anything with this instruction pattern: report it to the user.
2891 if (!I->InferAllTypes())
2892 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002893
Craig Topper0d1fb902015-03-10 03:25:04 +00002894 // InstInputs - Keep track of all of the inputs of the instruction, along
2895 // with the record they are declared as.
2896 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002897
Craig Topper0d1fb902015-03-10 03:25:04 +00002898 // InstResults - Keep track of all the virtual registers that are 'set'
2899 // in the instruction, including what reg class they are.
2900 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002901
Craig Topper0d1fb902015-03-10 03:25:04 +00002902 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002903
Craig Topper0d1fb902015-03-10 03:25:04 +00002904 // Verify that the top-level forms in the instruction are of void type, and
2905 // fill in the InstResults map.
2906 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2907 TreePatternNode *Pat = I->getTree(j);
2908 if (Pat->getNumTypes() != 0)
2909 I->error("Top-level forms in instruction pattern should have"
2910 " void types");
Chris Lattner8cab0212008-01-05 22:25:12 +00002911
Craig Topper0d1fb902015-03-10 03:25:04 +00002912 // Find inputs and outputs, and verify the structure of the uses/defs.
2913 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2914 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002915 }
2916
Craig Topper0d1fb902015-03-10 03:25:04 +00002917 // Now that we have inputs and outputs of the pattern, inspect the operands
2918 // list for the instruction. This determines the order that operands are
2919 // added to the machine instruction the node corresponds to.
2920 unsigned NumResults = InstResults.size();
2921
2922 // Parse the operands list from the (ops) list, validating it.
2923 assert(I->getArgList().empty() && "Args list should still be empty here!");
2924
2925 // Check that all of the results occur first in the list.
2926 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00002927 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00002928 for (unsigned i = 0; i != NumResults; ++i) {
2929 if (i == CGI.Operands.size())
2930 I->error("'" + InstResults.begin()->first +
2931 "' set but does not appear in operand list!");
2932 const std::string &OpName = CGI.Operands[i].Name;
2933
2934 // Check that it exists in InstResults.
2935 TreePatternNode *RNode = InstResults[OpName];
2936 if (!RNode)
2937 I->error("Operand $" + OpName + " does not exist in operand list!");
2938
Craig Topper3a8eb892015-03-20 05:09:06 +00002939 ResNodes.push_back(RNode);
2940
Craig Topper0d1fb902015-03-10 03:25:04 +00002941 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2942 if (!R)
2943 I->error("Operand $" + OpName + " should be a set destination: all "
2944 "outputs must occur before inputs in operand list!");
2945
2946 if (!checkOperandClass(CGI.Operands[i], R))
2947 I->error("Operand $" + OpName + " class mismatch!");
2948
2949 // Remember the return type.
2950 Results.push_back(CGI.Operands[i].Rec);
2951
2952 // Okay, this one checks out.
2953 InstResults.erase(OpName);
2954 }
2955
2956 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2957 // the copy while we're checking the inputs.
2958 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2959
2960 std::vector<TreePatternNode*> ResultNodeOperands;
2961 std::vector<Record*> Operands;
2962 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2963 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2964 const std::string &OpName = Op.Name;
2965 if (OpName.empty())
2966 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2967
2968 if (!InstInputsCheck.count(OpName)) {
2969 // If this is an operand with a DefaultOps set filled in, we can ignore
2970 // this. When we codegen it, we will do so as always executed.
2971 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2972 // Does it have a non-empty DefaultOps field? If so, ignore this
2973 // operand.
2974 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2975 continue;
2976 }
2977 I->error("Operand $" + OpName +
2978 " does not appear in the instruction pattern");
2979 }
2980 TreePatternNode *InVal = InstInputsCheck[OpName];
2981 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2982
2983 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2984 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2985 if (!checkOperandClass(Op, InRec))
2986 I->error("Operand $" + OpName + "'s register class disagrees"
2987 " between the operand and pattern");
2988 }
2989 Operands.push_back(Op.Rec);
2990
2991 // Construct the result for the dest-pattern operand list.
2992 TreePatternNode *OpNode = InVal->clone();
2993
2994 // No predicate is useful on the result.
2995 OpNode->clearPredicateFns();
2996
2997 // Promote the xform function to be an explicit node if set.
2998 if (Record *Xform = OpNode->getTransformFn()) {
2999 OpNode->setTransformFn(nullptr);
3000 std::vector<TreePatternNode*> Children;
3001 Children.push_back(OpNode);
3002 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3003 }
3004
3005 ResultNodeOperands.push_back(OpNode);
3006 }
3007
3008 if (!InstInputsCheck.empty())
3009 I->error("Input operand $" + InstInputsCheck.begin()->first +
3010 " occurs in pattern but not in operands list!");
3011
3012 TreePatternNode *ResultPattern =
3013 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3014 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003015 // Copy fully inferred output node types to instruction result pattern.
3016 for (unsigned i = 0; i != NumResults; ++i) {
3017 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3018 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3019 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003020
3021 // Create and insert the instruction.
3022 // FIXME: InstImpResults should not be part of DAGInstruction.
3023 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3024 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3025
3026 // Use a temporary tree pattern to infer all types and make sure that the
3027 // constructed result is correct. This depends on the instruction already
3028 // being inserted into the DAGInsts map.
3029 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3030 Temp.InferAllTypes(&I->getNamedNodesMap());
3031
3032 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3033 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3034
3035 return TheInsertedInst;
3036}
3037
Ahmed Bougacha14107512013-10-28 18:07:21 +00003038/// ParseInstructions - Parse all of the instructions, inlining and resolving
3039/// any fragments involved. This populates the Instructions list with fully
3040/// resolved instructions.
3041void CodeGenDAGPatterns::ParseInstructions() {
3042 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3043
Craig Topper306cb122015-11-22 20:46:24 +00003044 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003045 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003046
Craig Topper306cb122015-11-22 20:46:24 +00003047 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3048 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003049
3050 // If there is no pattern, only collect minimal information about the
3051 // instruction for its operand list. We have to assume that there is one
3052 // result, as we have no detailed info. A pattern which references the
3053 // null_frag operator is as-if no pattern were specified. Normally this
3054 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3055 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003056 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003057 std::vector<Record*> Results;
3058 std::vector<Record*> Operands;
3059
Craig Topper306cb122015-11-22 20:46:24 +00003060 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003061
3062 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003063 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3064 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003065
Craig Topper3a8eb892015-03-20 05:09:06 +00003066 // The rest are inputs.
3067 for (unsigned j = InstInfo.Operands.NumDefs,
3068 e = InstInfo.Operands.size(); j < e; ++j)
3069 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003070 }
3071
3072 // Create and insert the instruction.
3073 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003074 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003075 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003076 continue; // no pattern.
3077 }
3078
Craig Topper306cb122015-11-22 20:46:24 +00003079 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003080 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3081
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003082 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003083 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003084 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003085
Chris Lattner8cab0212008-01-05 22:25:12 +00003086 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003087 for (auto &Entry : Instructions) {
3088 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003089 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003090 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003091
3092 // FIXME: Assume only the first tree is the pattern. The others are clobber
3093 // nodes.
3094 TreePatternNode *Pattern = I->getTree(0);
3095 TreePatternNode *SrcPattern;
3096 if (Pattern->getOperator()->getName() == "set") {
3097 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3098 } else{
3099 // Not a set (store or something?)
3100 SrcPattern = Pattern;
3101 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003102
Craig Topper306cb122015-11-22 20:46:24 +00003103 Record *Instr = Entry.first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003104 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003105 PatternToMatch(Instr,
3106 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003107 SrcPattern,
3108 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003109 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003110 Instr->getValueAsInt("AddedComplexity"),
3111 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003112 }
3113}
3114
Chris Lattnera7722b62010-02-23 06:55:24 +00003115
3116typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3117
Jim Grosbach65586fe2010-12-21 16:16:00 +00003118static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003119 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003120 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003121 if (!P->getName().empty()) {
3122 NameRecord &Rec = Names[P->getName()];
3123 // If this is the first instance of the name, remember the node.
3124 if (Rec.second++ == 0)
3125 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003126 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003127 PatternTop->error("repetition of value: $" + P->getName() +
3128 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003129 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003130
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003131 if (!P->isLeaf()) {
3132 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003133 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003134 }
3135}
3136
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003137void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003138 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003139 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003140 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003141 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3142 PrintWarning(Pattern->getRecord()->getLoc(),
3143 Twine("Pattern can never match: ") + Reason);
3144 return;
3145 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003146
Chris Lattner1e634e32010-03-01 22:29:19 +00003147 // If the source pattern's root is a complex pattern, that complex pattern
3148 // must specify the nodes it can potentially match.
3149 if (const ComplexPattern *CP =
3150 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3151 if (CP->getRootNodes().empty())
3152 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3153 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003154
3155
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003156 // Find all of the named values in the input and output, ensure they have the
3157 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003158 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003159 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3160 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003161
3162 // Scan all of the named values in the destination pattern, rejecting them if
3163 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003164 for (const auto &Entry : DstNames) {
3165 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003166 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003167 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003168 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003169
Chris Lattnera7722b62010-02-23 06:55:24 +00003170 // Scan all of the named values in the source pattern, rejecting them if the
3171 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003172 for (const auto &Entry : SrcNames)
3173 if (DstNames[Entry.first].first == nullptr &&
3174 SrcNames[Entry.first].second == 1)
3175 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003176
Chris Lattner0c0baa92010-02-23 06:16:51 +00003177 PatternsToMatch.push_back(PTM);
3178}
3179
3180
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003181
3182void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003183 const std::vector<const CodeGenInstruction*> &Instructions =
3184 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003185
3186 // First try to infer flags from the primary instruction pattern, if any.
3187 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003188 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003189 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3190 CodeGenInstruction &InstInfo =
3191 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003192
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003193 // Get the primary instruction pattern.
3194 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3195 if (!Pattern) {
3196 if (InstInfo.hasUndefFlags())
3197 Revisit.push_back(&InstInfo);
3198 continue;
3199 }
3200 InstAnalyzer PatInfo(*this);
3201 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003202 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003203 }
3204
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003205 // Second, look for single-instruction patterns defined outside the
3206 // instruction.
3207 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3208 const PatternToMatch &PTM = *I;
3209
3210 // We can only infer from single-instruction patterns, otherwise we won't
3211 // know which instruction should get the flags.
3212 SmallVector<Record*, 8> PatInstrs;
3213 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3214 if (PatInstrs.size() != 1)
3215 continue;
3216
3217 // Get the single instruction.
3218 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3219
3220 // Only infer properties from the first pattern. We'll verify the others.
3221 if (InstInfo.InferredFrom)
3222 continue;
3223
3224 InstAnalyzer PatInfo(*this);
3225 PatInfo.Analyze(&PTM);
3226 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3227 }
3228
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003229 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003230 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003231
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003232 // Revisit instructions with undefined flags and no pattern.
3233 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003234 for (CodeGenInstruction *InstInfo : Revisit) {
3235 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003236 continue;
3237 // The mayLoad and mayStore flags default to false.
3238 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003239 if (InstInfo->hasSideEffects_Unset)
3240 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003241 }
3242 return;
3243 }
3244
3245 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003246 for (CodeGenInstruction *InstInfo : Revisit) {
3247 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003248 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003249 if (InstInfo->hasSideEffects_Unset)
3250 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003251 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003252 if (InstInfo->mayStore_Unset)
3253 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003254 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003255 if (InstInfo->mayLoad_Unset)
3256 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003257 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003258 }
3259}
3260
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003261
3262/// Verify instruction flags against pattern node properties.
3263void CodeGenDAGPatterns::VerifyInstructionFlags() {
3264 unsigned Errors = 0;
3265 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3266 const PatternToMatch &PTM = *I;
3267 SmallVector<Record*, 8> Instrs;
3268 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3269 if (Instrs.empty())
3270 continue;
3271
3272 // Count the number of instructions with each flag set.
3273 unsigned NumSideEffects = 0;
3274 unsigned NumStores = 0;
3275 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003276 for (const Record *Instr : Instrs) {
3277 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003278 NumSideEffects += InstInfo.hasSideEffects;
3279 NumStores += InstInfo.mayStore;
3280 NumLoads += InstInfo.mayLoad;
3281 }
3282
3283 // Analyze the source pattern.
3284 InstAnalyzer PatInfo(*this);
3285 PatInfo.Analyze(&PTM);
3286
3287 // Collect error messages.
3288 SmallVector<std::string, 4> Msgs;
3289
3290 // Check for missing flags in the output.
3291 // Permit extra flags for now at least.
3292 if (PatInfo.hasSideEffects && !NumSideEffects)
3293 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3294
3295 // Don't verify store flags on instructions with side effects. At least for
3296 // intrinsics, side effects implies mayStore.
3297 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3298 Msgs.push_back("pattern may store, but mayStore isn't set");
3299
3300 // Similarly, mayStore implies mayLoad on intrinsics.
3301 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3302 Msgs.push_back("pattern may load, but mayLoad isn't set");
3303
3304 // Print error messages.
3305 if (Msgs.empty())
3306 continue;
3307 ++Errors;
3308
Craig Topper306cb122015-11-22 20:46:24 +00003309 for (const std::string &Msg : Msgs)
3310 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003311 (Instrs.size() == 1 ?
3312 "instruction" : "output instructions"));
3313 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003314 for (const Record *Instr : Instrs) {
3315 if (Instr != PTM.getSrcRecord())
3316 PrintError(Instr->getLoc(), "defined here");
3317 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003318 if (InstInfo.InferredFrom &&
3319 InstInfo.InferredFrom != InstInfo.TheDef &&
3320 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003321 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003322 }
3323 }
3324 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003325 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003326}
3327
Chris Lattnercabe0372010-03-15 06:00:16 +00003328/// Given a pattern result with an unresolved type, see if we can find one
3329/// instruction with an unresolved result type. Force this result type to an
3330/// arbitrary element if it's possible types to converge results.
3331static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3332 if (N->isLeaf())
3333 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003334
Chris Lattnercabe0372010-03-15 06:00:16 +00003335 // Analyze children.
3336 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3337 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3338 return true;
3339
3340 if (!N->getOperator()->isSubClassOf("Instruction"))
3341 return false;
3342
3343 // If this type is already concrete or completely unknown we can't do
3344 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003345 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3346 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3347 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003348
Chris Lattnerf1447252010-03-19 21:37:09 +00003349 // Otherwise, force its type to the first possibility (an arbitrary choice).
3350 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3351 return true;
3352 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003353
Chris Lattnerf1447252010-03-19 21:37:09 +00003354 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003355}
3356
Chris Lattnerab3242f2008-01-06 01:10:31 +00003357void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003358 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3359
Craig Topper306cb122015-11-22 20:46:24 +00003360 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003361 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003362
3363 // If the pattern references the null_frag, there's nothing to do.
3364 if (hasNullFragReference(Tree))
3365 continue;
3366
Chris Lattner5c2182e2010-03-27 02:53:27 +00003367 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003368
3369 // Inline pattern fragments into it.
3370 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003371
David Greeneaf8ee2c2011-07-29 22:43:06 +00003372 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003373 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003374
Chris Lattner8cab0212008-01-05 22:25:12 +00003375 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003376 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003377
Chris Lattner8cab0212008-01-05 22:25:12 +00003378 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003379 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003380
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003381 if (Result.getNumTrees() != 1)
3382 Result.error("Cannot handle instructions producing instructions "
3383 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003384
Chris Lattner8cab0212008-01-05 22:25:12 +00003385 bool IterateInference;
3386 bool InferredAllPatternTypes, InferredAllResultTypes;
3387 do {
3388 // Infer as many types as possible. If we cannot infer all of them, we
3389 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003390 InferredAllPatternTypes =
3391 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003392
Chris Lattner8cab0212008-01-05 22:25:12 +00003393 // Infer as many types as possible. If we cannot infer all of them, we
3394 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003395 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003396 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003397
Chris Lattnerfdc20712010-03-18 23:15:10 +00003398 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003399
Chris Lattner8cab0212008-01-05 22:25:12 +00003400 // Apply the type of the result to the source pattern. This helps us
3401 // resolve cases where the input type is known to be a pointer type (which
3402 // is considered resolved), but the result knows it needs to be 32- or
3403 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003404 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003405 Pattern->getTree(0)->getNumTypes());
3406 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003407 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3408 i, Result.getTree(0)->getExtType(i), Result);
3409 IterateInference |= Result.getTree(0)->UpdateNodeType(
3410 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003411 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003412
Chris Lattnercabe0372010-03-15 06:00:16 +00003413 // If our iteration has converged and the input pattern's types are fully
3414 // resolved but the result pattern is not fully resolved, we may have a
3415 // situation where we have two instructions in the result pattern and
3416 // the instructions require a common register class, but don't care about
3417 // what actual MVT is used. This is actually a bug in our modelling:
3418 // output patterns should have register classes, not MVTs.
3419 //
3420 // In any case, to handle this, we just go through and disambiguate some
3421 // arbitrary types to the result pattern's nodes.
3422 if (!IterateInference && InferredAllPatternTypes &&
3423 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003424 IterateInference =
3425 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003426 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003427
Chris Lattner8cab0212008-01-05 22:25:12 +00003428 // Verify that we inferred enough types that we can do something with the
3429 // pattern and result. If these fire the user has to add type casts.
3430 if (!InferredAllPatternTypes)
3431 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003432 if (!InferredAllResultTypes) {
3433 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003434 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003435 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003436
Chris Lattner8cab0212008-01-05 22:25:12 +00003437 // Validate that the input pattern is correct.
3438 std::map<std::string, TreePatternNode*> InstInputs;
3439 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003440 std::vector<Record*> InstImpResults;
3441 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3442 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3443 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003444 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003445
3446 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003447 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003448 std::vector<TreePatternNode*> ResultNodeOperands;
3449 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3450 TreePatternNode *OpNode = DstPattern->getChild(ii);
3451 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003452 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003453 std::vector<TreePatternNode*> Children;
3454 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003455 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003456 }
3457 ResultNodeOperands.push_back(OpNode);
3458 }
David Blaikiecf195302014-11-17 22:55:41 +00003459 DstPattern = Result.getOnlyTree();
3460 if (!DstPattern->isLeaf())
3461 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3462 ResultNodeOperands,
3463 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003464
David Blaikiecf195302014-11-17 22:55:41 +00003465 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3466 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3467
3468 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003469 Temp.InferAllTypes();
3470
Jim Grosbach65586fe2010-12-21 16:16:00 +00003471
Chris Lattner0c0baa92010-02-23 06:16:51 +00003472 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003473 PatternToMatch(CurPattern,
3474 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003475 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003476 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003477 CurPattern->getValueAsInt("AddedComplexity"),
3478 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003479 }
3480}
3481
3482/// CombineChildVariants - Given a bunch of permutations of each child of the
3483/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003484static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003485 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3486 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003487 CodeGenDAGPatterns &CDP,
3488 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003489 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003490 for (const auto &Variants : ChildVariants)
3491 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003492 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003493
Chris Lattner8cab0212008-01-05 22:25:12 +00003494 // The end result is an all-pairs construction of the resultant pattern.
3495 std::vector<unsigned> Idxs;
3496 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003497 bool NotDone;
3498 do {
3499#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003500 DEBUG(if (!Idxs.empty()) {
3501 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003502 for (unsigned Idx : Idxs) {
3503 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003504 }
3505 errs() << "]\n";
3506 });
Scott Michel94420742008-03-05 17:49:05 +00003507#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003508 // Create the variant and add it to the output list.
3509 std::vector<TreePatternNode*> NewChildren;
3510 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3511 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003512 auto R = llvm::make_unique<TreePatternNode>(
3513 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003514
Chris Lattner8cab0212008-01-05 22:25:12 +00003515 // Copy over properties.
3516 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003517 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003518 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003519 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3520 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003521
Scott Michel94420742008-03-05 17:49:05 +00003522 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003523 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003524 // Scan to see if this pattern has already been emitted. We can get
3525 // duplication due to things like commuting:
3526 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3527 // which are the same pattern. Ignore the dups.
3528 if (R->canPatternMatch(ErrString, CDP) &&
3529 std::none_of(OutVariants.begin(), OutVariants.end(),
3530 [&](TreePatternNode *Variant) {
3531 return R->isIsomorphicTo(Variant, DepVars);
3532 }))
3533 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003534
Scott Michel94420742008-03-05 17:49:05 +00003535 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003536 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003537 // [0, 0], [0, 1], [1, 0], [1, 1].
3538 int IdxsIdx;
3539 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3540 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3541 Idxs[IdxsIdx] = 0;
3542 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003543 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003544 }
Scott Michel94420742008-03-05 17:49:05 +00003545 NotDone = (IdxsIdx >= 0);
3546 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003547}
3548
3549/// CombineChildVariants - A helper function for binary operators.
3550///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003551static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003552 const std::vector<TreePatternNode*> &LHS,
3553 const std::vector<TreePatternNode*> &RHS,
3554 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003555 CodeGenDAGPatterns &CDP,
3556 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003557 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3558 ChildVariants.push_back(LHS);
3559 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003560 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003561}
Chris Lattner8cab0212008-01-05 22:25:12 +00003562
3563
3564static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3565 std::vector<TreePatternNode *> &Children) {
3566 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3567 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003568
Chris Lattner8cab0212008-01-05 22:25:12 +00003569 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003570 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003571 N->getTransformFn()) {
3572 Children.push_back(N);
3573 return;
3574 }
3575
3576 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3577 Children.push_back(N->getChild(0));
3578 else
3579 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3580
3581 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3582 Children.push_back(N->getChild(1));
3583 else
3584 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3585}
3586
3587/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3588/// the (potentially recursive) pattern by using algebraic laws.
3589///
3590static void GenerateVariantsOf(TreePatternNode *N,
3591 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003592 CodeGenDAGPatterns &CDP,
3593 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003594 // We cannot permute leaves or ComplexPattern uses.
3595 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003596 OutVariants.push_back(N);
3597 return;
3598 }
3599
3600 // Look up interesting info about the node.
3601 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3602
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003603 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003604 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003605 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003606 std::vector<TreePatternNode*> MaximalChildren;
3607 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3608
3609 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3610 // permutations.
3611 if (MaximalChildren.size() == 3) {
3612 // Find the variants of all of our maximal children.
3613 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003614 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3615 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3616 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003617
Chris Lattner8cab0212008-01-05 22:25:12 +00003618 // There are only two ways we can permute the tree:
3619 // (A op B) op C and A op (B op C)
3620 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003621
Chris Lattner8cab0212008-01-05 22:25:12 +00003622 // Generate legal pair permutations of A/B/C.
3623 std::vector<TreePatternNode*> ABVariants;
3624 std::vector<TreePatternNode*> BAVariants;
3625 std::vector<TreePatternNode*> ACVariants;
3626 std::vector<TreePatternNode*> CAVariants;
3627 std::vector<TreePatternNode*> BCVariants;
3628 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003629 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3630 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3631 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3632 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3633 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3634 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003635
3636 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003637 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3638 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3639 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3640 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3641 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3642 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003643
3644 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003645 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3646 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3647 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3648 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3649 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3650 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003651 return;
3652 }
3653 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003654
Chris Lattner8cab0212008-01-05 22:25:12 +00003655 // Compute permutations of all children.
3656 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3657 ChildVariants.resize(N->getNumChildren());
3658 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003659 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003660
3661 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003662 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003663
3664 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003665 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3666 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3667 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3668 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003669 // Don't count children which are actually register references.
3670 unsigned NC = 0;
3671 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3672 TreePatternNode *Child = N->getChild(i);
3673 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003674 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003675 Record *RR = DI->getDef();
3676 if (RR->isSubClassOf("Register"))
3677 continue;
3678 }
3679 NC++;
3680 }
3681 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003682 if (isCommIntrinsic) {
3683 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3684 // operands are the commutative operands, and there might be more operands
3685 // after those.
3686 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003687 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00003688 std::vector<std::vector<TreePatternNode*> > Variants;
3689 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3690 Variants.push_back(ChildVariants[2]);
3691 Variants.push_back(ChildVariants[1]);
3692 for (unsigned i = 3; i != NC; ++i)
3693 Variants.push_back(ChildVariants[i]);
3694 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3695 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003696 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003697 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003698 }
3699}
3700
3701
3702// GenerateVariants - Generate variants. For example, commutative patterns can
3703// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003704void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003705 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003706
Chris Lattner8cab0212008-01-05 22:25:12 +00003707 // Loop over all of the patterns we've collected, checking to see if we can
3708 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003709 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003710 // the .td file having to contain tons of variants of instructions.
3711 //
3712 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3713 // intentionally do not reconsider these. Any variants of added patterns have
3714 // already been added.
3715 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00003716 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003717 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003718 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003719 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003720 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003721 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003722 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00003723 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003724 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003725
3726 assert(!Variants.empty() && "Must create at least original variant!");
3727 Variants.erase(Variants.begin()); // Remove the original pattern.
3728
3729 if (Variants.empty()) // No variants for this pattern.
3730 continue;
3731
Chris Lattner34822f62009-08-23 04:44:11 +00003732 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00003733 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00003734 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003735
3736 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3737 TreePatternNode *Variant = Variants[v];
3738
Chris Lattner34822f62009-08-23 04:44:11 +00003739 DEBUG(errs() << " VAR#" << v << ": ";
3740 Variant->dump();
3741 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003742
Chris Lattner8cab0212008-01-05 22:25:12 +00003743 // Scan to see if an instruction or explicit pattern already matches this.
3744 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003745 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003746 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003747 if (PatternsToMatch[i].getPredicates() !=
3748 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00003749 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003750 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003751 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3752 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003753 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003754 AlreadyExists = true;
3755 break;
3756 }
3757 }
3758 // If we already have it, ignore the variant.
3759 if (AlreadyExists) continue;
3760
3761 // Otherwise, add it to the list of patterns we have.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003762 PatternsToMatch.emplace_back(
3763 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3764 Variant, PatternsToMatch[i].getDstPattern(),
3765 PatternsToMatch[i].getDstRegs(),
3766 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
Chris Lattner8cab0212008-01-05 22:25:12 +00003767 }
3768
Chris Lattner34822f62009-08-23 04:44:11 +00003769 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003770 }
3771}