blob: 7d020a02104c2c79ae4b9cb2cc88f02e47919e18 [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) {
197 TypeVec.resize(1);
198 TypeVec[0] = InVT.TypeVec[0];
199 MadeChange = true;
200 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000201
Chris Lattnercabe0372010-03-15 06:00:16 +0000202 return MadeChange;
203 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000204
Chris Lattnercabe0372010-03-15 06:00:16 +0000205 // If this is a type list and the RHS is a typelist as well, eliminate entries
206 // from this list that aren't in the other one.
207 bool MadeChange = false;
208 TypeSet InputSet(*this);
209
210 for (unsigned i = 0; i != TypeVec.size(); ++i) {
Craig Toppercbdc27e2015-11-22 19:27:02 +0000211 if (std::find(InVT.TypeVec.begin(), InVT.TypeVec.end(), TypeVec[i]) !=
212 InVT.TypeVec.end())
213 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000214
Chris Lattnercabe0372010-03-15 06:00:16 +0000215 TypeVec.erase(TypeVec.begin()+i--);
216 MadeChange = true;
217 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000218
Chris Lattnercabe0372010-03-15 06:00:16 +0000219 // If we removed all of our types, we have a type contradiction.
220 if (!TypeVec.empty())
221 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000222
Chris Lattnercabe0372010-03-15 06:00:16 +0000223 // FIXME: Really want an SMLoc here!
224 TP.error("Type inference contradiction found, merging '" +
225 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000226 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000227}
228
229/// EnforceInteger - Remove all non-integer types from this set.
230bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000231 if (TP.hasError())
232 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000233 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000234 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000235 return FillWithPossibleTypes(TP, isInteger, "integer");
Craig Topperd2177de2015-11-23 07:19:08 +0000236
Chris Lattnercabe0372010-03-15 06:00:16 +0000237 if (!hasFloatingPointTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000238 return false;
239
240 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000241
Chris Lattnercabe0372010-03-15 06:00:16 +0000242 // Filter out all the fp types.
243 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000244 if (!isInteger(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000245 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000246
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000247 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000248 TP.error("Type inference contradiction found, '" +
249 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000250 return false;
251 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000252 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000253}
254
255/// EnforceFloatingPoint - Remove all integer types from this set.
256bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000257 if (TP.hasError())
258 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000259 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000260 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000261 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
262
Chris Lattnercabe0372010-03-15 06:00:16 +0000263 if (!hasIntegerTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000264 return false;
265
266 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000267
Chris Lattnercabe0372010-03-15 06:00:16 +0000268 // Filter out all the fp types.
269 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000270 if (!isFloatingPoint(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000271 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000272
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000273 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000274 TP.error("Type inference contradiction found, '" +
275 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000276 return false;
277 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000278 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000279}
280
281/// EnforceScalar - Remove all vector types from this.
282bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000283 if (TP.hasError())
284 return false;
285
Chris Lattnercabe0372010-03-15 06:00:16 +0000286 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000287 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000288 return FillWithPossibleTypes(TP, isScalar, "scalar");
289
Chris Lattnercabe0372010-03-15 06:00:16 +0000290 if (!hasVectorTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000291 return false;
292
293 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000294
Chris Lattnercabe0372010-03-15 06:00:16 +0000295 // Filter out all the vector types.
296 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000297 if (!isScalar(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000298 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000299
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000300 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000301 TP.error("Type inference contradiction found, '" +
302 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000303 return false;
304 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000305 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000306}
307
308/// EnforceVector - Remove all vector types from this.
309bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000310 if (TP.hasError())
311 return false;
312
Chris Lattner6d765eb2010-03-19 17:41:26 +0000313 // If we know nothing, then get the full set.
314 if (TypeVec.empty())
315 return FillWithPossibleTypes(TP, isVector, "vector");
316
Chris Lattnercabe0372010-03-15 06:00:16 +0000317 TypeSet InputSet(*this);
318 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000319
Chris Lattnercabe0372010-03-15 06:00:16 +0000320 // Filter out all the scalar types.
321 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000322 if (!isVector(TypeVec[i])) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000323 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner6d765eb2010-03-19 17:41:26 +0000324 MadeChange = true;
325 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000326
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000327 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000328 TP.error("Type inference contradiction found, '" +
329 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000330 return false;
331 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000332 return MadeChange;
333}
334
335
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000336
Craig Topper74169dc2014-01-28 04:49:01 +0000337/// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000338/// this should be based on the element type. Update this and other based on
Craig Topper74169dc2014-01-28 04:49:01 +0000339/// this information.
Chris Lattnercabe0372010-03-15 06:00:16 +0000340bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000341 if (TP.hasError())
342 return false;
343
Chris Lattnercabe0372010-03-15 06:00:16 +0000344 // Both operands must be integer or FP, but we don't care which.
345 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000346
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000347 if (isCompletelyUnknown())
348 MadeChange = FillWithPossibleTypes(TP);
349
350 if (Other.isCompletelyUnknown())
351 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000352
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000353 // If one side is known to be integer or known to be FP but the other side has
354 // no information, get at least the type integrality info in there.
355 if (!hasFloatingPointTypes())
356 MadeChange |= Other.EnforceInteger(TP);
357 else if (!hasIntegerTypes())
358 MadeChange |= Other.EnforceFloatingPoint(TP);
359 if (!Other.hasFloatingPointTypes())
360 MadeChange |= EnforceInteger(TP);
361 else if (!Other.hasIntegerTypes())
362 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000363
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000364 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
365 "Should have a type list now");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000366
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000367 // If one contains vectors but the other doesn't pull vectors out.
368 if (!hasVectorTypes())
369 MadeChange |= Other.EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000370 else if (!hasScalarTypes())
371 MadeChange |= Other.EnforceVector(TP);
Craig Topper6dbcb942014-01-25 05:17:38 +0000372 if (!Other.hasVectorTypes())
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000373 MadeChange |= EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000374 else if (!Other.hasScalarTypes())
375 MadeChange |= EnforceVector(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000376
Craig Topper74169dc2014-01-28 04:49:01 +0000377 // This code does not currently handle nodes which have multiple types,
378 // where some types are integer, and some are fp. Assert that this is not
379 // the case.
380 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
381 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
382 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
383
384 if (TP.hasError())
385 return false;
386
Craig Topper7bbd37b2015-03-10 03:25:07 +0000387 // Okay, find the smallest type from current set and remove anything the
388 // same or smaller from the other set. We need to ensure that the scalar
389 // type size is smaller than the scalar size of the smallest type. For
390 // vectors, we also need to make sure that the total size is no larger than
391 // the size of the smallest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000392 TypeSet InputSet(Other);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000393 MVT Smallest = TypeVec[0];
Craig Topper74169dc2014-01-28 04:49:01 +0000394 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000395 MVT OtherVT = Other.TypeVec[i];
396 // Don't compare vector and non-vector types.
397 if (OtherVT.isVector() != Smallest.isVector())
398 continue;
399 // The getSizeInBits() check here is only needed for vectors, but is
400 // a subset of the scalar check for scalars so no need to qualify.
401 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
402 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000403 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
404 MadeChange = true;
405 }
406 }
407
408 if (Other.TypeVec.empty()) {
409 TP.error("Type inference contradiction found, '" + InputSet.getName() +
410 "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000411 return false;
412 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000413
Craig Topper7bbd37b2015-03-10 03:25:07 +0000414 // Okay, find the largest type from the other set and remove anything the
415 // same or smaller from the current set. We need to ensure that the scalar
416 // type size is larger than the scalar size of the largest type. For
417 // vectors, we also need to make sure that the total size is no smaller than
418 // the size of the largest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000419 InputSet = TypeSet(*this);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000420 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
Craig Topper74169dc2014-01-28 04:49:01 +0000421 for (unsigned i = 0; i != TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000422 MVT OtherVT = TypeVec[i];
423 // Don't compare vector and non-vector types.
424 if (OtherVT.isVector() != Largest.isVector())
425 continue;
426 // The getSizeInBits() check here is only needed for vectors, but is
427 // a subset of the scalar check for scalars so no need to qualify.
428 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
429 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000430 TypeVec.erase(TypeVec.begin()+i--);
431 MadeChange = true;
David Greene433c6182011-02-01 19:12:32 +0000432 }
David Greene433c6182011-02-01 19:12:32 +0000433 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000434
Craig Topper74169dc2014-01-28 04:49:01 +0000435 if (TypeVec.empty()) {
436 TP.error("Type inference contradiction found, '" + InputSet.getName() +
437 "' has nothing smaller than '" + Other.getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000438 return false;
439 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000440
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000441 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000442}
443
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000444/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000445/// whose element is specified by VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000446bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
447 TreePattern &TP) {
448 bool MadeChange = false;
449
450 MadeChange |= EnforceVector(TP);
451
452 TypeSet InputSet(*this);
453
454 // Filter out all the types which don't have the right element type.
455 for (unsigned i = 0; i != TypeVec.size(); ++i) {
456 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
457 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
458 TypeVec.erase(TypeVec.begin()+i--);
459 MadeChange = true;
460 }
461 }
462
463 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
464 TP.error("Type inference contradiction found, forcing '" +
465 InputSet.getName() + "' to have a vector element");
466 return false;
467 }
468
469 return MadeChange;
470}
471
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000472/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Craig Topper0be34582015-03-05 07:11:34 +0000473/// whose element is specified by VTOperand.
Chris Lattner57ebf632010-03-24 00:01:16 +0000474bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000475 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000476 if (TP.hasError())
477 return false;
478
Chris Lattner57ebf632010-03-24 00:01:16 +0000479 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000480 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000481 MadeChange |= EnforceVector(TP);
482 MadeChange |= VTOperand.EnforceScalar(TP);
483
484 // If we know the vector type, it forces the scalar to agree.
485 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000486 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000487 IVT = IVT.getVectorElementType();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000488 return MadeChange |
Craig Topper95198f42013-09-25 06:37:18 +0000489 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000490 }
491
492 // If the scalar type is known, filter out vector types whose element types
493 // disagree.
494 if (!VTOperand.isConcrete())
495 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000496
Chris Lattner57ebf632010-03-24 00:01:16 +0000497 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000498
Chris Lattner57ebf632010-03-24 00:01:16 +0000499 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000500
Chris Lattner57ebf632010-03-24 00:01:16 +0000501 // Filter out all the types which don't have the right element type.
502 for (unsigned i = 0; i != TypeVec.size(); ++i) {
503 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
Craig Topper95198f42013-09-25 06:37:18 +0000504 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000505 TypeVec.erase(TypeVec.begin()+i--);
506 MadeChange = true;
507 }
Chris Lattner57ebf632010-03-24 00:01:16 +0000508 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000509
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000510 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattnercabe0372010-03-15 06:00:16 +0000511 TP.error("Type inference contradiction found, forcing '" +
512 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000513 return false;
514 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000515 return MadeChange;
516}
517
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000518/// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
David Greene127fd1d2011-01-24 20:53:18 +0000519/// vector type specified by VTOperand.
520bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
521 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000522 if (TP.hasError())
523 return false;
524
David Greene127fd1d2011-01-24 20:53:18 +0000525 // "This" must be a vector and "VTOperand" must be a vector.
526 bool MadeChange = false;
527 MadeChange |= EnforceVector(TP);
528 MadeChange |= VTOperand.EnforceVector(TP);
529
Craig Topper6e1faaf2014-01-25 17:40:33 +0000530 // If one side is known to be integer or known to be FP but the other side has
531 // no information, get at least the type integrality info in there.
532 if (!hasFloatingPointTypes())
533 MadeChange |= VTOperand.EnforceInteger(TP);
534 else if (!hasIntegerTypes())
535 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
536 if (!VTOperand.hasFloatingPointTypes())
537 MadeChange |= EnforceInteger(TP);
538 else if (!VTOperand.hasIntegerTypes())
539 MadeChange |= EnforceFloatingPoint(TP);
540
541 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
542 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000543
544 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000545 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000546 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000547 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000548 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000549 IVT = IVT.getVectorElementType();
550
Craig Topper95198f42013-09-25 06:37:18 +0000551 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000552 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000553
554 // Only keep types that have less elements than VTOperand.
555 TypeSet InputSet(VTOperand);
556
557 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
558 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
559 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
560 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
561 MadeChange = true;
562 }
563 }
564 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
565 TP.error("Type inference contradiction found, forcing '" +
566 InputSet.getName() + "' to have less vector elements than '" +
567 getName() + "'");
568 return false;
569 }
David Greene127fd1d2011-01-24 20:53:18 +0000570 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000571 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000572 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000573 IVT = IVT.getVectorElementType();
574
Craig Topper95198f42013-09-25 06:37:18 +0000575 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000576 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000577
578 // Only keep types that have more elements than 'this'.
579 TypeSet InputSet(*this);
580
581 for (unsigned i = 0; i != TypeVec.size(); ++i) {
582 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
583 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
584 TypeVec.erase(TypeVec.begin()+i--);
585 MadeChange = true;
586 }
587 }
588 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
589 TP.error("Type inference contradiction found, forcing '" +
590 InputSet.getName() + "' to have more vector elements than '" +
591 VTOperand.getName() + "'");
592 return false;
593 }
David Greene127fd1d2011-01-24 20:53:18 +0000594 }
595
596 return MadeChange;
597}
598
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000599/// EnforceVectorSameNumElts - 'this' is now constrained to
Craig Topper0be34582015-03-05 07:11:34 +0000600/// be a vector with same num elements as VTOperand.
601bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
602 TreePattern &TP) {
603 if (TP.hasError())
604 return false;
605
606 // "This" must be a vector and "VTOperand" must be a vector.
607 bool MadeChange = false;
608 MadeChange |= EnforceVector(TP);
609 MadeChange |= VTOperand.EnforceVector(TP);
610
611 // If we know one of the vector types, it forces the other type to agree.
612 if (isConcrete()) {
613 MVT IVT = getConcrete();
614 unsigned NumElems = IVT.getVectorNumElements();
615
616 // Only keep types that have same elements as VTOperand.
617 TypeSet InputSet(VTOperand);
618
619 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
620 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
621 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
622 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
623 MadeChange = true;
624 }
625 }
626 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
627 TP.error("Type inference contradiction found, forcing '" +
628 InputSet.getName() + "' to have same number elements as '" +
629 getName() + "'");
630 return false;
631 }
632 } else if (VTOperand.isConcrete()) {
633 MVT IVT = VTOperand.getConcrete();
634 unsigned NumElems = IVT.getVectorNumElements();
635
636 // Only keep types that have same elements as 'this'.
637 TypeSet InputSet(*this);
638
639 for (unsigned i = 0; i != TypeVec.size(); ++i) {
640 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
641 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
642 TypeVec.erase(TypeVec.begin()+i--);
643 MadeChange = true;
644 }
645 }
646 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
647 TP.error("Type inference contradiction found, forcing '" +
648 InputSet.getName() + "' to have same number elements than '" +
649 VTOperand.getName() + "'");
650 return false;
651 }
652 }
653
654 return MadeChange;
655}
656
Chris Lattnercabe0372010-03-15 06:00:16 +0000657//===----------------------------------------------------------------------===//
658// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000659
Scott Michel94420742008-03-05 17:49:05 +0000660/// Dependent variable map for CodeGenDAGPattern variant generation
661typedef std::map<std::string, int> DepVarMap;
662
Chris Lattner514e2922011-04-17 21:38:24 +0000663static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000664 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000665 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000666 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000667 } else {
668 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
669 FindDepVarsOf(N->getChild(i), DepMap);
670 }
671}
Chris Lattner514e2922011-04-17 21:38:24 +0000672
673/// Find dependent variables within child patterns
674static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000675 DepVarMap depcounts;
676 FindDepVarsOf(N, depcounts);
Craig Topper306cb122015-11-22 20:46:24 +0000677 for (const std::pair<std::string, int> &Pair : depcounts) {
678 if (Pair.second > 1)
679 DepVars.insert(Pair.first);
Scott Michel94420742008-03-05 17:49:05 +0000680 }
681}
682
Daniel Dunbarba66a812010-10-08 02:07:22 +0000683#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000684/// Dump the dependent variable set:
685static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000686 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000687 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000688 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000689 DEBUG(errs() << "[ ");
Craig Topper306cb122015-11-22 20:46:24 +0000690 for (const std::string &DepVar : DepVars) {
691 DEBUG(errs() << DepVar << " ");
Scott Michel94420742008-03-05 17:49:05 +0000692 }
Chris Lattner34822f62009-08-23 04:44:11 +0000693 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000694 }
695}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000696#endif
697
Chris Lattner514e2922011-04-17 21:38:24 +0000698
699//===----------------------------------------------------------------------===//
700// TreePredicateFn Implementation
701//===----------------------------------------------------------------------===//
702
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000703/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
704TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
705 assert((getPredCode().empty() || getImmCode().empty()) &&
706 ".td file corrupt: can't have a node predicate *and* an imm predicate");
707}
708
Chris Lattner514e2922011-04-17 21:38:24 +0000709std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000710 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000711}
712
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000713std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000714 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000715}
716
Chris Lattner514e2922011-04-17 21:38:24 +0000717
718/// isAlwaysTrue - Return true if this is a noop predicate.
719bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000720 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000721}
722
723/// Return the name to use in the generated code to reference this, this is
724/// "Predicate_foo" if from a pattern fragment "foo".
725std::string TreePredicateFn::getFnName() const {
726 return "Predicate_" + PatFragRec->getRecord()->getName();
727}
728
729/// getCodeToRunOnSDNode - Return the code for the function body that
730/// evaluates this predicate. The argument is expected to be in "Node",
731/// not N. This handles casting and conversion to a concrete node type as
732/// appropriate.
733std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000734 // Handle immediate predicates first.
735 std::string ImmCode = getImmCode();
736 if (!ImmCode.empty()) {
737 std::string Result =
738 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000739 return Result + ImmCode;
740 }
741
742 // Handle arbitrary node predicates.
743 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000744 std::string ClassName;
745 if (PatFragRec->getOnlyTree()->isLeaf())
746 ClassName = "SDNode";
747 else {
748 Record *Op = PatFragRec->getOnlyTree()->getOperator();
749 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
750 }
751 std::string Result;
752 if (ClassName == "SDNode")
753 Result = " SDNode *N = Node;\n";
754 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000755 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000756
757 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000758}
759
Chris Lattner8cab0212008-01-05 22:25:12 +0000760//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000761// PatternToMatch implementation
762//
763
Chris Lattner05925fe2010-03-29 01:40:38 +0000764
765/// getPatternSize - Return the 'size' of this pattern. We want to match large
766/// patterns before small ones. This is used to determine the size of a
767/// pattern.
768static unsigned getPatternSize(const TreePatternNode *P,
769 const CodeGenDAGPatterns &CGP) {
770 unsigned Size = 3; // The node itself.
771 // If the root node is a ConstantSDNode, increases its size.
772 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000773 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000774 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000775
Chris Lattner05925fe2010-03-29 01:40:38 +0000776 // FIXME: This is a hack to statically increase the priority of patterns
777 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
778 // Later we can allow complexity / cost for each pattern to be (optionally)
779 // specified. To get best possible pattern match we'll need to dynamically
780 // calculate the complexity of all patterns a dag can potentially map to.
781 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000782 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000783 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000784
Tim Northoverc807a172014-05-20 11:52:46 +0000785 // We don't want to count any children twice, so return early.
786 return Size;
787 }
788
Chris Lattner05925fe2010-03-29 01:40:38 +0000789 // If this node has some predicate function that must match, it adds to the
790 // complexity of this node.
791 if (!P->getPredicateFns().empty())
792 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000793
Chris Lattner05925fe2010-03-29 01:40:38 +0000794 // Count children in the count if they are also nodes.
795 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
796 TreePatternNode *Child = P->getChild(i);
797 if (!Child->isLeaf() && Child->getNumTypes() &&
798 Child->getType(0) != MVT::Other)
799 Size += getPatternSize(Child, CGP);
800 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000801 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000802 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
803 else if (Child->getComplexPatternInfo(CGP))
804 Size += getPatternSize(Child, CGP);
805 else if (!Child->getPredicateFns().empty())
806 ++Size;
807 }
808 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000809
Chris Lattner05925fe2010-03-29 01:40:38 +0000810 return Size;
811}
812
813/// Compute the complexity metric for the input pattern. This roughly
814/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000815int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000816getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
817 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
818}
819
820
Dan Gohman49e19e92008-08-22 00:20:26 +0000821/// getPredicateCheck - Return a single string containing all of this
822/// pattern's predicates concatenated with "&&" operators.
823///
824std::string PatternToMatch::getPredicateCheck() const {
825 std::string PredicateCheck;
Craig Topperef0578a2015-06-02 04:15:51 +0000826 for (Init *I : Predicates->getValues()) {
827 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000828 Record *Def = Pred->getDef();
829 if (!Def->isSubClassOf("Predicate")) {
830#ifndef NDEBUG
831 Def->dump();
832#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000833 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000834 }
835 if (!PredicateCheck.empty())
836 PredicateCheck += " && ";
837 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
838 }
839 }
840
841 return PredicateCheck;
842}
843
844//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000845// SDTypeConstraint implementation
846//
847
848SDTypeConstraint::SDTypeConstraint(Record *R) {
849 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000850
Chris Lattner8cab0212008-01-05 22:25:12 +0000851 if (R->isSubClassOf("SDTCisVT")) {
852 ConstraintType = SDTCisVT;
853 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000854 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000855 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000856
Chris Lattner8cab0212008-01-05 22:25:12 +0000857 } else if (R->isSubClassOf("SDTCisPtrTy")) {
858 ConstraintType = SDTCisPtrTy;
859 } else if (R->isSubClassOf("SDTCisInt")) {
860 ConstraintType = SDTCisInt;
861 } else if (R->isSubClassOf("SDTCisFP")) {
862 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000863 } else if (R->isSubClassOf("SDTCisVec")) {
864 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000865 } else if (R->isSubClassOf("SDTCisSameAs")) {
866 ConstraintType = SDTCisSameAs;
867 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
868 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
869 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000870 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000871 R->getValueAsInt("OtherOperandNum");
872 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
873 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000874 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000875 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000876 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
877 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000878 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000879 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
880 ConstraintType = SDTCisSubVecOfVec;
881 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
882 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000883 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
884 ConstraintType = SDTCVecEltisVT;
885 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
886 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
887 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
888 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
889 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
890 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
891 "as SDTCVecEltisVT");
892 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
893 ConstraintType = SDTCisSameNumEltsAs;
894 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
895 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000896 } else {
James Y Knighte452e272015-05-11 22:17:13 +0000897 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +0000898 }
899}
900
901/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000902/// N, and the result number in ResNo.
903static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
904 const SDNodeInfo &NodeInfo,
905 unsigned &ResNo) {
906 unsigned NumResults = NodeInfo.getNumResults();
907 if (OpNo < NumResults) {
908 ResNo = OpNo;
909 return N;
910 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000911
Chris Lattner2db7aba2010-03-19 21:56:21 +0000912 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000913
Chris Lattner2db7aba2010-03-19 21:56:21 +0000914 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +0000915 std::string S;
916 raw_string_ostream OS(S);
917 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000918 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +0000919 N->print(OS);
920 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +0000921 }
922
Chris Lattner2db7aba2010-03-19 21:56:21 +0000923 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000924}
925
926/// ApplyTypeConstraint - Given a node in a pattern, apply this type
927/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000928/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000929bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
930 const SDNodeInfo &NodeInfo,
931 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000932 if (TP.hasError())
933 return false;
934
Chris Lattner2db7aba2010-03-19 21:56:21 +0000935 unsigned ResNo = 0; // The result number being referenced.
936 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000937
Chris Lattner8cab0212008-01-05 22:25:12 +0000938 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000939 case SDTCisVT:
940 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000941 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000942 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000943 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000944 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000945 case SDTCisInt:
946 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000947 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000948 case SDTCisFP:
949 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000950 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000951 case SDTCisVec:
952 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000953 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000954 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000955 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000956 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000957 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +0000958 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
959 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000960 }
961 case SDTCisVTSmallerThanOp: {
962 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
963 // have an integer type that is smaller than the VT.
964 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +0000965 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +0000966 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000967 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000968 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000969 return false;
970 }
Owen Anderson9f944592009-08-11 20:47:22 +0000971 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +0000972 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000973
Chris Lattner38c99662010-03-24 00:06:46 +0000974 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000975
Chris Lattner2db7aba2010-03-19 21:56:21 +0000976 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000977 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000978 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
979 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +0000980
Chris Lattner38c99662010-03-24 00:06:46 +0000981 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000982 }
983 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000984 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000985 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000986 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
987 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000988 return NodeToApply->getExtType(ResNo).
989 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000990 }
Nate Begeman17bedbc2008-02-09 01:37:05 +0000991 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000992 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +0000993 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000994 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
995 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000996
Chris Lattner57ebf632010-03-24 00:01:16 +0000997 // Filter vector types out of VecOperand that don't have the right element
998 // type.
999 return VecOperand->getExtType(VResNo).
1000 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +00001001 }
David Greene127fd1d2011-01-24 20:53:18 +00001002 case SDTCisSubVecOfVec: {
1003 unsigned VResNo = 0;
1004 TreePatternNode *BigVecOperand =
1005 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1006 VResNo);
1007
1008 // Filter vector types out of BigVecOperand that don't have the
1009 // right subvector type.
1010 return BigVecOperand->getExtType(VResNo).
1011 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1012 }
Craig Topper0be34582015-03-05 07:11:34 +00001013 case SDTCVecEltisVT: {
1014 return NodeToApply->getExtType(ResNo).
1015 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1016 }
1017 case SDTCisSameNumEltsAs: {
1018 unsigned OResNo = 0;
1019 TreePatternNode *OtherNode =
1020 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1021 N, NodeInfo, OResNo);
1022 return OtherNode->getExtType(OResNo).
1023 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1024 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001025 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001026 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001027}
1028
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001029// Update the node type to match an instruction operand or result as specified
1030// in the ins or outs lists on the instruction definition. Return true if the
1031// type was actually changed.
1032bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1033 Record *Operand,
1034 TreePattern &TP) {
1035 // The 'unknown' operand indicates that types should be inferred from the
1036 // context.
1037 if (Operand->isSubClassOf("unknown_class"))
1038 return false;
1039
1040 // The Operand class specifies a type directly.
1041 if (Operand->isSubClassOf("Operand"))
1042 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1043 TP);
1044
1045 // PointerLikeRegClass has a type that is determined at runtime.
1046 if (Operand->isSubClassOf("PointerLikeRegClass"))
1047 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1048
1049 // Both RegisterClass and RegisterOperand operands derive their types from a
1050 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001051 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001052 if (Operand->isSubClassOf("RegisterClass"))
1053 RC = Operand;
1054 else if (Operand->isSubClassOf("RegisterOperand"))
1055 RC = Operand->getValueAsDef("RegClass");
1056
1057 assert(RC && "Unknown operand type");
1058 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1059 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1060}
1061
1062
Chris Lattner8cab0212008-01-05 22:25:12 +00001063//===----------------------------------------------------------------------===//
1064// SDNodeInfo implementation
1065//
1066SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1067 EnumName = R->getValueAsString("Opcode");
1068 SDClassName = R->getValueAsString("SDClass");
1069 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1070 NumResults = TypeProfile->getValueAsInt("NumResults");
1071 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001072
Chris Lattner8cab0212008-01-05 22:25:12 +00001073 // Parse the properties.
1074 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001075 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1076 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001077 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001078 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001079 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001080 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001081 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001082 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001083 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001084 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001085 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001086 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001087 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001088 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001089 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001090 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001091 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001092 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001093 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001094 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001095 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001096 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001097 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001098 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001099 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001100 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001101 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001102 }
1103 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001104
1105
Chris Lattner8cab0212008-01-05 22:25:12 +00001106 // Parse the type constraints.
1107 std::vector<Record*> ConstraintList =
1108 TypeProfile->getValueAsListOfDefs("Constraints");
1109 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1110}
1111
Chris Lattner99e53b32010-02-28 00:22:30 +00001112/// getKnownType - If the type constraints on this node imply a fixed type
1113/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001114/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001115MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001116 unsigned NumResults = getNumResults();
1117 assert(NumResults <= 1 &&
1118 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001119 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001120
Craig Topper306cb122015-11-22 20:46:24 +00001121 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001122 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001123 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001124 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001125
Craig Topper306cb122015-11-22 20:46:24 +00001126 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001127 default: break;
1128 case SDTypeConstraint::SDTCisVT:
Craig Topper306cb122015-11-22 20:46:24 +00001129 return Constraint.x.SDTCisVT_Info.VT;
Chris Lattner99e53b32010-02-28 00:22:30 +00001130 case SDTypeConstraint::SDTCisPtrTy:
1131 return MVT::iPTR;
1132 }
1133 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001134 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001135}
1136
Chris Lattner8cab0212008-01-05 22:25:12 +00001137//===----------------------------------------------------------------------===//
1138// TreePatternNode implementation
1139//
1140
1141TreePatternNode::~TreePatternNode() {
1142#if 0 // FIXME: implement refcounted tree nodes!
1143 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1144 delete getChild(i);
1145#endif
1146}
1147
Chris Lattnerf1447252010-03-19 21:37:09 +00001148static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1149 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001150 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001151 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001152
Chris Lattner2109cb42010-03-22 20:56:36 +00001153 if (Operator->isSubClassOf("Intrinsic"))
1154 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001155
Chris Lattnerf1447252010-03-19 21:37:09 +00001156 if (Operator->isSubClassOf("SDNode"))
1157 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001158
Chris Lattnerf1447252010-03-19 21:37:09 +00001159 if (Operator->isSubClassOf("PatFrag")) {
1160 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1161 // the forward reference case where one pattern fragment references another
1162 // before it is processed.
1163 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1164 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001165
Chris Lattnerf1447252010-03-19 21:37:09 +00001166 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001167 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001168 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001169 if (Tree)
1170 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1171 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001172 assert(Op && "Invalid Fragment");
1173 return GetNumNodeResults(Op, CDP);
1174 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001175
Chris Lattnerf1447252010-03-19 21:37:09 +00001176 if (Operator->isSubClassOf("Instruction")) {
1177 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001178
Craig Topper3a8eb892015-03-20 05:09:06 +00001179 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1180
1181 // Subtract any defaulted outputs.
1182 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1183 Record *OperandNode = InstInfo.Operands[i].Rec;
1184
1185 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1186 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1187 --NumDefsToAdd;
1188 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001189
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001190 // Add on one implicit def if it has a resolvable type.
1191 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1192 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001193 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001194 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001195
Chris Lattnerf1447252010-03-19 21:37:09 +00001196 if (Operator->isSubClassOf("SDNodeXForm"))
1197 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001198
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001199 if (Operator->isSubClassOf("ValueType"))
1200 return 1; // A type-cast of one result.
1201
Tim Northoverc807a172014-05-20 11:52:46 +00001202 if (Operator->isSubClassOf("ComplexPattern"))
1203 return 1;
1204
Chris Lattnerf1447252010-03-19 21:37:09 +00001205 Operator->dump();
James Y Knighte452e272015-05-11 22:17:13 +00001206 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001207}
1208
1209void TreePatternNode::print(raw_ostream &OS) const {
1210 if (isLeaf())
1211 OS << *getLeafValue();
1212 else
1213 OS << '(' << getOperator()->getName();
1214
1215 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1216 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001217
1218 if (!isLeaf()) {
1219 if (getNumChildren() != 0) {
1220 OS << " ";
1221 getChild(0)->print(OS);
1222 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1223 OS << ", ";
1224 getChild(i)->print(OS);
1225 }
1226 }
1227 OS << ")";
1228 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001229
Craig Topper306cb122015-11-22 20:46:24 +00001230 for (const TreePredicateFn &Pred : PredicateFns)
1231 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001232 if (TransformFn)
1233 OS << "<<X:" << TransformFn->getName() << ">>";
1234 if (!getName().empty())
1235 OS << ":$" << getName();
1236
1237}
1238void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001239 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001240}
1241
Scott Michel94420742008-03-05 17:49:05 +00001242/// isIsomorphicTo - Return true if this node is recursively
1243/// isomorphic to the specified node. For this comparison, the node's
1244/// entire state is considered. The assigned name is ignored, since
1245/// nodes with differing names are considered isomorphic. However, if
1246/// the assigned name is present in the dependent variable set, then
1247/// the assigned name is considered significant and the node is
1248/// isomorphic if the names match.
1249bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1250 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001251 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001252 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001253 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001254 getTransformFn() != N->getTransformFn())
1255 return false;
1256
1257 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001258 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1259 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001260 return ((DI->getDef() == NDI->getDef())
1261 && (DepVars.find(getName()) == DepVars.end()
1262 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001263 }
1264 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001265 return getLeafValue() == N->getLeafValue();
1266 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001267
Chris Lattner8cab0212008-01-05 22:25:12 +00001268 if (N->getOperator() != getOperator() ||
1269 N->getNumChildren() != getNumChildren()) return false;
1270 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001271 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001272 return false;
1273 return true;
1274}
1275
1276/// clone - Make a copy of this tree and all of its children.
1277///
1278TreePatternNode *TreePatternNode::clone() const {
1279 TreePatternNode *New;
1280 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001281 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001282 } else {
1283 std::vector<TreePatternNode*> CChildren;
1284 CChildren.reserve(Children.size());
1285 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1286 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001287 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001288 }
1289 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001290 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001291 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001292 New->setTransformFn(getTransformFn());
1293 return New;
1294}
1295
Chris Lattner53c39ba2010-02-14 22:22:58 +00001296/// RemoveAllTypes - Recursively strip all the types of this tree.
1297void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001298 // Reset to unknown type.
1299 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001300 if (isLeaf()) return;
1301 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1302 getChild(i)->RemoveAllTypes();
1303}
1304
1305
Chris Lattner8cab0212008-01-05 22:25:12 +00001306/// SubstituteFormalArguments - Replace the formal arguments in this tree
1307/// with actual values specified by ArgMap.
1308void TreePatternNode::
1309SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1310 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001311
Chris Lattner8cab0212008-01-05 22:25:12 +00001312 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1313 TreePatternNode *Child = getChild(i);
1314 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001315 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001316 // Note that, when substituting into an output pattern, Val might be an
1317 // UnsetInit.
1318 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1319 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001320 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001321 TreePatternNode *NewChild = ArgMap[Child->getName()];
1322 assert(NewChild && "Couldn't find formal argument!");
1323 assert((Child->getPredicateFns().empty() ||
1324 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1325 "Non-empty child predicate clobbered!");
1326 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001327 }
1328 } else {
1329 getChild(i)->SubstituteFormalArguments(ArgMap);
1330 }
1331 }
1332}
1333
1334
1335/// InlinePatternFragments - If this pattern refers to any pattern
1336/// fragments, inline them into place, giving us a pattern without any
1337/// PatFrag references.
1338TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001339 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001340 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001341
1342 if (isLeaf())
1343 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001344 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001345
Chris Lattner8cab0212008-01-05 22:25:12 +00001346 if (!Op->isSubClassOf("PatFrag")) {
1347 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001348 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1349 TreePatternNode *Child = getChild(i);
1350 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1351
1352 assert((Child->getPredicateFns().empty() ||
1353 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1354 "Non-empty child predicate clobbered!");
1355
1356 setChild(i, NewChild);
1357 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001358 return this;
1359 }
1360
1361 // Otherwise, we found a reference to a fragment. First, look up its
1362 // TreePattern record.
1363 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001364
Chris Lattner8cab0212008-01-05 22:25:12 +00001365 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001366 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001367 TP.error("'" + Op->getName() + "' fragment requires " +
1368 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001369 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001370 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001371
1372 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1373
Chris Lattner514e2922011-04-17 21:38:24 +00001374 TreePredicateFn PredFn(Frag);
1375 if (!PredFn.isAlwaysTrue())
1376 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001377
Chris Lattner8cab0212008-01-05 22:25:12 +00001378 // Resolve formal arguments to their actual value.
1379 if (Frag->getNumArgs()) {
1380 // Compute the map of formal to actual arguments.
1381 std::map<std::string, TreePatternNode*> ArgMap;
1382 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1383 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001384
Chris Lattner8cab0212008-01-05 22:25:12 +00001385 FragTree->SubstituteFormalArguments(ArgMap);
1386 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001387
Chris Lattner8cab0212008-01-05 22:25:12 +00001388 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001389 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1390 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001391
1392 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001393 for (const TreePredicateFn &Pred : getPredicateFns())
1394 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001395
Chris Lattner8cab0212008-01-05 22:25:12 +00001396 // Get a new copy of this fragment to stitch into here.
1397 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001398
Chris Lattner2e253b42008-06-30 03:02:03 +00001399 // The fragment we inlined could have recursive inlining that is needed. See
1400 // if there are any pattern fragments in it and inline them as needed.
1401 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001402}
1403
1404/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001405/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001406/// references from the register file information, for example.
1407///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001408/// When Unnamed is set, return the type of a DAG operand with no name, such as
1409/// the F8RC register class argument in:
1410///
1411/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1412///
1413/// When Unnamed is false, return the type of a named DAG operand such as the
1414/// GPR:$src operand above.
1415///
Chris Lattnerf1447252010-03-19 21:37:09 +00001416static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001417 bool NotRegisters,
1418 bool Unnamed,
1419 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001420 // Check to see if this is a register operand.
1421 if (R->isSubClassOf("RegisterOperand")) {
1422 assert(ResNo == 0 && "Regoperand ref only has one result!");
1423 if (NotRegisters)
1424 return EEVT::TypeSet(); // Unknown.
1425 Record *RegClass = R->getValueAsDef("RegClass");
1426 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1427 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1428 }
1429
Chris Lattnercabe0372010-03-15 06:00:16 +00001430 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001431 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001432 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001433 // An unnamed register class represents itself as an i32 immediate, for
1434 // example on a COPY_TO_REGCLASS instruction.
1435 if (Unnamed)
1436 return EEVT::TypeSet(MVT::i32, TP);
1437
1438 // In a named operand, the register class provides the possible set of
1439 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001440 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001441 return EEVT::TypeSet(); // Unknown.
1442 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1443 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001444 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001445
Chris Lattner6070ee22010-03-23 23:50:31 +00001446 if (R->isSubClassOf("PatFrag")) {
1447 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001448 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001449 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001450 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001451
Chris Lattner6070ee22010-03-23 23:50:31 +00001452 if (R->isSubClassOf("Register")) {
1453 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001454 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001455 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001456 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001457 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001458 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001459
1460 if (R->isSubClassOf("SubRegIndex")) {
1461 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001462 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001463 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001464
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001465 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001466 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001467 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1468 //
1469 // (sext_inreg GPR:$src, i16)
1470 // ~~~
1471 if (Unnamed)
1472 return EEVT::TypeSet(MVT::Other, TP);
1473 // With a name, the ValueType simply provides the type of the named
1474 // variable.
1475 //
1476 // (sext_inreg i32:$src, i16)
1477 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001478 if (NotRegisters)
1479 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001480 return EEVT::TypeSet(getValueType(R), TP);
1481 }
1482
1483 if (R->isSubClassOf("CondCode")) {
1484 assert(ResNo == 0 && "This node only has one result!");
1485 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001486 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001487 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001488
Chris Lattner6070ee22010-03-23 23:50:31 +00001489 if (R->isSubClassOf("ComplexPattern")) {
1490 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001491 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001492 return EEVT::TypeSet(); // Unknown.
1493 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1494 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001495 }
1496 if (R->isSubClassOf("PointerLikeRegClass")) {
1497 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001498 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001499 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001500
Chris Lattner6070ee22010-03-23 23:50:31 +00001501 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1502 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001503 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001504 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001505 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001506
Tim Northoverc807a172014-05-20 11:52:46 +00001507 if (R->isSubClassOf("Operand"))
1508 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1509
Chris Lattner8cab0212008-01-05 22:25:12 +00001510 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001511 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001512}
1513
Chris Lattner89c65662008-01-06 05:36:50 +00001514
1515/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1516/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1517const CodeGenIntrinsic *TreePatternNode::
1518getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1519 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1520 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1521 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001522 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001523
Sean Silva88eb8dd2012-10-10 20:24:47 +00001524 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001525 return &CDP.getIntrinsicInfo(IID);
1526}
1527
Chris Lattner53c39ba2010-02-14 22:22:58 +00001528/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1529/// return the ComplexPattern information, otherwise return null.
1530const ComplexPattern *
1531TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001532 Record *Rec;
1533 if (isLeaf()) {
1534 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1535 if (!DI)
1536 return nullptr;
1537 Rec = DI->getDef();
1538 } else
1539 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001540
Tim Northoverc807a172014-05-20 11:52:46 +00001541 if (!Rec->isSubClassOf("ComplexPattern"))
1542 return nullptr;
1543 return &CGP.getComplexPattern(Rec);
1544}
1545
1546unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1547 // A ComplexPattern specifically declares how many results it fills in.
1548 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1549 return CP->getNumOperands();
1550
1551 // If MIOperandInfo is specified, that gives the count.
1552 if (isLeaf()) {
1553 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1554 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1555 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1556 if (MIOps->getNumArgs())
1557 return MIOps->getNumArgs();
1558 }
1559 }
1560
1561 // Otherwise there is just one result.
1562 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001563}
1564
1565/// NodeHasProperty - Return true if this node has the specified property.
1566bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001567 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001568 if (isLeaf()) {
1569 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1570 return CP->hasProperty(Property);
1571 return false;
1572 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001573
Chris Lattner53c39ba2010-02-14 22:22:58 +00001574 Record *Operator = getOperator();
1575 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001576
Chris Lattner53c39ba2010-02-14 22:22:58 +00001577 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1578}
1579
1580
1581
1582
1583/// TreeHasProperty - Return true if any node in this tree has the specified
1584/// property.
1585bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001586 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001587 if (NodeHasProperty(Property, CGP))
1588 return true;
1589 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1590 if (getChild(i)->TreeHasProperty(Property, CGP))
1591 return true;
1592 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001593}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001594
Evan Cheng49bad4c2008-06-16 20:29:38 +00001595/// isCommutativeIntrinsic - Return true if the node corresponds to a
1596/// commutative intrinsic.
1597bool
1598TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1599 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1600 return Int->isCommutative;
1601 return false;
1602}
1603
Matt Arsenaulteb492162014-11-02 23:46:51 +00001604static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1605 if (!N->isLeaf())
1606 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001607
Matt Arsenaulteb492162014-11-02 23:46:51 +00001608 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1609 if (DI && DI->getDef()->isSubClassOf(Class))
1610 return true;
1611
1612 return false;
1613}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001614
1615static void emitTooManyOperandsError(TreePattern &TP,
1616 StringRef InstName,
1617 unsigned Expected,
1618 unsigned Actual) {
1619 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1620 " operands but expected only " + Twine(Expected) + "!");
1621}
1622
1623static void emitTooFewOperandsError(TreePattern &TP,
1624 StringRef InstName,
1625 unsigned Actual) {
1626 TP.error("Instruction '" + InstName +
1627 "' expects more than the provided " + Twine(Actual) + " operands!");
1628}
1629
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001630/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001631/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001632/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001633bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001634 if (TP.hasError())
1635 return false;
1636
Chris Lattnerab3242f2008-01-06 01:10:31 +00001637 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001638 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001639 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001640 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001641 bool MadeChange = false;
1642 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1643 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001644 NotRegisters,
1645 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001646 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001647 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001648
Sean Silvafb509ed2012-10-10 20:24:43 +00001649 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001650 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001651
Chris Lattnerf1447252010-03-19 21:37:09 +00001652 // Int inits are always integers. :)
1653 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001654
Chris Lattnerf1447252010-03-19 21:37:09 +00001655 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001656 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001657
Chris Lattnerf1447252010-03-19 21:37:09 +00001658 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001659 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1660 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001661
Craig Topper95198f42013-09-25 06:37:18 +00001662 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001663 // Make sure that the value is representable for this type.
1664 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001665
Richard Smith228e6d42012-08-24 23:29:28 +00001666 // Check that the value doesn't use more bits than we have. It must either
1667 // be a sign- or zero-extended equivalent of the original.
1668 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1669 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001670 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001671
Richard Smith228e6d42012-08-24 23:29:28 +00001672 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001673 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001674 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001675 }
1676 return false;
1677 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001678
Chris Lattner8cab0212008-01-05 22:25:12 +00001679 // special handling for set, which isn't really an SDNode.
1680 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001681 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1682 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001683 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001684
Chris Lattnerf1447252010-03-19 21:37:09 +00001685 TreePatternNode *SetVal = getChild(NC-1);
1686 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1687
Elena Demikhovsky09954792015-03-01 08:23:41 +00001688 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001689 TreePatternNode *Child = getChild(i);
1690 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001691
Chris Lattner8cab0212008-01-05 22:25:12 +00001692 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001693 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1694 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001695 }
1696 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001697 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001698
Chris Lattner5c2182e2010-03-27 02:53:27 +00001699 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001700 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1701
Chris Lattner8cab0212008-01-05 22:25:12 +00001702 bool MadeChange = false;
1703 for (unsigned i = 0; i < getNumChildren(); ++i)
1704 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001705 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001706 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001707
Chris Lattneree820ac2010-02-23 05:51:07 +00001708 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001709 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001710
Chris Lattner8cab0212008-01-05 22:25:12 +00001711 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001712 unsigned NumRetVTs = Int->IS.RetVTs.size();
1713 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001714
Bill Wendling91821472008-11-13 09:08:33 +00001715 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001716 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001717
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001718 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001719 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001720 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001721 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001722 return false;
1723 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001724
1725 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001726 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001727
Chris Lattnerf1447252010-03-19 21:37:09 +00001728 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1729 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001730
Chris Lattnerf1447252010-03-19 21:37:09 +00001731 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1732 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1733 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001734 }
1735 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001736 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001737
Chris Lattneree820ac2010-02-23 05:51:07 +00001738 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001739 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001740
Chris Lattner135091b2010-03-28 08:48:47 +00001741 // Check that the number of operands is sane. Negative operands -> varargs.
1742 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001743 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001744 TP.error(getOperator()->getName() + " node requires exactly " +
1745 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001746 return false;
1747 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001748
Chris Lattner8cab0212008-01-05 22:25:12 +00001749 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1750 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1751 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001752 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001753 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001754
Chris Lattneree820ac2010-02-23 05:51:07 +00001755 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001756 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001757 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001758 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001759
Chris Lattnerd44966f2010-03-27 19:15:02 +00001760 bool MadeChange = false;
1761
1762 // Apply the result types to the node, these come from the things in the
1763 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001764 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1765 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001766 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1767 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001768
Chris Lattnerd44966f2010-03-27 19:15:02 +00001769 // If the instruction has implicit defs, we apply the first one as a result.
1770 // FIXME: This sucks, it should apply all implicit defs.
1771 if (!InstInfo.ImplicitDefs.empty()) {
1772 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001773
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001774 // FIXME: Generalize to multiple possible types and multiple possible
1775 // ImplicitDefs.
1776 MVT::SimpleValueType VT =
1777 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001778
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001779 if (VT != MVT::Other)
1780 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001781 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001782
Chris Lattnercabe0372010-03-15 06:00:16 +00001783 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1784 // be the same.
1785 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001786 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1787 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1788 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001789 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1790 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1791 // variadic.
1792
1793 unsigned NChild = getNumChildren();
1794 if (NChild < 3) {
1795 TP.error("REG_SEQUENCE requires at least 3 operands!");
1796 return false;
1797 }
1798
1799 if (NChild % 2 == 0) {
1800 TP.error("REG_SEQUENCE requires an odd number of operands!");
1801 return false;
1802 }
1803
1804 if (!isOperandClass(getChild(0), "RegisterClass")) {
1805 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1806 return false;
1807 }
1808
1809 for (unsigned I = 1; I < NChild; I += 2) {
1810 TreePatternNode *SubIdxChild = getChild(I + 1);
1811 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1812 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1813 itostr(I + 1) + "!");
1814 return false;
1815 }
1816 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001817 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001818
1819 unsigned ChildNo = 0;
1820 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1821 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001822
Chris Lattner8cab0212008-01-05 22:25:12 +00001823 // If the instruction expects a predicate or optional def operand, we
1824 // codegen this by setting the operand to it's default value if it has a
1825 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001826 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001827 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1828 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001829
Chris Lattner8cab0212008-01-05 22:25:12 +00001830 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001831 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001832 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001833 return false;
1834 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001835
Chris Lattner8cab0212008-01-05 22:25:12 +00001836 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001837 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001838
1839 // If the operand has sub-operands, they may be provided by distinct
1840 // child patterns, so attempt to match each sub-operand separately.
1841 if (OperandNode->isSubClassOf("Operand")) {
1842 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1843 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1844 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001845 // a single ComplexPattern-related Operand.
1846
1847 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001848 // Match first sub-operand against the child we already have.
1849 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1850 MadeChange |=
1851 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1852
1853 // And the remaining sub-operands against subsequent children.
1854 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1855 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001856 emitTooFewOperandsError(TP, getOperator()->getName(),
1857 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001858 return false;
1859 }
1860 Child = getChild(ChildNo++);
1861
1862 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1863 MadeChange |=
1864 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1865 }
1866 continue;
1867 }
1868 }
1869 }
1870
1871 // If we didn't match by pieces above, attempt to match the whole
1872 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001873 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001874 }
Christopher Lamba7312392008-03-11 09:33:47 +00001875
Matt Arsenaulteb492162014-11-02 23:46:51 +00001876 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001877 emitTooManyOperandsError(TP, getOperator()->getName(),
1878 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001879 return false;
1880 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001881
Ulrich Weigande618abd2013-03-19 19:51:09 +00001882 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1883 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001884 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001885 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001886
Tim Northoverc807a172014-05-20 11:52:46 +00001887 if (getOperator()->isSubClassOf("ComplexPattern")) {
1888 bool MadeChange = false;
1889
1890 for (unsigned i = 0; i < getNumChildren(); ++i)
1891 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1892
1893 return MadeChange;
1894 }
1895
Chris Lattneree820ac2010-02-23 05:51:07 +00001896 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001897
Chris Lattneree820ac2010-02-23 05:51:07 +00001898 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001899 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001900 TP.error("Node transform '" + getOperator()->getName() +
1901 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001902 return false;
1903 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001904
Chris Lattnercabe0372010-03-15 06:00:16 +00001905 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1906
Jim Grosbach65586fe2010-12-21 16:16:00 +00001907
Chris Lattneree820ac2010-02-23 05:51:07 +00001908 // If either the output or input of the xform does not have exact
1909 // type info. We assume they must be the same. Otherwise, it is perfectly
1910 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001911#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001912 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001913 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1914 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001915 return MadeChange;
1916 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001917#endif
1918 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001919}
1920
1921/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1922/// RHS of a commutative operation, not the on LHS.
1923static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1924 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1925 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001926 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001927 return true;
1928 return false;
1929}
1930
1931
1932/// canPatternMatch - If it is impossible for this pattern to match on this
1933/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001934/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001935/// that can never possibly work), and to prevent the pattern permuter from
1936/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001937bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001938 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001939 if (isLeaf()) return true;
1940
1941 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1942 if (!getChild(i)->canPatternMatch(Reason, CDP))
1943 return false;
1944
1945 // If this is an intrinsic, handle cases that would make it not match. For
1946 // example, if an operand is required to be an immediate.
1947 if (getOperator()->isSubClassOf("Intrinsic")) {
1948 // TODO:
1949 return true;
1950 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001951
Tim Northoverc807a172014-05-20 11:52:46 +00001952 if (getOperator()->isSubClassOf("ComplexPattern"))
1953 return true;
1954
Chris Lattner8cab0212008-01-05 22:25:12 +00001955 // If this node is a commutative operator, check that the LHS isn't an
1956 // immediate.
1957 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001958 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1959 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001960 // Scan all of the operands of the node and make sure that only the last one
1961 // is a constant node, unless the RHS also is.
1962 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001963 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1964 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001965 if (OnlyOnRHSOfCommutative(getChild(i))) {
1966 Reason="Immediate value must be on the RHS of commutative operators!";
1967 return false;
1968 }
1969 }
1970 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001971
Chris Lattner8cab0212008-01-05 22:25:12 +00001972 return true;
1973}
1974
1975//===----------------------------------------------------------------------===//
1976// TreePattern implementation
1977//
1978
David Greeneaf8ee2c2011-07-29 22:43:06 +00001979TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001980 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1981 isInputPattern(isInput), HasError(false) {
Craig Topperef0578a2015-06-02 04:15:51 +00001982 for (Init *I : RawPat->getValues())
1983 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001984}
1985
David Greeneaf8ee2c2011-07-29 22:43:06 +00001986TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001987 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1988 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001989 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001990}
1991
David Blaikiecf195302014-11-17 22:55:41 +00001992TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001993 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1994 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00001995 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00001996}
1997
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00001998void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001999 if (HasError)
2000 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002001 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002002 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2003 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002004}
2005
Chris Lattnercabe0372010-03-15 06:00:16 +00002006void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002007 for (TreePatternNode *Tree : Trees)
2008 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002009}
2010
2011void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2012 if (!N->getName().empty())
2013 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002014
Chris Lattnercabe0372010-03-15 06:00:16 +00002015 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2016 ComputeNamedNodes(N->getChild(i));
2017}
2018
David Blaikiecf195302014-11-17 22:55:41 +00002019
2020TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002021 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002022 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002023
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002024 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002025 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002026 /// (foo GPR, imm) -> (foo GPR, (imm))
2027 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002028 return ParseTreePattern(
2029 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002030 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002031 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002032
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002033 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002034 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002035 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002036 if (OpName.empty())
2037 error("'node' argument requires a name to match with operand list");
2038 Args.push_back(OpName);
2039 }
2040
2041 Res->setName(OpName);
2042 return Res;
2043 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002044
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002045 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002046 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002047 if (OpName.empty())
2048 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002049 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002050 Args.push_back(OpName);
2051 Res->setName(OpName);
2052 return Res;
2053 }
2054
Sean Silvafb509ed2012-10-10 20:24:43 +00002055 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002056 if (!OpName.empty())
2057 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002058 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002059 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002060
Sean Silvafb509ed2012-10-10 20:24:43 +00002061 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002062 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002063 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002064 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002065 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002066 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002067 }
2068
Sean Silvafb509ed2012-10-10 20:24:43 +00002069 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002070 if (!Dag) {
2071 TheInit->dump();
2072 error("Pattern has unexpected init kind!");
2073 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002074 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002075 if (!OpDef) error("Pattern has unexpected operator type!");
2076 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002077
Chris Lattner8cab0212008-01-05 22:25:12 +00002078 if (Operator->isSubClassOf("ValueType")) {
2079 // If the operator is a ValueType, then this must be "type cast" of a leaf
2080 // node.
2081 if (Dag->getNumArgs() != 1)
2082 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002083
David Blaikiecf195302014-11-17 22:55:41 +00002084 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002085
Chris Lattner8cab0212008-01-05 22:25:12 +00002086 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002087 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2088 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002089
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002090 if (!OpName.empty())
2091 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002092 return New;
2093 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002094
Chris Lattner8cab0212008-01-05 22:25:12 +00002095 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002096 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002097 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002098 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002099 !Operator->isSubClassOf("SDNodeXForm") &&
2100 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002101 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002102 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002103 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002104 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002105
Chris Lattner8cab0212008-01-05 22:25:12 +00002106 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002107 if (isInputPattern) {
2108 if (Operator->isSubClassOf("Instruction") ||
2109 Operator->isSubClassOf("SDNodeXForm"))
2110 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2111 } else {
2112 if (Operator->isSubClassOf("Intrinsic"))
2113 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002114
Chris Lattner2e9eae12010-03-28 06:57:56 +00002115 if (Operator->isSubClassOf("SDNode") &&
2116 Operator->getName() != "imm" &&
2117 Operator->getName() != "fpimm" &&
2118 Operator->getName() != "tglobaltlsaddr" &&
2119 Operator->getName() != "tconstpool" &&
2120 Operator->getName() != "tjumptable" &&
2121 Operator->getName() != "tframeindex" &&
2122 Operator->getName() != "texternalsym" &&
2123 Operator->getName() != "tblockaddress" &&
2124 Operator->getName() != "tglobaladdr" &&
2125 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002126 Operator->getName() != "vt" &&
2127 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002128 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2129 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002130
Chris Lattner8cab0212008-01-05 22:25:12 +00002131 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002132
2133 // Parse all the operands.
2134 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002135 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002136
Chris Lattner8cab0212008-01-05 22:25:12 +00002137 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002138 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002139 // convert the intrinsic name to a number.
2140 if (Operator->isSubClassOf("Intrinsic")) {
2141 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2142 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2143
2144 // If this intrinsic returns void, it must have side-effects and thus a
2145 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002146 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002147 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002148 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002149 // Has side-effects, requires chain.
2150 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002151 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002152 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002153
David Greenee32ebf22011-07-29 19:07:07 +00002154 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002155 Children.insert(Children.begin(), IIDNode);
2156 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002157
Tim Northoverc807a172014-05-20 11:52:46 +00002158 if (Operator->isSubClassOf("ComplexPattern")) {
2159 for (unsigned i = 0; i < Children.size(); ++i) {
2160 TreePatternNode *Child = Children[i];
2161
2162 if (Child->getName().empty())
2163 error("All arguments to a ComplexPattern must be named");
2164
2165 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2166 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2167 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2168 auto OperandId = std::make_pair(Operator, i);
2169 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2170 if (PrevOp != ComplexPatternOperands.end()) {
2171 if (PrevOp->getValue() != OperandId)
2172 error("All ComplexPattern operands must appear consistently: "
2173 "in the same order in just one ComplexPattern instance.");
2174 } else
2175 ComplexPatternOperands[Child->getName()] = OperandId;
2176 }
2177 }
2178
Chris Lattnerf1447252010-03-19 21:37:09 +00002179 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002180 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002181 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002182
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002183 if (!Dag->getName().empty()) {
2184 assert(Result->getName().empty());
2185 Result->setName(Dag->getName());
2186 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002187 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002188}
2189
Chris Lattnera787c9e2010-03-28 08:38:32 +00002190/// SimplifyTree - See if we can simplify this tree to eliminate something that
2191/// will never match in favor of something obvious that will. This is here
2192/// strictly as a convenience to target authors because it allows them to write
2193/// more type generic things and have useless type casts fold away.
2194///
2195/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002196static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002197 if (N->isLeaf())
2198 return false;
2199
2200 // If we have a bitconvert with a resolved type and if the source and
2201 // destination types are the same, then the bitconvert is useless, remove it.
2202 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002203 N->getExtType(0).isConcrete() &&
2204 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2205 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002206 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002207 SimplifyTree(N);
2208 return true;
2209 }
2210
2211 // Walk all children.
2212 bool MadeChange = false;
2213 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002214 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002215 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002216 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002217 }
2218 return MadeChange;
2219}
2220
2221
2222
Chris Lattner8cab0212008-01-05 22:25:12 +00002223/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002224/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002225/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002226bool TreePattern::
2227InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2228 if (NamedNodes.empty())
2229 ComputeNamedNodes();
2230
Chris Lattner8cab0212008-01-05 22:25:12 +00002231 bool MadeChange = true;
2232 while (MadeChange) {
2233 MadeChange = false;
Craig Topper306cb122015-11-22 20:46:24 +00002234 for (TreePatternNode *Tree : Trees) {
2235 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2236 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002237 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002238
2239 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002240 for (auto &Entry : NamedNodes) {
2241 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002242
Chris Lattnercabe0372010-03-15 06:00:16 +00002243 // If we have input named node types, propagate their types to the named
2244 // values here.
2245 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002246 if (!InNamedTypes->count(Entry.getKey())) {
2247 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002248 "' in output pattern but not input pattern");
2249 return true;
2250 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002251
2252 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002253 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002254
2255 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002256 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002257 // If this node is a register class, and it is the root of the pattern
2258 // then we're mapping something onto an input register. We allow
2259 // changing the type of the input register in this case. This allows
2260 // us to match things like:
2261 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002262 if (Node == Trees[0] && Node->isLeaf()) {
2263 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002264 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2265 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002266 continue;
2267 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002268
Craig Topper306cb122015-11-22 20:46:24 +00002269 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002270 InNodes[0]->getNumTypes() == 1 &&
2271 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002272 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2273 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002274 }
2275 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002276
Chris Lattnercabe0372010-03-15 06:00:16 +00002277 // If there are multiple nodes with the same name, they must all have the
2278 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002279 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002280 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002281 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002282 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002283 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002284
Chris Lattnerf1447252010-03-19 21:37:09 +00002285 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2286 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002287 }
2288 }
2289 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002290 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002291
Chris Lattner8cab0212008-01-05 22:25:12 +00002292 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002293 for (const TreePatternNode *Tree : Trees)
2294 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
Chris Lattner8cab0212008-01-05 22:25:12 +00002295 return !HasUnresolvedTypes;
2296}
2297
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002298void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002299 OS << getRecord()->getName();
2300 if (!Args.empty()) {
2301 OS << "(" << Args[0];
2302 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2303 OS << ", " << Args[i];
2304 OS << ")";
2305 }
2306 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002307
Chris Lattner8cab0212008-01-05 22:25:12 +00002308 if (Trees.size() > 1)
2309 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002310 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002311 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002312 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002313 OS << "\n";
2314 }
2315
2316 if (Trees.size() > 1)
2317 OS << "]\n";
2318}
2319
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002320void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002321
2322//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002323// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002324//
2325
Jim Grosbach65586fe2010-12-21 16:16:00 +00002326CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002327 Records(R), Target(R) {
2328
Dale Johannesenb842d522009-02-05 01:49:45 +00002329 Intrinsics = LoadIntrinsics(Records, false);
2330 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002331 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002332 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002333 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002334 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002335 ParseDefaultOperands();
2336 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002337 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002338 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002339
Chris Lattner8cab0212008-01-05 22:25:12 +00002340 // Generate variants. For example, commutative patterns can match
2341 // multiple ways. Add them to PatternsToMatch as well.
2342 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002343
2344 // Infer instruction flags. For example, we can detect loads,
2345 // stores, and side effects in many cases by examining an
2346 // instruction's pattern.
2347 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002348
2349 // Verify that instruction flags match the patterns.
2350 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002351}
2352
Chris Lattnerab3242f2008-01-06 01:10:31 +00002353Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002354 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002355 if (!N || !N->isSubClassOf("SDNode"))
2356 PrintFatalError("Error getting SDNode '" + Name + "'!");
2357
Chris Lattner8cab0212008-01-05 22:25:12 +00002358 return N;
2359}
2360
2361// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002362void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002363 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2364 while (!Nodes.empty()) {
2365 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2366 Nodes.pop_back();
2367 }
2368
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002369 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002370 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2371 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2372 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2373}
2374
2375/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2376/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002377void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002378 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2379 while (!Xforms.empty()) {
2380 Record *XFormNode = Xforms.back();
2381 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002382 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002383 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002384
2385 Xforms.pop_back();
2386 }
2387}
2388
Chris Lattnerab3242f2008-01-06 01:10:31 +00002389void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002390 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2391 while (!AMs.empty()) {
2392 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2393 AMs.pop_back();
2394 }
2395}
2396
2397
2398/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2399/// file, building up the PatternFragments map. After we've collected them all,
2400/// inline fragments together as necessary, so that there are no references left
2401/// inside a pattern fragment to a pattern fragment.
2402///
Hal Finkel2756dc12014-02-28 00:26:56 +00002403void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002404 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002405
Chris Lattnere7170df2008-01-05 22:43:57 +00002406 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002407 for (Record *Frag : Fragments) {
2408 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002409 continue;
2410
Craig Topper306cb122015-11-22 20:46:24 +00002411 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002412 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002413 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2414 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002415 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002416
Chris Lattnere7170df2008-01-05 22:43:57 +00002417 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002418 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002419 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002420
Chris Lattnere7170df2008-01-05 22:43:57 +00002421 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002422 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002423
Chris Lattner8cab0212008-01-05 22:25:12 +00002424 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002425 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002426 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002427 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002428 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002429 if (!OpsOp ||
2430 (OpsOp->getDef()->getName() != "ops" &&
2431 OpsOp->getDef()->getName() != "outs" &&
2432 OpsOp->getDef()->getName() != "ins"))
2433 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002434
2435 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002436 Args.clear();
2437 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002438 if (!isa<DefInit>(OpsList->getArg(j)) ||
2439 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002440 P->error("Operands list should all be 'node' values.");
2441 if (OpsList->getArgName(j).empty())
2442 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002443 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002444 P->error("'" + OpsList->getArgName(j) +
2445 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002446 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002447 Args.push_back(OpsList->getArgName(j));
2448 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002449
Chris Lattnere7170df2008-01-05 22:43:57 +00002450 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002451 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002452 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002453
Chris Lattnere7170df2008-01-05 22:43:57 +00002454 // If there is a code init for this fragment, keep track of the fact that
2455 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002456 TreePredicateFn PredFn(P);
2457 if (!PredFn.isAlwaysTrue())
2458 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002459
Chris Lattner8cab0212008-01-05 22:25:12 +00002460 // If there is a node transformation corresponding to this, keep track of
2461 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002462 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002463 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2464 P->getOnlyTree()->setTransformFn(Transform);
2465 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002466
Chris Lattner8cab0212008-01-05 22:25:12 +00002467 // Now that we've parsed all of the tree fragments, do a closure on them so
2468 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002469 for (Record *Frag : Fragments) {
2470 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002471 continue;
2472
Craig Topper306cb122015-11-22 20:46:24 +00002473 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002474 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002475
Chris Lattner8cab0212008-01-05 22:25:12 +00002476 // Infer as many types as possible. Don't worry about it if we don't infer
2477 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002478 ThePat.InferAllTypes();
2479 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002480
Chris Lattner8cab0212008-01-05 22:25:12 +00002481 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002482 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002483 }
2484}
2485
Chris Lattnerab3242f2008-01-06 01:10:31 +00002486void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002487 std::vector<Record*> DefaultOps;
2488 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002489
2490 // Find some SDNode.
2491 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002492 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002493
Tom Stellardb7246a72012-09-06 14:15:52 +00002494 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2495 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002496
Tom Stellardb7246a72012-09-06 14:15:52 +00002497 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2498 // SomeSDnode so that we can parse this.
2499 std::vector<std::pair<Init*, std::string> > Ops;
2500 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2501 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2502 DefaultInfo->getArgName(op)));
2503 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002504
Tom Stellardb7246a72012-09-06 14:15:52 +00002505 // Create a TreePattern to parse this.
2506 TreePattern P(DefaultOps[i], DI, false, *this);
2507 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002508
Tom Stellardb7246a72012-09-06 14:15:52 +00002509 // Copy the operands over into a DAGDefaultOperand.
2510 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002511
Tom Stellardb7246a72012-09-06 14:15:52 +00002512 TreePatternNode *T = P.getTree(0);
2513 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2514 TreePatternNode *TPN = T->getChild(op);
2515 while (TPN->ApplyTypeConstraints(P, false))
2516 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002517
Tom Stellardb7246a72012-09-06 14:15:52 +00002518 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002519 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2520 DefaultOps[i]->getName() +
2521 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002522 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002523 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002524 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002525
2526 // Insert it into the DefaultOperands map so we can find it later.
2527 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002528 }
2529}
2530
2531/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2532/// instruction input. Return true if this is a real use.
2533static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002534 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002535 // No name -> not interesting.
2536 if (Pat->getName().empty()) {
2537 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002538 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002539 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2540 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002541 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002542 }
2543 return false;
2544 }
2545
2546 Record *Rec;
2547 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002548 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002549 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2550 Rec = DI->getDef();
2551 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002552 Rec = Pat->getOperator();
2553 }
2554
2555 // SRCVALUE nodes are ignored.
2556 if (Rec->getName() == "srcvalue")
2557 return false;
2558
2559 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2560 if (!Slot) {
2561 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002562 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002563 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002564 Record *SlotRec;
2565 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002566 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002567 } else {
2568 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2569 SlotRec = Slot->getOperator();
2570 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002571
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002572 // Ensure that the inputs agree if we've already seen this input.
2573 if (Rec != SlotRec)
2574 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002575 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002576 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002577 return true;
2578}
2579
2580/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2581/// part of "I", the instruction), computing the set of inputs and outputs of
2582/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002583void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002584FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2585 std::map<std::string, TreePatternNode*> &InstInputs,
2586 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002587 std::vector<Record*> &InstImpResults) {
2588 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002589 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002590 if (!isUse && Pat->getTransformFn())
2591 I->error("Cannot specify a transform function for a non-input value!");
2592 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002593 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002594
Chris Lattnerf2d70992010-02-17 06:53:36 +00002595 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002596 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2597 TreePatternNode *Dest = Pat->getChild(i);
2598 if (!Dest->isLeaf())
2599 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002600
Sean Silvafb509ed2012-10-10 20:24:43 +00002601 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002602 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2603 I->error("implicitly defined value should be a register!");
2604 InstImpResults.push_back(Val->getDef());
2605 }
2606 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002607 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002608
Chris Lattnerf2d70992010-02-17 06:53:36 +00002609 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002610 // If this is not a set, verify that the children nodes are not void typed,
2611 // and recurse.
2612 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002613 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002614 I->error("Cannot have void nodes inside of patterns!");
2615 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002616 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002617 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002618
Chris Lattner8cab0212008-01-05 22:25:12 +00002619 // If this is a non-leaf node with no children, treat it basically as if
2620 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002621 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002622
Chris Lattner8cab0212008-01-05 22:25:12 +00002623 if (!isUse && Pat->getTransformFn())
2624 I->error("Cannot specify a transform function for a non-input value!");
2625 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002626 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002627
Chris Lattner8cab0212008-01-05 22:25:12 +00002628 // Otherwise, this is a set, validate and collect instruction results.
2629 if (Pat->getNumChildren() == 0)
2630 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002631
Chris Lattner8cab0212008-01-05 22:25:12 +00002632 if (Pat->getTransformFn())
2633 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002634
Chris Lattner8cab0212008-01-05 22:25:12 +00002635 // Check the set destinations.
2636 unsigned NumDests = Pat->getNumChildren()-1;
2637 for (unsigned i = 0; i != NumDests; ++i) {
2638 TreePatternNode *Dest = Pat->getChild(i);
2639 if (!Dest->isLeaf())
2640 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002641
Sean Silvafb509ed2012-10-10 20:24:43 +00002642 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002643 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002644 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002645 continue;
2646 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002647
2648 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002649 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002650 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002651 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002652 if (Dest->getName().empty())
2653 I->error("set destination must have a name!");
2654 if (InstResults.count(Dest->getName()))
2655 I->error("cannot set '" + Dest->getName() +"' multiple times");
2656 InstResults[Dest->getName()] = Dest;
2657 } else if (Val->getDef()->isSubClassOf("Register")) {
2658 InstImpResults.push_back(Val->getDef());
2659 } else {
2660 I->error("set destination should be a register!");
2661 }
2662 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002663
Chris Lattner8cab0212008-01-05 22:25:12 +00002664 // Verify and collect info from the computation.
2665 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002666 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002667}
2668
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002669//===----------------------------------------------------------------------===//
2670// Instruction Analysis
2671//===----------------------------------------------------------------------===//
2672
2673class InstAnalyzer {
2674 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002675public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002676 bool hasSideEffects;
2677 bool mayStore;
2678 bool mayLoad;
2679 bool isBitcast;
2680 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002681
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002682 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2683 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2684 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002685
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002686 void Analyze(const TreePattern *Pat) {
2687 // Assume only the first tree is the pattern. The others are clobber nodes.
2688 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002689 }
2690
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002691 void Analyze(const PatternToMatch *Pat) {
2692 AnalyzeNode(Pat->getSrcPattern());
2693 }
2694
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002695private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002696 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002697 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002698 return false;
2699
2700 if (N->getNumChildren() != 2)
2701 return false;
2702
2703 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002704 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002705 return false;
2706
2707 const TreePatternNode *N1 = N->getChild(1);
2708 if (N1->isLeaf())
2709 return false;
2710 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2711 return false;
2712
2713 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2714 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2715 return false;
2716 return OpInfo.getEnumName() == "ISD::BITCAST";
2717 }
2718
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002719public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002720 void AnalyzeNode(const TreePatternNode *N) {
2721 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002722 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002723 Record *LeafRec = DI->getDef();
2724 // Handle ComplexPattern leaves.
2725 if (LeafRec->isSubClassOf("ComplexPattern")) {
2726 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2727 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2728 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002729 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002730 }
2731 }
2732 return;
2733 }
2734
2735 // Analyze children.
2736 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2737 AnalyzeNode(N->getChild(i));
2738
2739 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002740 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002741 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002742 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002743 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002744
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002745 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002746 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2747 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2748 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2749 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002750
2751 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2752 // If this is an intrinsic, analyze it.
2753 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2754 mayLoad = true;// These may load memory.
2755
Dan Gohmanddb2d652010-08-05 23:36:21 +00002756 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002757 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2758
Dan Gohmanddb2d652010-08-05 23:36:21 +00002759 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002760 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002761 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002762 }
2763 }
2764
2765};
2766
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002767static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002768 const InstAnalyzer &PatInfo,
2769 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002770 bool Error = false;
2771
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002772 // Remember where InstInfo got its flags.
2773 if (InstInfo.hasUndefFlags())
2774 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002775
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002776 // Check explicitly set flags for consistency.
2777 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2778 !InstInfo.hasSideEffects_Unset) {
2779 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2780 // the pattern has no side effects. That could be useful for div/rem
2781 // instructions that may trap.
2782 if (!InstInfo.hasSideEffects) {
2783 Error = true;
2784 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2785 Twine(InstInfo.hasSideEffects));
2786 }
2787 }
2788
2789 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2790 Error = true;
2791 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2792 Twine(InstInfo.mayStore));
2793 }
2794
2795 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2796 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00002797 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002798 if (!InstInfo.mayLoad) {
2799 Error = true;
2800 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2801 Twine(InstInfo.mayLoad));
2802 }
2803 }
2804
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002805 // Transfer inferred flags.
2806 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2807 InstInfo.mayStore |= PatInfo.mayStore;
2808 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002809
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002810 // These flags are silently added without any verification.
2811 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002812
2813 // Don't infer isVariadic. This flag means something different on SDNodes and
2814 // instructions. For example, a CALL SDNode is variadic because it has the
2815 // call arguments as operands, but a CALL instruction is not variadic - it
2816 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002817
2818 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002819}
2820
Jim Grosbach514410b2012-07-17 00:47:06 +00002821/// hasNullFragReference - Return true if the DAG has any reference to the
2822/// null_frag operator.
2823static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002824 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002825 if (!OpDef) return false;
2826 Record *Operator = OpDef->getDef();
2827
2828 // If this is the null fragment, return true.
2829 if (Operator->getName() == "null_frag") return true;
2830 // If any of the arguments reference the null fragment, return true.
2831 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002832 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002833 if (Arg && hasNullFragReference(Arg))
2834 return true;
2835 }
2836
2837 return false;
2838}
2839
2840/// hasNullFragReference - Return true if any DAG in the list references
2841/// the null_frag operator.
2842static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00002843 for (Init *I : LI->getValues()) {
2844 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00002845 assert(DI && "non-dag in an instruction Pattern list?!");
2846 if (hasNullFragReference(DI))
2847 return true;
2848 }
2849 return false;
2850}
2851
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002852/// Get all the instructions in a tree.
2853static void
2854getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2855 if (Tree->isLeaf())
2856 return;
2857 if (Tree->getOperator()->isSubClassOf("Instruction"))
2858 Instrs.push_back(Tree->getOperator());
2859 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2860 getInstructionsInTree(Tree->getChild(i), Instrs);
2861}
2862
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002863/// Check the class of a pattern leaf node against the instruction operand it
2864/// represents.
2865static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2866 Record *Leaf) {
2867 if (OI.Rec == Leaf)
2868 return true;
2869
2870 // Allow direct value types to be used in instruction set patterns.
2871 // The type will be checked later.
2872 if (Leaf->isSubClassOf("ValueType"))
2873 return true;
2874
2875 // Patterns can also be ComplexPattern instances.
2876 if (Leaf->isSubClassOf("ComplexPattern"))
2877 return true;
2878
2879 return false;
2880}
2881
Ahmed Bougacha14107512013-10-28 18:07:21 +00002882const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2883 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002884
Craig Topper0d1fb902015-03-10 03:25:04 +00002885 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002886
Craig Topper0d1fb902015-03-10 03:25:04 +00002887 // Parse the instruction.
2888 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2889 // Inline pattern fragments into it.
2890 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002891
Craig Topper0d1fb902015-03-10 03:25:04 +00002892 // Infer as many types as possible. If we cannot infer all of them, we can
2893 // never do anything with this instruction pattern: report it to the user.
2894 if (!I->InferAllTypes())
2895 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002896
Craig Topper0d1fb902015-03-10 03:25:04 +00002897 // InstInputs - Keep track of all of the inputs of the instruction, along
2898 // with the record they are declared as.
2899 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002900
Craig Topper0d1fb902015-03-10 03:25:04 +00002901 // InstResults - Keep track of all the virtual registers that are 'set'
2902 // in the instruction, including what reg class they are.
2903 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002904
Craig Topper0d1fb902015-03-10 03:25:04 +00002905 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002906
Craig Topper0d1fb902015-03-10 03:25:04 +00002907 // Verify that the top-level forms in the instruction are of void type, and
2908 // fill in the InstResults map.
2909 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2910 TreePatternNode *Pat = I->getTree(j);
2911 if (Pat->getNumTypes() != 0)
2912 I->error("Top-level forms in instruction pattern should have"
2913 " void types");
Chris Lattner8cab0212008-01-05 22:25:12 +00002914
Craig Topper0d1fb902015-03-10 03:25:04 +00002915 // Find inputs and outputs, and verify the structure of the uses/defs.
2916 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2917 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002918 }
2919
Craig Topper0d1fb902015-03-10 03:25:04 +00002920 // Now that we have inputs and outputs of the pattern, inspect the operands
2921 // list for the instruction. This determines the order that operands are
2922 // added to the machine instruction the node corresponds to.
2923 unsigned NumResults = InstResults.size();
2924
2925 // Parse the operands list from the (ops) list, validating it.
2926 assert(I->getArgList().empty() && "Args list should still be empty here!");
2927
2928 // Check that all of the results occur first in the list.
2929 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00002930 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00002931 for (unsigned i = 0; i != NumResults; ++i) {
2932 if (i == CGI.Operands.size())
2933 I->error("'" + InstResults.begin()->first +
2934 "' set but does not appear in operand list!");
2935 const std::string &OpName = CGI.Operands[i].Name;
2936
2937 // Check that it exists in InstResults.
2938 TreePatternNode *RNode = InstResults[OpName];
2939 if (!RNode)
2940 I->error("Operand $" + OpName + " does not exist in operand list!");
2941
Craig Topper3a8eb892015-03-20 05:09:06 +00002942 ResNodes.push_back(RNode);
2943
Craig Topper0d1fb902015-03-10 03:25:04 +00002944 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2945 if (!R)
2946 I->error("Operand $" + OpName + " should be a set destination: all "
2947 "outputs must occur before inputs in operand list!");
2948
2949 if (!checkOperandClass(CGI.Operands[i], R))
2950 I->error("Operand $" + OpName + " class mismatch!");
2951
2952 // Remember the return type.
2953 Results.push_back(CGI.Operands[i].Rec);
2954
2955 // Okay, this one checks out.
2956 InstResults.erase(OpName);
2957 }
2958
2959 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2960 // the copy while we're checking the inputs.
2961 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2962
2963 std::vector<TreePatternNode*> ResultNodeOperands;
2964 std::vector<Record*> Operands;
2965 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2966 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2967 const std::string &OpName = Op.Name;
2968 if (OpName.empty())
2969 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2970
2971 if (!InstInputsCheck.count(OpName)) {
2972 // If this is an operand with a DefaultOps set filled in, we can ignore
2973 // this. When we codegen it, we will do so as always executed.
2974 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2975 // Does it have a non-empty DefaultOps field? If so, ignore this
2976 // operand.
2977 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2978 continue;
2979 }
2980 I->error("Operand $" + OpName +
2981 " does not appear in the instruction pattern");
2982 }
2983 TreePatternNode *InVal = InstInputsCheck[OpName];
2984 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2985
2986 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2987 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2988 if (!checkOperandClass(Op, InRec))
2989 I->error("Operand $" + OpName + "'s register class disagrees"
2990 " between the operand and pattern");
2991 }
2992 Operands.push_back(Op.Rec);
2993
2994 // Construct the result for the dest-pattern operand list.
2995 TreePatternNode *OpNode = InVal->clone();
2996
2997 // No predicate is useful on the result.
2998 OpNode->clearPredicateFns();
2999
3000 // Promote the xform function to be an explicit node if set.
3001 if (Record *Xform = OpNode->getTransformFn()) {
3002 OpNode->setTransformFn(nullptr);
3003 std::vector<TreePatternNode*> Children;
3004 Children.push_back(OpNode);
3005 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3006 }
3007
3008 ResultNodeOperands.push_back(OpNode);
3009 }
3010
3011 if (!InstInputsCheck.empty())
3012 I->error("Input operand $" + InstInputsCheck.begin()->first +
3013 " occurs in pattern but not in operands list!");
3014
3015 TreePatternNode *ResultPattern =
3016 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3017 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003018 // Copy fully inferred output node types to instruction result pattern.
3019 for (unsigned i = 0; i != NumResults; ++i) {
3020 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3021 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3022 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003023
3024 // Create and insert the instruction.
3025 // FIXME: InstImpResults should not be part of DAGInstruction.
3026 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3027 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3028
3029 // Use a temporary tree pattern to infer all types and make sure that the
3030 // constructed result is correct. This depends on the instruction already
3031 // being inserted into the DAGInsts map.
3032 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3033 Temp.InferAllTypes(&I->getNamedNodesMap());
3034
3035 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3036 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3037
3038 return TheInsertedInst;
3039}
3040
Ahmed Bougacha14107512013-10-28 18:07:21 +00003041/// ParseInstructions - Parse all of the instructions, inlining and resolving
3042/// any fragments involved. This populates the Instructions list with fully
3043/// resolved instructions.
3044void CodeGenDAGPatterns::ParseInstructions() {
3045 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3046
Craig Topper306cb122015-11-22 20:46:24 +00003047 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003048 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003049
Craig Topper306cb122015-11-22 20:46:24 +00003050 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3051 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003052
3053 // If there is no pattern, only collect minimal information about the
3054 // instruction for its operand list. We have to assume that there is one
3055 // result, as we have no detailed info. A pattern which references the
3056 // null_frag operator is as-if no pattern were specified. Normally this
3057 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3058 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003059 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003060 std::vector<Record*> Results;
3061 std::vector<Record*> Operands;
3062
Craig Topper306cb122015-11-22 20:46:24 +00003063 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003064
3065 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003066 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3067 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003068
Craig Topper3a8eb892015-03-20 05:09:06 +00003069 // The rest are inputs.
3070 for (unsigned j = InstInfo.Operands.NumDefs,
3071 e = InstInfo.Operands.size(); j < e; ++j)
3072 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003073 }
3074
3075 // Create and insert the instruction.
3076 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003077 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003078 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003079 continue; // no pattern.
3080 }
3081
Craig Topper306cb122015-11-22 20:46:24 +00003082 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003083 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3084
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003085 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003086 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003087 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003088
Chris Lattner8cab0212008-01-05 22:25:12 +00003089 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003090 for (auto &Entry : Instructions) {
3091 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003092 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003093 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003094
3095 // FIXME: Assume only the first tree is the pattern. The others are clobber
3096 // nodes.
3097 TreePatternNode *Pattern = I->getTree(0);
3098 TreePatternNode *SrcPattern;
3099 if (Pattern->getOperator()->getName() == "set") {
3100 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3101 } else{
3102 // Not a set (store or something?)
3103 SrcPattern = Pattern;
3104 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003105
Craig Topper306cb122015-11-22 20:46:24 +00003106 Record *Instr = Entry.first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003107 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003108 PatternToMatch(Instr,
3109 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003110 SrcPattern,
3111 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003112 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003113 Instr->getValueAsInt("AddedComplexity"),
3114 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003115 }
3116}
3117
Chris Lattnera7722b62010-02-23 06:55:24 +00003118
3119typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3120
Jim Grosbach65586fe2010-12-21 16:16:00 +00003121static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003122 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003123 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003124 if (!P->getName().empty()) {
3125 NameRecord &Rec = Names[P->getName()];
3126 // If this is the first instance of the name, remember the node.
3127 if (Rec.second++ == 0)
3128 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003129 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003130 PatternTop->error("repetition of value: $" + P->getName() +
3131 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003132 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003133
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003134 if (!P->isLeaf()) {
3135 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003136 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003137 }
3138}
3139
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003140void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003141 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003142 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003143 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003144 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3145 PrintWarning(Pattern->getRecord()->getLoc(),
3146 Twine("Pattern can never match: ") + Reason);
3147 return;
3148 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003149
Chris Lattner1e634e32010-03-01 22:29:19 +00003150 // If the source pattern's root is a complex pattern, that complex pattern
3151 // must specify the nodes it can potentially match.
3152 if (const ComplexPattern *CP =
3153 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3154 if (CP->getRootNodes().empty())
3155 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3156 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003157
3158
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003159 // Find all of the named values in the input and output, ensure they have the
3160 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003161 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003162 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3163 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003164
3165 // Scan all of the named values in the destination pattern, rejecting them if
3166 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003167 for (const auto &Entry : DstNames) {
3168 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003169 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003170 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003171 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003172
Chris Lattnera7722b62010-02-23 06:55:24 +00003173 // Scan all of the named values in the source pattern, rejecting them if the
3174 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003175 for (const auto &Entry : SrcNames)
3176 if (DstNames[Entry.first].first == nullptr &&
3177 SrcNames[Entry.first].second == 1)
3178 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003179
Chris Lattner0c0baa92010-02-23 06:16:51 +00003180 PatternsToMatch.push_back(PTM);
3181}
3182
3183
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003184
3185void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003186 const std::vector<const CodeGenInstruction*> &Instructions =
3187 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003188
3189 // First try to infer flags from the primary instruction pattern, if any.
3190 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003191 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003192 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3193 CodeGenInstruction &InstInfo =
3194 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003195
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003196 // Get the primary instruction pattern.
3197 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3198 if (!Pattern) {
3199 if (InstInfo.hasUndefFlags())
3200 Revisit.push_back(&InstInfo);
3201 continue;
3202 }
3203 InstAnalyzer PatInfo(*this);
3204 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003205 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003206 }
3207
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003208 // Second, look for single-instruction patterns defined outside the
3209 // instruction.
3210 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3211 const PatternToMatch &PTM = *I;
3212
3213 // We can only infer from single-instruction patterns, otherwise we won't
3214 // know which instruction should get the flags.
3215 SmallVector<Record*, 8> PatInstrs;
3216 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3217 if (PatInstrs.size() != 1)
3218 continue;
3219
3220 // Get the single instruction.
3221 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3222
3223 // Only infer properties from the first pattern. We'll verify the others.
3224 if (InstInfo.InferredFrom)
3225 continue;
3226
3227 InstAnalyzer PatInfo(*this);
3228 PatInfo.Analyze(&PTM);
3229 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3230 }
3231
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003232 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003233 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003234
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003235 // Revisit instructions with undefined flags and no pattern.
3236 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003237 for (CodeGenInstruction *InstInfo : Revisit) {
3238 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003239 continue;
3240 // The mayLoad and mayStore flags default to false.
3241 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003242 if (InstInfo->hasSideEffects_Unset)
3243 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003244 }
3245 return;
3246 }
3247
3248 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003249 for (CodeGenInstruction *InstInfo : Revisit) {
3250 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003251 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003252 if (InstInfo->hasSideEffects_Unset)
3253 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003254 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003255 if (InstInfo->mayStore_Unset)
3256 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003257 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003258 if (InstInfo->mayLoad_Unset)
3259 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003260 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003261 }
3262}
3263
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003264
3265/// Verify instruction flags against pattern node properties.
3266void CodeGenDAGPatterns::VerifyInstructionFlags() {
3267 unsigned Errors = 0;
3268 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3269 const PatternToMatch &PTM = *I;
3270 SmallVector<Record*, 8> Instrs;
3271 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3272 if (Instrs.empty())
3273 continue;
3274
3275 // Count the number of instructions with each flag set.
3276 unsigned NumSideEffects = 0;
3277 unsigned NumStores = 0;
3278 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003279 for (const Record *Instr : Instrs) {
3280 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003281 NumSideEffects += InstInfo.hasSideEffects;
3282 NumStores += InstInfo.mayStore;
3283 NumLoads += InstInfo.mayLoad;
3284 }
3285
3286 // Analyze the source pattern.
3287 InstAnalyzer PatInfo(*this);
3288 PatInfo.Analyze(&PTM);
3289
3290 // Collect error messages.
3291 SmallVector<std::string, 4> Msgs;
3292
3293 // Check for missing flags in the output.
3294 // Permit extra flags for now at least.
3295 if (PatInfo.hasSideEffects && !NumSideEffects)
3296 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3297
3298 // Don't verify store flags on instructions with side effects. At least for
3299 // intrinsics, side effects implies mayStore.
3300 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3301 Msgs.push_back("pattern may store, but mayStore isn't set");
3302
3303 // Similarly, mayStore implies mayLoad on intrinsics.
3304 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3305 Msgs.push_back("pattern may load, but mayLoad isn't set");
3306
3307 // Print error messages.
3308 if (Msgs.empty())
3309 continue;
3310 ++Errors;
3311
Craig Topper306cb122015-11-22 20:46:24 +00003312 for (const std::string &Msg : Msgs)
3313 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003314 (Instrs.size() == 1 ?
3315 "instruction" : "output instructions"));
3316 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003317 for (const Record *Instr : Instrs) {
3318 if (Instr != PTM.getSrcRecord())
3319 PrintError(Instr->getLoc(), "defined here");
3320 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003321 if (InstInfo.InferredFrom &&
3322 InstInfo.InferredFrom != InstInfo.TheDef &&
3323 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003324 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003325 }
3326 }
3327 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003328 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003329}
3330
Chris Lattnercabe0372010-03-15 06:00:16 +00003331/// Given a pattern result with an unresolved type, see if we can find one
3332/// instruction with an unresolved result type. Force this result type to an
3333/// arbitrary element if it's possible types to converge results.
3334static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3335 if (N->isLeaf())
3336 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003337
Chris Lattnercabe0372010-03-15 06:00:16 +00003338 // Analyze children.
3339 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3340 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3341 return true;
3342
3343 if (!N->getOperator()->isSubClassOf("Instruction"))
3344 return false;
3345
3346 // If this type is already concrete or completely unknown we can't do
3347 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003348 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3349 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3350 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003351
Chris Lattnerf1447252010-03-19 21:37:09 +00003352 // Otherwise, force its type to the first possibility (an arbitrary choice).
3353 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3354 return true;
3355 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003356
Chris Lattnerf1447252010-03-19 21:37:09 +00003357 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003358}
3359
Chris Lattnerab3242f2008-01-06 01:10:31 +00003360void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003361 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3362
Craig Topper306cb122015-11-22 20:46:24 +00003363 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003364 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003365
3366 // If the pattern references the null_frag, there's nothing to do.
3367 if (hasNullFragReference(Tree))
3368 continue;
3369
Chris Lattner5c2182e2010-03-27 02:53:27 +00003370 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003371
3372 // Inline pattern fragments into it.
3373 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003374
David Greeneaf8ee2c2011-07-29 22:43:06 +00003375 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003376 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003377
Chris Lattner8cab0212008-01-05 22:25:12 +00003378 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003379 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003380
Chris Lattner8cab0212008-01-05 22:25:12 +00003381 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003382 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003383
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003384 if (Result.getNumTrees() != 1)
3385 Result.error("Cannot handle instructions producing instructions "
3386 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003387
Chris Lattner8cab0212008-01-05 22:25:12 +00003388 bool IterateInference;
3389 bool InferredAllPatternTypes, InferredAllResultTypes;
3390 do {
3391 // Infer as many types as possible. If we cannot infer all of them, we
3392 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003393 InferredAllPatternTypes =
3394 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003395
Chris Lattner8cab0212008-01-05 22:25:12 +00003396 // Infer as many types as possible. If we cannot infer all of them, we
3397 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003398 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003399 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003400
Chris Lattnerfdc20712010-03-18 23:15:10 +00003401 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003402
Chris Lattner8cab0212008-01-05 22:25:12 +00003403 // Apply the type of the result to the source pattern. This helps us
3404 // resolve cases where the input type is known to be a pointer type (which
3405 // is considered resolved), but the result knows it needs to be 32- or
3406 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003407 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003408 Pattern->getTree(0)->getNumTypes());
3409 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003410 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3411 i, Result.getTree(0)->getExtType(i), Result);
3412 IterateInference |= Result.getTree(0)->UpdateNodeType(
3413 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003414 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003415
Chris Lattnercabe0372010-03-15 06:00:16 +00003416 // If our iteration has converged and the input pattern's types are fully
3417 // resolved but the result pattern is not fully resolved, we may have a
3418 // situation where we have two instructions in the result pattern and
3419 // the instructions require a common register class, but don't care about
3420 // what actual MVT is used. This is actually a bug in our modelling:
3421 // output patterns should have register classes, not MVTs.
3422 //
3423 // In any case, to handle this, we just go through and disambiguate some
3424 // arbitrary types to the result pattern's nodes.
3425 if (!IterateInference && InferredAllPatternTypes &&
3426 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003427 IterateInference =
3428 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003429 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003430
Chris Lattner8cab0212008-01-05 22:25:12 +00003431 // Verify that we inferred enough types that we can do something with the
3432 // pattern and result. If these fire the user has to add type casts.
3433 if (!InferredAllPatternTypes)
3434 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003435 if (!InferredAllResultTypes) {
3436 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003437 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003438 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003439
Chris Lattner8cab0212008-01-05 22:25:12 +00003440 // Validate that the input pattern is correct.
3441 std::map<std::string, TreePatternNode*> InstInputs;
3442 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003443 std::vector<Record*> InstImpResults;
3444 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3445 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3446 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003447 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003448
3449 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003450 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003451 std::vector<TreePatternNode*> ResultNodeOperands;
3452 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3453 TreePatternNode *OpNode = DstPattern->getChild(ii);
3454 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003455 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003456 std::vector<TreePatternNode*> Children;
3457 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003458 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003459 }
3460 ResultNodeOperands.push_back(OpNode);
3461 }
David Blaikiecf195302014-11-17 22:55:41 +00003462 DstPattern = Result.getOnlyTree();
3463 if (!DstPattern->isLeaf())
3464 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3465 ResultNodeOperands,
3466 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003467
David Blaikiecf195302014-11-17 22:55:41 +00003468 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3469 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3470
3471 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003472 Temp.InferAllTypes();
3473
Jim Grosbach65586fe2010-12-21 16:16:00 +00003474
Chris Lattner0c0baa92010-02-23 06:16:51 +00003475 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003476 PatternToMatch(CurPattern,
3477 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003478 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003479 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003480 CurPattern->getValueAsInt("AddedComplexity"),
3481 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003482 }
3483}
3484
3485/// CombineChildVariants - Given a bunch of permutations of each child of the
3486/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003487static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003488 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3489 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003490 CodeGenDAGPatterns &CDP,
3491 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003492 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003493 for (const auto &Variants : ChildVariants)
3494 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003495 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003496
Chris Lattner8cab0212008-01-05 22:25:12 +00003497 // The end result is an all-pairs construction of the resultant pattern.
3498 std::vector<unsigned> Idxs;
3499 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003500 bool NotDone;
3501 do {
3502#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003503 DEBUG(if (!Idxs.empty()) {
3504 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003505 for (unsigned Idx : Idxs) {
3506 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003507 }
3508 errs() << "]\n";
3509 });
Scott Michel94420742008-03-05 17:49:05 +00003510#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003511 // Create the variant and add it to the output list.
3512 std::vector<TreePatternNode*> NewChildren;
3513 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3514 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003515 auto R = llvm::make_unique<TreePatternNode>(
3516 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003517
Chris Lattner8cab0212008-01-05 22:25:12 +00003518 // Copy over properties.
3519 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003520 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003521 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003522 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3523 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003524
Scott Michel94420742008-03-05 17:49:05 +00003525 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003526 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003527 // Scan to see if this pattern has already been emitted. We can get
3528 // duplication due to things like commuting:
3529 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3530 // which are the same pattern. Ignore the dups.
3531 if (R->canPatternMatch(ErrString, CDP) &&
3532 std::none_of(OutVariants.begin(), OutVariants.end(),
3533 [&](TreePatternNode *Variant) {
3534 return R->isIsomorphicTo(Variant, DepVars);
3535 }))
3536 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003537
Scott Michel94420742008-03-05 17:49:05 +00003538 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003539 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003540 // [0, 0], [0, 1], [1, 0], [1, 1].
3541 int IdxsIdx;
3542 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3543 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3544 Idxs[IdxsIdx] = 0;
3545 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003546 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003547 }
Scott Michel94420742008-03-05 17:49:05 +00003548 NotDone = (IdxsIdx >= 0);
3549 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003550}
3551
3552/// CombineChildVariants - A helper function for binary operators.
3553///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003554static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003555 const std::vector<TreePatternNode*> &LHS,
3556 const std::vector<TreePatternNode*> &RHS,
3557 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003558 CodeGenDAGPatterns &CDP,
3559 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003560 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3561 ChildVariants.push_back(LHS);
3562 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003563 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003564}
Chris Lattner8cab0212008-01-05 22:25:12 +00003565
3566
3567static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3568 std::vector<TreePatternNode *> &Children) {
3569 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3570 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003571
Chris Lattner8cab0212008-01-05 22:25:12 +00003572 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003573 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003574 N->getTransformFn()) {
3575 Children.push_back(N);
3576 return;
3577 }
3578
3579 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3580 Children.push_back(N->getChild(0));
3581 else
3582 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3583
3584 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3585 Children.push_back(N->getChild(1));
3586 else
3587 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3588}
3589
3590/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3591/// the (potentially recursive) pattern by using algebraic laws.
3592///
3593static void GenerateVariantsOf(TreePatternNode *N,
3594 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003595 CodeGenDAGPatterns &CDP,
3596 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003597 // We cannot permute leaves or ComplexPattern uses.
3598 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003599 OutVariants.push_back(N);
3600 return;
3601 }
3602
3603 // Look up interesting info about the node.
3604 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3605
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003606 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003607 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003608 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003609 std::vector<TreePatternNode*> MaximalChildren;
3610 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3611
3612 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3613 // permutations.
3614 if (MaximalChildren.size() == 3) {
3615 // Find the variants of all of our maximal children.
3616 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003617 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3618 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3619 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003620
Chris Lattner8cab0212008-01-05 22:25:12 +00003621 // There are only two ways we can permute the tree:
3622 // (A op B) op C and A op (B op C)
3623 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003624
Chris Lattner8cab0212008-01-05 22:25:12 +00003625 // Generate legal pair permutations of A/B/C.
3626 std::vector<TreePatternNode*> ABVariants;
3627 std::vector<TreePatternNode*> BAVariants;
3628 std::vector<TreePatternNode*> ACVariants;
3629 std::vector<TreePatternNode*> CAVariants;
3630 std::vector<TreePatternNode*> BCVariants;
3631 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003632 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3633 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3634 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3635 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3636 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3637 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003638
3639 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003640 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3641 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3642 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3643 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3644 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3645 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003646
3647 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003648 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3649 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3650 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3651 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3652 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3653 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003654 return;
3655 }
3656 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003657
Chris Lattner8cab0212008-01-05 22:25:12 +00003658 // Compute permutations of all children.
3659 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3660 ChildVariants.resize(N->getNumChildren());
3661 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003662 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003663
3664 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003665 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003666
3667 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003668 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3669 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3670 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3671 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003672 // Don't count children which are actually register references.
3673 unsigned NC = 0;
3674 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3675 TreePatternNode *Child = N->getChild(i);
3676 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003677 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003678 Record *RR = DI->getDef();
3679 if (RR->isSubClassOf("Register"))
3680 continue;
3681 }
3682 NC++;
3683 }
3684 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003685 if (isCommIntrinsic) {
3686 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3687 // operands are the commutative operands, and there might be more operands
3688 // after those.
3689 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003690 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00003691 std::vector<std::vector<TreePatternNode*> > Variants;
3692 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3693 Variants.push_back(ChildVariants[2]);
3694 Variants.push_back(ChildVariants[1]);
3695 for (unsigned i = 3; i != NC; ++i)
3696 Variants.push_back(ChildVariants[i]);
3697 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3698 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003699 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003700 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003701 }
3702}
3703
3704
3705// GenerateVariants - Generate variants. For example, commutative patterns can
3706// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003707void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003708 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003709
Chris Lattner8cab0212008-01-05 22:25:12 +00003710 // Loop over all of the patterns we've collected, checking to see if we can
3711 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003712 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003713 // the .td file having to contain tons of variants of instructions.
3714 //
3715 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3716 // intentionally do not reconsider these. Any variants of added patterns have
3717 // already been added.
3718 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00003719 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003720 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003721 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003722 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003723 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003724 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003725 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00003726 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003727 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003728
3729 assert(!Variants.empty() && "Must create at least original variant!");
3730 Variants.erase(Variants.begin()); // Remove the original pattern.
3731
3732 if (Variants.empty()) // No variants for this pattern.
3733 continue;
3734
Chris Lattner34822f62009-08-23 04:44:11 +00003735 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00003736 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00003737 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003738
3739 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3740 TreePatternNode *Variant = Variants[v];
3741
Chris Lattner34822f62009-08-23 04:44:11 +00003742 DEBUG(errs() << " VAR#" << v << ": ";
3743 Variant->dump();
3744 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003745
Chris Lattner8cab0212008-01-05 22:25:12 +00003746 // Scan to see if an instruction or explicit pattern already matches this.
3747 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003748 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003749 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003750 if (PatternsToMatch[i].getPredicates() !=
3751 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00003752 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003753 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003754 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3755 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003756 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003757 AlreadyExists = true;
3758 break;
3759 }
3760 }
3761 // If we already have it, ignore the variant.
3762 if (AlreadyExists) continue;
3763
3764 // Otherwise, add it to the list of patterns we have.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003765 PatternsToMatch.emplace_back(
3766 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3767 Variant, PatternsToMatch[i].getDstPattern(),
3768 PatternsToMatch[i].getDstRegs(),
3769 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
Chris Lattner8cab0212008-01-05 22:25:12 +00003770 }
3771
Chris Lattner34822f62009-08-23 04:44:11 +00003772 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003773 }
3774}