blob: 8bd0dc3b4b247c0212eeacb9abd9117eec83dc23 [file] [log] [blame]
Chris Lattnerab3242f2008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerab3242f2008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner8cab0212008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner78ac0742008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000016#include "llvm/ADT/STLExtras.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000017#include "llvm/ADT/StringExtras.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000018#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000019#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000020#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000021#include "llvm/TableGen/Error.h"
22#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000023#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000024#include <cstdio>
25#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000026using namespace llvm;
27
Chandler Carruthe96dd892014-04-21 22:55:11 +000028#define DEBUG_TYPE "dag-patterns"
29
Chris Lattner8cab0212008-01-05 22:25:12 +000030//===----------------------------------------------------------------------===//
Chris Lattnercabe0372010-03-15 06:00:16 +000031// EEVT::TypeSet Implementation
32//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +000033
Owen Anderson9f944592009-08-11 20:47:22 +000034static inline bool isInteger(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000035 return MVT(VT).isInteger();
Duncan Sands13237ac2008-06-06 12:08:01 +000036}
Owen Anderson9f944592009-08-11 20:47:22 +000037static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000038 return MVT(VT).isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000039}
Owen Anderson9f944592009-08-11 20:47:22 +000040static inline bool isVector(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000041 return MVT(VT).isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000042}
Chris Lattner6d765eb2010-03-19 17:41:26 +000043static inline bool isScalar(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000044 return !MVT(VT).isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000045}
Duncan Sands13237ac2008-06-06 12:08:01 +000046
Chris Lattnercabe0372010-03-15 06:00:16 +000047EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
48 if (VT == MVT::iAny)
49 EnforceInteger(TP);
50 else if (VT == MVT::fAny)
51 EnforceFloatingPoint(TP);
52 else if (VT == MVT::vAny)
53 EnforceVector(TP);
54 else {
55 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
Ramkumar Ramachandra75a4f352015-01-22 20:14:38 +000056 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
Chris Lattnercabe0372010-03-15 06:00:16 +000057 TypeVec.push_back(VT);
58 }
Chris Lattner8cab0212008-01-05 22:25:12 +000059}
60
Chris Lattnercabe0372010-03-15 06:00:16 +000061
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000062EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
Chris Lattnercabe0372010-03-15 06:00:16 +000063 assert(!VTList.empty() && "empty list?");
64 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +000065
Chris Lattnercabe0372010-03-15 06:00:16 +000066 if (!VTList.empty())
67 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
68 VTList[0] != MVT::fAny);
Jim Grosbach65586fe2010-12-21 16:16:00 +000069
Chris Lattner4a5f7be2010-03-27 20:32:26 +000070 // Verify no duplicates.
Chris Lattnercabe0372010-03-15 06:00:16 +000071 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner4a5f7be2010-03-27 20:32:26 +000072 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner8cab0212008-01-05 22:25:12 +000073}
74
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000075/// FillWithPossibleTypes - Set to all legal types and return true, only valid
76/// on completely unknown type sets.
Chris Lattner6d765eb2010-03-19 17:41:26 +000077bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
78 bool (*Pred)(MVT::SimpleValueType),
79 const char *PredicateName) {
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000080 assert(isCompletelyUnknown());
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000081 ArrayRef<MVT::SimpleValueType> LegalTypes =
Chris Lattner6d765eb2010-03-19 17:41:26 +000082 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +000083
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000084 if (TP.hasError())
85 return false;
86
Craig Topper306cb122015-11-22 20:46:24 +000087 for (MVT::SimpleValueType VT : LegalTypes)
88 if (!Pred || Pred(VT))
89 TypeVec.push_back(VT);
Chris Lattner6d765eb2010-03-19 17:41:26 +000090
91 // If we have nothing that matches the predicate, bail out.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000092 if (TypeVec.empty()) {
Chris Lattner6d765eb2010-03-19 17:41:26 +000093 TP.error("Type inference contradiction found, no " +
Jim Grosbach65586fe2010-12-21 16:16:00 +000094 std::string(PredicateName) + " types found");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000095 return false;
96 }
Chris Lattner6d765eb2010-03-19 17:41:26 +000097 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
99
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000103
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000104 return true;
105}
Chris Lattnercabe0372010-03-15 06:00:16 +0000106
107/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108/// integer value type.
109bool EEVT::TypeSet::hasIntegerTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000110 return std::any_of(TypeVec.begin(), TypeVec.end(), isInteger);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000111}
Chris Lattnercabe0372010-03-15 06:00:16 +0000112
113/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
114/// a floating point value type.
115bool EEVT::TypeSet::hasFloatingPointTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000116 return std::any_of(TypeVec.begin(), TypeVec.end(), isFloatingPoint);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000117}
Chris Lattnercabe0372010-03-15 06:00:16 +0000118
Craig Topper74169dc2014-01-28 04:49:01 +0000119/// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
120bool EEVT::TypeSet::hasScalarTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000121 return std::any_of(TypeVec.begin(), TypeVec.end(), isScalar);
Craig Topper74169dc2014-01-28 04:49:01 +0000122}
123
Chris Lattnercabe0372010-03-15 06:00:16 +0000124/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
125/// value type.
126bool EEVT::TypeSet::hasVectorTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000127 return std::any_of(TypeVec.begin(), TypeVec.end(), isVector);
Chris Lattner8cab0212008-01-05 22:25:12 +0000128}
Bob Wilson2cd5da82009-08-11 01:14:02 +0000129
Chris Lattnercabe0372010-03-15 06:00:16 +0000130
131std::string EEVT::TypeSet::getName() const {
Chris Lattnerda5b4ad2010-03-19 01:14:27 +0000132 if (TypeVec.empty()) return "<empty>";
Jim Grosbach65586fe2010-12-21 16:16:00 +0000133
Chris Lattnercabe0372010-03-15 06:00:16 +0000134 std::string Result;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000135
Chris Lattnercabe0372010-03-15 06:00:16 +0000136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
137 std::string VTName = llvm::getEnumName(TypeVec[i]);
138 // Strip off MVT:: prefix if present.
139 if (VTName.substr(0,5) == "MVT::")
140 VTName = VTName.substr(5);
141 if (i) Result += ':';
142 Result += VTName;
143 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000144
Chris Lattnercabe0372010-03-15 06:00:16 +0000145 if (TypeVec.size() == 1)
146 return Result;
147 return "{" + Result + "}";
Bob Wilson2cd5da82009-08-11 01:14:02 +0000148}
Chris Lattnercabe0372010-03-15 06:00:16 +0000149
150/// MergeInTypeInfo - This merges in type information from the specified
151/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000152/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattnercabe0372010-03-15 06:00:16 +0000153bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000154 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattnercabe0372010-03-15 06:00:16 +0000155 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000156
Chris Lattnercabe0372010-03-15 06:00:16 +0000157 if (isCompletelyUnknown()) {
158 *this = InVT;
159 return true;
160 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000161
Craig Topperd2177de2015-11-23 07:19:08 +0000162 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000163
Chris Lattnercabe0372010-03-15 06:00:16 +0000164 // Handle the abstract cases, seeing if we can resolve them better.
165 switch (TypeVec[0]) {
166 default: break;
167 case MVT::iPTR:
168 case MVT::iPTRAny:
169 if (InVT.hasIntegerTypes()) {
170 EEVT::TypeSet InCopy(InVT);
171 InCopy.EnforceInteger(TP);
172 InCopy.EnforceScalar(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000173
Chris Lattnercabe0372010-03-15 06:00:16 +0000174 if (InCopy.isConcrete()) {
175 // If the RHS has one integer type, upgrade iPTR to i32.
176 TypeVec[0] = InVT.TypeVec[0];
177 return true;
178 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000179
Chris Lattnercabe0372010-03-15 06:00:16 +0000180 // If the input has multiple scalar integers, this doesn't add any info.
181 if (!InCopy.isCompletelyUnknown())
182 return false;
183 }
184 break;
185 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000186
Chris Lattnercabe0372010-03-15 06:00:16 +0000187 // If the input constraint is iAny/iPTR and this is an integer type list,
188 // remove non-integer types from the list.
189 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
190 hasIntegerTypes()) {
191 bool MadeChange = EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000192
Chris Lattnercabe0372010-03-15 06:00:16 +0000193 // If we're merging in iPTR/iPTRAny and the node currently has a list of
194 // multiple different integer types, replace them with a single iPTR.
195 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
196 TypeVec.size() != 1) {
Craig Topper4856c812015-11-24 08:20:41 +0000197 TypeVec.assign(1, InVT.TypeVec[0]);
Chris Lattnercabe0372010-03-15 06:00:16 +0000198 MadeChange = true;
199 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000200
Chris Lattnercabe0372010-03-15 06:00:16 +0000201 return MadeChange;
202 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000203
Chris Lattnercabe0372010-03-15 06:00:16 +0000204 // If this is a type list and the RHS is a typelist as well, eliminate entries
205 // from this list that aren't in the other one.
Chris Lattnercabe0372010-03-15 06:00:16 +0000206 TypeSet InputSet(*this);
207
Craig Topperfef745c2015-11-24 08:20:42 +0000208 TypeVec.clear();
209 std::set_intersection(InputSet.TypeVec.begin(), InputSet.TypeVec.end(),
210 InVT.TypeVec.begin(), InVT.TypeVec.end(),
211 std::back_inserter(TypeVec));
Jim Grosbach65586fe2010-12-21 16:16:00 +0000212
Craig Topperfef745c2015-11-24 08:20:42 +0000213 // If the intersection is the same size as the original set then we're done.
214 if (TypeVec.size() == InputSet.TypeVec.size())
215 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000216
Chris Lattnercabe0372010-03-15 06:00:16 +0000217 // If we removed all of our types, we have a type contradiction.
218 if (!TypeVec.empty())
Craig Topperfef745c2015-11-24 08:20:42 +0000219 return true;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000220
Chris Lattnercabe0372010-03-15 06:00:16 +0000221 // FIXME: Really want an SMLoc here!
222 TP.error("Type inference contradiction found, merging '" +
223 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000224 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000225}
226
227/// EnforceInteger - Remove all non-integer types from this set.
228bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000229 if (TP.hasError())
230 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000231 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000232 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000233 return FillWithPossibleTypes(TP, isInteger, "integer");
Craig Topperd2177de2015-11-23 07:19:08 +0000234
Chris Lattnercabe0372010-03-15 06:00:16 +0000235 if (!hasFloatingPointTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000236 return false;
237
238 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000239
Chris Lattnercabe0372010-03-15 06:00:16 +0000240 // Filter out all the fp types.
Craig Topperde2d7592015-11-23 07:19:10 +0000241 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
242 std::not1(std::ptr_fun(isInteger))),
243 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000244
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000245 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000246 TP.error("Type inference contradiction found, '" +
247 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000248 return false;
249 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000250 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000251}
252
253/// EnforceFloatingPoint - Remove all integer types from this set.
254bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000255 if (TP.hasError())
256 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000257 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000258 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000259 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
260
Chris Lattnercabe0372010-03-15 06:00:16 +0000261 if (!hasIntegerTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000262 return false;
263
264 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000265
Craig Topperde2d7592015-11-23 07:19:10 +0000266 // Filter out all the integer types.
267 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
268 std::not1(std::ptr_fun(isFloatingPoint))),
269 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000270
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000271 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000272 TP.error("Type inference contradiction found, '" +
273 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000274 return false;
275 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000276 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000277}
278
279/// EnforceScalar - Remove all vector types from this.
280bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000281 if (TP.hasError())
282 return false;
283
Chris Lattnercabe0372010-03-15 06:00:16 +0000284 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000285 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000286 return FillWithPossibleTypes(TP, isScalar, "scalar");
287
Chris Lattnercabe0372010-03-15 06:00:16 +0000288 if (!hasVectorTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000289 return false;
290
291 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000292
Chris Lattnercabe0372010-03-15 06:00:16 +0000293 // Filter out all the vector types.
Craig Topperde2d7592015-11-23 07:19:10 +0000294 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
295 std::not1(std::ptr_fun(isScalar))),
296 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000297
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000298 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000299 TP.error("Type inference contradiction found, '" +
300 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000301 return false;
302 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000303 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000304}
305
306/// EnforceVector - Remove all vector types from this.
307bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000308 if (TP.hasError())
309 return false;
310
Chris Lattner6d765eb2010-03-19 17:41:26 +0000311 // If we know nothing, then get the full set.
312 if (TypeVec.empty())
313 return FillWithPossibleTypes(TP, isVector, "vector");
314
Chris Lattnercabe0372010-03-15 06:00:16 +0000315 TypeSet InputSet(*this);
316 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000317
Chris Lattnercabe0372010-03-15 06:00:16 +0000318 // Filter out all the scalar types.
Craig Topperde2d7592015-11-23 07:19:10 +0000319 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
320 std::not1(std::ptr_fun(isVector))),
321 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000322
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000323 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000324 TP.error("Type inference contradiction found, '" +
325 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000326 return false;
327 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000328 return MadeChange;
329}
330
331
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000332
Craig Topper74169dc2014-01-28 04:49:01 +0000333/// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000334/// this should be based on the element type. Update this and other based on
Craig Topper74169dc2014-01-28 04:49:01 +0000335/// this information.
Chris Lattnercabe0372010-03-15 06:00:16 +0000336bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000337 if (TP.hasError())
338 return false;
339
Chris Lattnercabe0372010-03-15 06:00:16 +0000340 // Both operands must be integer or FP, but we don't care which.
341 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000342
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000343 if (isCompletelyUnknown())
344 MadeChange = FillWithPossibleTypes(TP);
345
346 if (Other.isCompletelyUnknown())
347 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000348
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000349 // If one side is known to be integer or known to be FP but the other side has
350 // no information, get at least the type integrality info in there.
351 if (!hasFloatingPointTypes())
352 MadeChange |= Other.EnforceInteger(TP);
353 else if (!hasIntegerTypes())
354 MadeChange |= Other.EnforceFloatingPoint(TP);
355 if (!Other.hasFloatingPointTypes())
356 MadeChange |= EnforceInteger(TP);
357 else if (!Other.hasIntegerTypes())
358 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000359
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000360 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
361 "Should have a type list now");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000362
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000363 // If one contains vectors but the other doesn't pull vectors out.
364 if (!hasVectorTypes())
365 MadeChange |= Other.EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000366 else if (!hasScalarTypes())
367 MadeChange |= Other.EnforceVector(TP);
Craig Topper6dbcb942014-01-25 05:17:38 +0000368 if (!Other.hasVectorTypes())
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000369 MadeChange |= EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000370 else if (!Other.hasScalarTypes())
371 MadeChange |= EnforceVector(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000372
Craig Topper74169dc2014-01-28 04:49:01 +0000373 // This code does not currently handle nodes which have multiple types,
374 // where some types are integer, and some are fp. Assert that this is not
375 // the case.
376 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
377 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
378 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
379
380 if (TP.hasError())
381 return false;
382
Craig Topper7bbd37b2015-03-10 03:25:07 +0000383 // Okay, find the smallest type from current set and remove anything the
384 // same or smaller from the other set. We need to ensure that the scalar
385 // type size is smaller than the scalar size of the smallest type. For
386 // vectors, we also need to make sure that the total size is no larger than
387 // the size of the smallest type.
Craig Topper5712d462015-11-24 08:20:47 +0000388 {
389 TypeSet InputSet(Other);
390 MVT Smallest = TypeVec[0];
391 auto I = std::remove_if(Other.TypeVec.begin(), Other.TypeVec.end(),
392 [Smallest](MVT OtherVT) {
393 // Don't compare vector and non-vector types.
394 if (OtherVT.isVector() != Smallest.isVector())
395 return false;
396 // The getSizeInBits() check here is only needed for vectors, but is
397 // a subset of the scalar check for scalars so no need to qualify.
398 return OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits()||
399 OtherVT.getSizeInBits() < Smallest.getSizeInBits();
400 });
401 MadeChange |= I != Other.TypeVec.end(); // If we're about to remove types.
402 Other.TypeVec.erase(I, Other.TypeVec.end());
Craig Topper74169dc2014-01-28 04:49:01 +0000403
Craig Topper5712d462015-11-24 08:20:47 +0000404 if (Other.TypeVec.empty()) {
405 TP.error("Type inference contradiction found, '" + InputSet.getName() +
406 "' has nothing larger than '" + getName() +"'!");
407 return false;
408 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000409 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000410
Craig Topper7bbd37b2015-03-10 03:25:07 +0000411 // Okay, find the largest type from the other set and remove anything the
412 // same or smaller from the current set. We need to ensure that the scalar
413 // type size is larger than the scalar size of the largest type. For
414 // vectors, we also need to make sure that the total size is no smaller than
415 // the size of the largest type.
Craig Topper5712d462015-11-24 08:20:47 +0000416 {
417 TypeSet InputSet(*this);
418 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
419 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
420 [Largest](MVT OtherVT) {
421 // Don't compare vector and non-vector types.
422 if (OtherVT.isVector() != Largest.isVector())
423 return false;
424 return OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
425 OtherVT.getSizeInBits() > Largest.getSizeInBits();
426 });
427 MadeChange |= I != TypeVec.end(); // If we're about to remove types.
428 TypeVec.erase(I, TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000429
Craig Topper5712d462015-11-24 08:20:47 +0000430 if (TypeVec.empty()) {
431 TP.error("Type inference contradiction found, '" + InputSet.getName() +
432 "' has nothing smaller than '" + Other.getName() +"'!");
433 return false;
434 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000435 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000436
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000437 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000438}
439
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000440/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000441/// whose element is specified by VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000442bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
443 TreePattern &TP) {
444 bool MadeChange = false;
445
446 MadeChange |= EnforceVector(TP);
447
448 TypeSet InputSet(*this);
449
450 // Filter out all the types which don't have the right element type.
Craig Topper5712d462015-11-24 08:20:47 +0000451 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
452 [VT](MVT VVT) {
453 return VVT.getVectorElementType().SimpleTy != VT;
454 });
455 MadeChange |= I != TypeVec.end();
456 TypeVec.erase(I, TypeVec.end());
Craig Topper0be34582015-03-05 07:11:34 +0000457
458 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
459 TP.error("Type inference contradiction found, forcing '" +
Craig Topper5712d462015-11-24 08:20:47 +0000460 InputSet.getName() + "' to have a vector element of type " +
461 getEnumName(VT));
Craig Topper0be34582015-03-05 07:11:34 +0000462 return false;
463 }
464
465 return MadeChange;
466}
467
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000468/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Craig Topper0be34582015-03-05 07:11:34 +0000469/// whose element is specified by VTOperand.
Chris Lattner57ebf632010-03-24 00:01:16 +0000470bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000471 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000472 if (TP.hasError())
473 return false;
474
Chris Lattner57ebf632010-03-24 00:01:16 +0000475 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000476 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000477 MadeChange |= EnforceVector(TP);
478 MadeChange |= VTOperand.EnforceScalar(TP);
479
480 // If we know the vector type, it forces the scalar to agree.
481 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000482 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000483 IVT = IVT.getVectorElementType();
Craig Topperdbfcc102015-11-24 08:20:44 +0000484 return MadeChange || VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000485 }
486
487 // If the scalar type is known, filter out vector types whose element types
488 // disagree.
489 if (!VTOperand.isConcrete())
490 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000491
Chris Lattner57ebf632010-03-24 00:01:16 +0000492 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000493
Craig Topper16f1cbd2015-11-24 08:20:45 +0000494 MadeChange |= EnforceVectorEltTypeIs(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000495
Chris Lattnercabe0372010-03-15 06:00:16 +0000496 return MadeChange;
497}
498
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000499/// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
David Greene127fd1d2011-01-24 20:53:18 +0000500/// vector type specified by VTOperand.
501bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
502 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000503 if (TP.hasError())
504 return false;
505
David Greene127fd1d2011-01-24 20:53:18 +0000506 // "This" must be a vector and "VTOperand" must be a vector.
507 bool MadeChange = false;
508 MadeChange |= EnforceVector(TP);
509 MadeChange |= VTOperand.EnforceVector(TP);
510
Craig Topper6e1faaf2014-01-25 17:40:33 +0000511 // If one side is known to be integer or known to be FP but the other side has
512 // no information, get at least the type integrality info in there.
513 if (!hasFloatingPointTypes())
514 MadeChange |= VTOperand.EnforceInteger(TP);
515 else if (!hasIntegerTypes())
516 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
517 if (!VTOperand.hasFloatingPointTypes())
518 MadeChange |= EnforceInteger(TP);
519 else if (!VTOperand.hasIntegerTypes())
520 MadeChange |= EnforceFloatingPoint(TP);
521
522 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
523 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000524
525 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000526 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000527 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000528 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000529 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000530 IVT = IVT.getVectorElementType();
531
Craig Topper95198f42013-09-25 06:37:18 +0000532 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000533 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000534
535 // Only keep types that have less elements than VTOperand.
536 TypeSet InputSet(VTOperand);
537
Craig Topper5712d462015-11-24 08:20:47 +0000538 auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(),
539 [NumElems](MVT VVT) {
540 return VVT.getVectorNumElements() >= NumElems;
541 });
542 MadeChange |= I != VTOperand.TypeVec.end();
543 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
544
Craig Topper6e1faaf2014-01-25 17:40:33 +0000545 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
546 TP.error("Type inference contradiction found, forcing '" +
547 InputSet.getName() + "' to have less vector elements than '" +
548 getName() + "'");
549 return false;
550 }
David Greene127fd1d2011-01-24 20:53:18 +0000551 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000552 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000553 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000554 IVT = IVT.getVectorElementType();
555
Craig Topper95198f42013-09-25 06:37:18 +0000556 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000557 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000558
559 // Only keep types that have more elements than 'this'.
560 TypeSet InputSet(*this);
561
Craig Topper5712d462015-11-24 08:20:47 +0000562 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
563 [NumElems](MVT VVT) {
564 return VVT.getVectorNumElements() <= NumElems;
565 });
566 MadeChange |= I != TypeVec.end();
567 TypeVec.erase(I, TypeVec.end());
568
Craig Topper6e1faaf2014-01-25 17:40:33 +0000569 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
570 TP.error("Type inference contradiction found, forcing '" +
571 InputSet.getName() + "' to have more vector elements than '" +
572 VTOperand.getName() + "'");
573 return false;
574 }
David Greene127fd1d2011-01-24 20:53:18 +0000575 }
576
577 return MadeChange;
578}
579
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000580/// EnforceVectorSameNumElts - 'this' is now constrained to
Craig Topper0be34582015-03-05 07:11:34 +0000581/// be a vector with same num elements as VTOperand.
582bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
583 TreePattern &TP) {
584 if (TP.hasError())
585 return false;
586
587 // "This" must be a vector and "VTOperand" must be a vector.
588 bool MadeChange = false;
589 MadeChange |= EnforceVector(TP);
590 MadeChange |= VTOperand.EnforceVector(TP);
591
592 // If we know one of the vector types, it forces the other type to agree.
593 if (isConcrete()) {
594 MVT IVT = getConcrete();
595 unsigned NumElems = IVT.getVectorNumElements();
596
597 // Only keep types that have same elements as VTOperand.
598 TypeSet InputSet(VTOperand);
599
Craig Topper5712d462015-11-24 08:20:47 +0000600 auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(),
601 [NumElems](MVT VVT) {
602 return VVT.getVectorNumElements() != NumElems;
603 });
604 MadeChange |= I != VTOperand.TypeVec.end();
605 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
606
Craig Topper0be34582015-03-05 07:11:34 +0000607 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
608 TP.error("Type inference contradiction found, forcing '" +
609 InputSet.getName() + "' to have same number elements as '" +
610 getName() + "'");
611 return false;
612 }
613 } else if (VTOperand.isConcrete()) {
614 MVT IVT = VTOperand.getConcrete();
615 unsigned NumElems = IVT.getVectorNumElements();
616
617 // Only keep types that have same elements as 'this'.
618 TypeSet InputSet(*this);
619
Craig Topper5712d462015-11-24 08:20:47 +0000620 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
621 [NumElems](MVT VVT) {
622 return VVT.getVectorNumElements() != NumElems;
623 });
624 MadeChange |= I != TypeVec.end();
625 TypeVec.erase(I, TypeVec.end());
626
Craig Topper0be34582015-03-05 07:11:34 +0000627 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
628 TP.error("Type inference contradiction found, forcing '" +
629 InputSet.getName() + "' to have same number elements than '" +
630 VTOperand.getName() + "'");
631 return false;
632 }
633 }
634
635 return MadeChange;
636}
637
Chris Lattnercabe0372010-03-15 06:00:16 +0000638//===----------------------------------------------------------------------===//
639// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000640
Scott Michel94420742008-03-05 17:49:05 +0000641/// Dependent variable map for CodeGenDAGPattern variant generation
642typedef std::map<std::string, int> DepVarMap;
643
Chris Lattner514e2922011-04-17 21:38:24 +0000644static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000645 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000646 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000647 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000648 } else {
649 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
650 FindDepVarsOf(N->getChild(i), DepMap);
651 }
652}
Chris Lattner514e2922011-04-17 21:38:24 +0000653
654/// Find dependent variables within child patterns
655static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000656 DepVarMap depcounts;
657 FindDepVarsOf(N, depcounts);
Craig Topper306cb122015-11-22 20:46:24 +0000658 for (const std::pair<std::string, int> &Pair : depcounts) {
659 if (Pair.second > 1)
660 DepVars.insert(Pair.first);
Scott Michel94420742008-03-05 17:49:05 +0000661 }
662}
663
Daniel Dunbarba66a812010-10-08 02:07:22 +0000664#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000665/// Dump the dependent variable set:
666static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000667 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000668 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000669 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000670 DEBUG(errs() << "[ ");
Craig Topper306cb122015-11-22 20:46:24 +0000671 for (const std::string &DepVar : DepVars) {
672 DEBUG(errs() << DepVar << " ");
Scott Michel94420742008-03-05 17:49:05 +0000673 }
Chris Lattner34822f62009-08-23 04:44:11 +0000674 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000675 }
676}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000677#endif
678
Chris Lattner514e2922011-04-17 21:38:24 +0000679
680//===----------------------------------------------------------------------===//
681// TreePredicateFn Implementation
682//===----------------------------------------------------------------------===//
683
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000684/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
685TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
686 assert((getPredCode().empty() || getImmCode().empty()) &&
687 ".td file corrupt: can't have a node predicate *and* an imm predicate");
688}
689
Chris Lattner514e2922011-04-17 21:38:24 +0000690std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000691 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000692}
693
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000694std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000695 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000696}
697
Chris Lattner514e2922011-04-17 21:38:24 +0000698
699/// isAlwaysTrue - Return true if this is a noop predicate.
700bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000701 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000702}
703
704/// Return the name to use in the generated code to reference this, this is
705/// "Predicate_foo" if from a pattern fragment "foo".
706std::string TreePredicateFn::getFnName() const {
707 return "Predicate_" + PatFragRec->getRecord()->getName();
708}
709
710/// getCodeToRunOnSDNode - Return the code for the function body that
711/// evaluates this predicate. The argument is expected to be in "Node",
712/// not N. This handles casting and conversion to a concrete node type as
713/// appropriate.
714std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000715 // Handle immediate predicates first.
716 std::string ImmCode = getImmCode();
717 if (!ImmCode.empty()) {
718 std::string Result =
719 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000720 return Result + ImmCode;
721 }
722
723 // Handle arbitrary node predicates.
724 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000725 std::string ClassName;
726 if (PatFragRec->getOnlyTree()->isLeaf())
727 ClassName = "SDNode";
728 else {
729 Record *Op = PatFragRec->getOnlyTree()->getOperator();
730 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
731 }
732 std::string Result;
733 if (ClassName == "SDNode")
734 Result = " SDNode *N = Node;\n";
735 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000736 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000737
738 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000739}
740
Chris Lattner8cab0212008-01-05 22:25:12 +0000741//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000742// PatternToMatch implementation
743//
744
Chris Lattner05925fe2010-03-29 01:40:38 +0000745
746/// getPatternSize - Return the 'size' of this pattern. We want to match large
747/// patterns before small ones. This is used to determine the size of a
748/// pattern.
749static unsigned getPatternSize(const TreePatternNode *P,
750 const CodeGenDAGPatterns &CGP) {
751 unsigned Size = 3; // The node itself.
752 // If the root node is a ConstantSDNode, increases its size.
753 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000754 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000755 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000756
Chris Lattner05925fe2010-03-29 01:40:38 +0000757 // FIXME: This is a hack to statically increase the priority of patterns
758 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
759 // Later we can allow complexity / cost for each pattern to be (optionally)
760 // specified. To get best possible pattern match we'll need to dynamically
761 // calculate the complexity of all patterns a dag can potentially map to.
762 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000763 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000764 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000765
Tim Northoverc807a172014-05-20 11:52:46 +0000766 // We don't want to count any children twice, so return early.
767 return Size;
768 }
769
Chris Lattner05925fe2010-03-29 01:40:38 +0000770 // If this node has some predicate function that must match, it adds to the
771 // complexity of this node.
772 if (!P->getPredicateFns().empty())
773 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000774
Chris Lattner05925fe2010-03-29 01:40:38 +0000775 // Count children in the count if they are also nodes.
776 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
777 TreePatternNode *Child = P->getChild(i);
778 if (!Child->isLeaf() && Child->getNumTypes() &&
779 Child->getType(0) != MVT::Other)
780 Size += getPatternSize(Child, CGP);
781 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000782 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000783 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
784 else if (Child->getComplexPatternInfo(CGP))
785 Size += getPatternSize(Child, CGP);
786 else if (!Child->getPredicateFns().empty())
787 ++Size;
788 }
789 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000790
Chris Lattner05925fe2010-03-29 01:40:38 +0000791 return Size;
792}
793
794/// Compute the complexity metric for the input pattern. This roughly
795/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000796int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000797getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
798 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
799}
800
801
Dan Gohman49e19e92008-08-22 00:20:26 +0000802/// getPredicateCheck - Return a single string containing all of this
803/// pattern's predicates concatenated with "&&" operators.
804///
805std::string PatternToMatch::getPredicateCheck() const {
806 std::string PredicateCheck;
Craig Topperef0578a2015-06-02 04:15:51 +0000807 for (Init *I : Predicates->getValues()) {
808 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000809 Record *Def = Pred->getDef();
810 if (!Def->isSubClassOf("Predicate")) {
811#ifndef NDEBUG
812 Def->dump();
813#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000814 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000815 }
816 if (!PredicateCheck.empty())
817 PredicateCheck += " && ";
818 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
819 }
820 }
821
822 return PredicateCheck;
823}
824
825//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000826// SDTypeConstraint implementation
827//
828
829SDTypeConstraint::SDTypeConstraint(Record *R) {
830 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000831
Chris Lattner8cab0212008-01-05 22:25:12 +0000832 if (R->isSubClassOf("SDTCisVT")) {
833 ConstraintType = SDTCisVT;
834 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000835 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000836 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000837
Chris Lattner8cab0212008-01-05 22:25:12 +0000838 } else if (R->isSubClassOf("SDTCisPtrTy")) {
839 ConstraintType = SDTCisPtrTy;
840 } else if (R->isSubClassOf("SDTCisInt")) {
841 ConstraintType = SDTCisInt;
842 } else if (R->isSubClassOf("SDTCisFP")) {
843 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000844 } else if (R->isSubClassOf("SDTCisVec")) {
845 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000846 } else if (R->isSubClassOf("SDTCisSameAs")) {
847 ConstraintType = SDTCisSameAs;
848 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
849 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
850 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000851 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000852 R->getValueAsInt("OtherOperandNum");
853 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
854 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000855 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000856 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000857 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
858 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000859 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000860 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
861 ConstraintType = SDTCisSubVecOfVec;
862 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
863 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000864 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
865 ConstraintType = SDTCVecEltisVT;
866 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
867 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
868 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
869 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
870 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
871 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
872 "as SDTCVecEltisVT");
873 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
874 ConstraintType = SDTCisSameNumEltsAs;
875 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
876 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000877 } else {
James Y Knighte452e272015-05-11 22:17:13 +0000878 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +0000879 }
880}
881
882/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000883/// N, and the result number in ResNo.
884static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
885 const SDNodeInfo &NodeInfo,
886 unsigned &ResNo) {
887 unsigned NumResults = NodeInfo.getNumResults();
888 if (OpNo < NumResults) {
889 ResNo = OpNo;
890 return N;
891 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000892
Chris Lattner2db7aba2010-03-19 21:56:21 +0000893 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000894
Chris Lattner2db7aba2010-03-19 21:56:21 +0000895 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +0000896 std::string S;
897 raw_string_ostream OS(S);
898 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000899 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +0000900 N->print(OS);
901 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +0000902 }
903
Chris Lattner2db7aba2010-03-19 21:56:21 +0000904 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000905}
906
907/// ApplyTypeConstraint - Given a node in a pattern, apply this type
908/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000909/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000910bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
911 const SDNodeInfo &NodeInfo,
912 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000913 if (TP.hasError())
914 return false;
915
Chris Lattner2db7aba2010-03-19 21:56:21 +0000916 unsigned ResNo = 0; // The result number being referenced.
917 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000918
Chris Lattner8cab0212008-01-05 22:25:12 +0000919 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000920 case SDTCisVT:
921 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000922 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000923 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000924 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000925 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000926 case SDTCisInt:
927 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000928 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000929 case SDTCisFP:
930 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000931 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000932 case SDTCisVec:
933 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000934 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000935 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000936 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000937 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000938 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +0000939 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
940 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000941 }
942 case SDTCisVTSmallerThanOp: {
943 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
944 // have an integer type that is smaller than the VT.
945 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +0000946 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +0000947 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000948 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000949 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000950 return false;
951 }
Owen Anderson9f944592009-08-11 20:47:22 +0000952 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +0000953 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000954
Chris Lattner38c99662010-03-24 00:06:46 +0000955 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000956
Chris Lattner2db7aba2010-03-19 21:56:21 +0000957 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000958 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000959 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
960 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +0000961
Chris Lattner38c99662010-03-24 00:06:46 +0000962 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000963 }
964 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000965 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000966 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000967 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
968 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000969 return NodeToApply->getExtType(ResNo).
970 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000971 }
Nate Begeman17bedbc2008-02-09 01:37:05 +0000972 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000973 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +0000974 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000975 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
976 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000977
Chris Lattner57ebf632010-03-24 00:01:16 +0000978 // Filter vector types out of VecOperand that don't have the right element
979 // type.
980 return VecOperand->getExtType(VResNo).
981 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +0000982 }
David Greene127fd1d2011-01-24 20:53:18 +0000983 case SDTCisSubVecOfVec: {
984 unsigned VResNo = 0;
985 TreePatternNode *BigVecOperand =
986 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
987 VResNo);
988
989 // Filter vector types out of BigVecOperand that don't have the
990 // right subvector type.
991 return BigVecOperand->getExtType(VResNo).
992 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
993 }
Craig Topper0be34582015-03-05 07:11:34 +0000994 case SDTCVecEltisVT: {
995 return NodeToApply->getExtType(ResNo).
996 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
997 }
998 case SDTCisSameNumEltsAs: {
999 unsigned OResNo = 0;
1000 TreePatternNode *OtherNode =
1001 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1002 N, NodeInfo, OResNo);
1003 return OtherNode->getExtType(OResNo).
1004 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1005 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001006 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001007 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001008}
1009
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001010// Update the node type to match an instruction operand or result as specified
1011// in the ins or outs lists on the instruction definition. Return true if the
1012// type was actually changed.
1013bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1014 Record *Operand,
1015 TreePattern &TP) {
1016 // The 'unknown' operand indicates that types should be inferred from the
1017 // context.
1018 if (Operand->isSubClassOf("unknown_class"))
1019 return false;
1020
1021 // The Operand class specifies a type directly.
1022 if (Operand->isSubClassOf("Operand"))
1023 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1024 TP);
1025
1026 // PointerLikeRegClass has a type that is determined at runtime.
1027 if (Operand->isSubClassOf("PointerLikeRegClass"))
1028 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1029
1030 // Both RegisterClass and RegisterOperand operands derive their types from a
1031 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001032 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001033 if (Operand->isSubClassOf("RegisterClass"))
1034 RC = Operand;
1035 else if (Operand->isSubClassOf("RegisterOperand"))
1036 RC = Operand->getValueAsDef("RegClass");
1037
1038 assert(RC && "Unknown operand type");
1039 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1040 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1041}
1042
1043
Chris Lattner8cab0212008-01-05 22:25:12 +00001044//===----------------------------------------------------------------------===//
1045// SDNodeInfo implementation
1046//
1047SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1048 EnumName = R->getValueAsString("Opcode");
1049 SDClassName = R->getValueAsString("SDClass");
1050 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1051 NumResults = TypeProfile->getValueAsInt("NumResults");
1052 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001053
Chris Lattner8cab0212008-01-05 22:25:12 +00001054 // Parse the properties.
1055 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001056 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1057 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001058 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001059 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001060 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001061 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001062 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001063 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001064 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001065 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001066 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001067 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001068 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001069 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001070 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001071 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001072 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001073 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001074 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001075 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001076 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001077 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001078 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001079 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001080 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001081 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001082 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001083 }
1084 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001085
1086
Chris Lattner8cab0212008-01-05 22:25:12 +00001087 // Parse the type constraints.
1088 std::vector<Record*> ConstraintList =
1089 TypeProfile->getValueAsListOfDefs("Constraints");
1090 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1091}
1092
Chris Lattner99e53b32010-02-28 00:22:30 +00001093/// getKnownType - If the type constraints on this node imply a fixed type
1094/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001095/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001096MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001097 unsigned NumResults = getNumResults();
1098 assert(NumResults <= 1 &&
1099 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001100 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001101
Craig Topper306cb122015-11-22 20:46:24 +00001102 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001103 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001104 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001105 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001106
Craig Topper306cb122015-11-22 20:46:24 +00001107 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001108 default: break;
1109 case SDTypeConstraint::SDTCisVT:
Craig Topper306cb122015-11-22 20:46:24 +00001110 return Constraint.x.SDTCisVT_Info.VT;
Chris Lattner99e53b32010-02-28 00:22:30 +00001111 case SDTypeConstraint::SDTCisPtrTy:
1112 return MVT::iPTR;
1113 }
1114 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001115 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001116}
1117
Chris Lattner8cab0212008-01-05 22:25:12 +00001118//===----------------------------------------------------------------------===//
1119// TreePatternNode implementation
1120//
1121
1122TreePatternNode::~TreePatternNode() {
1123#if 0 // FIXME: implement refcounted tree nodes!
1124 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1125 delete getChild(i);
1126#endif
1127}
1128
Chris Lattnerf1447252010-03-19 21:37:09 +00001129static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1130 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001131 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001132 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001133
Chris Lattner2109cb42010-03-22 20:56:36 +00001134 if (Operator->isSubClassOf("Intrinsic"))
1135 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001136
Chris Lattnerf1447252010-03-19 21:37:09 +00001137 if (Operator->isSubClassOf("SDNode"))
1138 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001139
Chris Lattnerf1447252010-03-19 21:37:09 +00001140 if (Operator->isSubClassOf("PatFrag")) {
1141 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1142 // the forward reference case where one pattern fragment references another
1143 // before it is processed.
1144 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1145 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001146
Chris Lattnerf1447252010-03-19 21:37:09 +00001147 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001148 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001149 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001150 if (Tree)
1151 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1152 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001153 assert(Op && "Invalid Fragment");
1154 return GetNumNodeResults(Op, CDP);
1155 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001156
Chris Lattnerf1447252010-03-19 21:37:09 +00001157 if (Operator->isSubClassOf("Instruction")) {
1158 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001159
Craig Topper3a8eb892015-03-20 05:09:06 +00001160 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1161
1162 // Subtract any defaulted outputs.
1163 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1164 Record *OperandNode = InstInfo.Operands[i].Rec;
1165
1166 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1167 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1168 --NumDefsToAdd;
1169 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001170
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001171 // Add on one implicit def if it has a resolvable type.
1172 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1173 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001174 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001175 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001176
Chris Lattnerf1447252010-03-19 21:37:09 +00001177 if (Operator->isSubClassOf("SDNodeXForm"))
1178 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001179
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001180 if (Operator->isSubClassOf("ValueType"))
1181 return 1; // A type-cast of one result.
1182
Tim Northoverc807a172014-05-20 11:52:46 +00001183 if (Operator->isSubClassOf("ComplexPattern"))
1184 return 1;
1185
Chris Lattnerf1447252010-03-19 21:37:09 +00001186 Operator->dump();
James Y Knighte452e272015-05-11 22:17:13 +00001187 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001188}
1189
1190void TreePatternNode::print(raw_ostream &OS) const {
1191 if (isLeaf())
1192 OS << *getLeafValue();
1193 else
1194 OS << '(' << getOperator()->getName();
1195
1196 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1197 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001198
1199 if (!isLeaf()) {
1200 if (getNumChildren() != 0) {
1201 OS << " ";
1202 getChild(0)->print(OS);
1203 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1204 OS << ", ";
1205 getChild(i)->print(OS);
1206 }
1207 }
1208 OS << ")";
1209 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001210
Craig Topper306cb122015-11-22 20:46:24 +00001211 for (const TreePredicateFn &Pred : PredicateFns)
1212 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001213 if (TransformFn)
1214 OS << "<<X:" << TransformFn->getName() << ">>";
1215 if (!getName().empty())
1216 OS << ":$" << getName();
1217
1218}
1219void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001220 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001221}
1222
Scott Michel94420742008-03-05 17:49:05 +00001223/// isIsomorphicTo - Return true if this node is recursively
1224/// isomorphic to the specified node. For this comparison, the node's
1225/// entire state is considered. The assigned name is ignored, since
1226/// nodes with differing names are considered isomorphic. However, if
1227/// the assigned name is present in the dependent variable set, then
1228/// the assigned name is considered significant and the node is
1229/// isomorphic if the names match.
1230bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1231 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001232 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001233 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001234 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001235 getTransformFn() != N->getTransformFn())
1236 return false;
1237
1238 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001239 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1240 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001241 return ((DI->getDef() == NDI->getDef())
1242 && (DepVars.find(getName()) == DepVars.end()
1243 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001244 }
1245 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001246 return getLeafValue() == N->getLeafValue();
1247 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001248
Chris Lattner8cab0212008-01-05 22:25:12 +00001249 if (N->getOperator() != getOperator() ||
1250 N->getNumChildren() != getNumChildren()) return false;
1251 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001252 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001253 return false;
1254 return true;
1255}
1256
1257/// clone - Make a copy of this tree and all of its children.
1258///
1259TreePatternNode *TreePatternNode::clone() const {
1260 TreePatternNode *New;
1261 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001262 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001263 } else {
1264 std::vector<TreePatternNode*> CChildren;
1265 CChildren.reserve(Children.size());
1266 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1267 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001268 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001269 }
1270 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001271 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001272 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001273 New->setTransformFn(getTransformFn());
1274 return New;
1275}
1276
Chris Lattner53c39ba2010-02-14 22:22:58 +00001277/// RemoveAllTypes - Recursively strip all the types of this tree.
1278void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001279 // Reset to unknown type.
1280 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001281 if (isLeaf()) return;
1282 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1283 getChild(i)->RemoveAllTypes();
1284}
1285
1286
Chris Lattner8cab0212008-01-05 22:25:12 +00001287/// SubstituteFormalArguments - Replace the formal arguments in this tree
1288/// with actual values specified by ArgMap.
1289void TreePatternNode::
1290SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1291 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001292
Chris Lattner8cab0212008-01-05 22:25:12 +00001293 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1294 TreePatternNode *Child = getChild(i);
1295 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001296 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001297 // Note that, when substituting into an output pattern, Val might be an
1298 // UnsetInit.
1299 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1300 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001301 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001302 TreePatternNode *NewChild = ArgMap[Child->getName()];
1303 assert(NewChild && "Couldn't find formal argument!");
1304 assert((Child->getPredicateFns().empty() ||
1305 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1306 "Non-empty child predicate clobbered!");
1307 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001308 }
1309 } else {
1310 getChild(i)->SubstituteFormalArguments(ArgMap);
1311 }
1312 }
1313}
1314
1315
1316/// InlinePatternFragments - If this pattern refers to any pattern
1317/// fragments, inline them into place, giving us a pattern without any
1318/// PatFrag references.
1319TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001320 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001321 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001322
1323 if (isLeaf())
1324 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001325 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001326
Chris Lattner8cab0212008-01-05 22:25:12 +00001327 if (!Op->isSubClassOf("PatFrag")) {
1328 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001329 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1330 TreePatternNode *Child = getChild(i);
1331 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1332
1333 assert((Child->getPredicateFns().empty() ||
1334 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1335 "Non-empty child predicate clobbered!");
1336
1337 setChild(i, NewChild);
1338 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001339 return this;
1340 }
1341
1342 // Otherwise, we found a reference to a fragment. First, look up its
1343 // TreePattern record.
1344 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001345
Chris Lattner8cab0212008-01-05 22:25:12 +00001346 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001347 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001348 TP.error("'" + Op->getName() + "' fragment requires " +
1349 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001350 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001351 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001352
1353 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1354
Chris Lattner514e2922011-04-17 21:38:24 +00001355 TreePredicateFn PredFn(Frag);
1356 if (!PredFn.isAlwaysTrue())
1357 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001358
Chris Lattner8cab0212008-01-05 22:25:12 +00001359 // Resolve formal arguments to their actual value.
1360 if (Frag->getNumArgs()) {
1361 // Compute the map of formal to actual arguments.
1362 std::map<std::string, TreePatternNode*> ArgMap;
1363 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1364 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001365
Chris Lattner8cab0212008-01-05 22:25:12 +00001366 FragTree->SubstituteFormalArguments(ArgMap);
1367 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001368
Chris Lattner8cab0212008-01-05 22:25:12 +00001369 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001370 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1371 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001372
1373 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001374 for (const TreePredicateFn &Pred : getPredicateFns())
1375 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001376
Chris Lattner8cab0212008-01-05 22:25:12 +00001377 // Get a new copy of this fragment to stitch into here.
1378 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001379
Chris Lattner2e253b42008-06-30 03:02:03 +00001380 // The fragment we inlined could have recursive inlining that is needed. See
1381 // if there are any pattern fragments in it and inline them as needed.
1382 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001383}
1384
1385/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001386/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001387/// references from the register file information, for example.
1388///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001389/// When Unnamed is set, return the type of a DAG operand with no name, such as
1390/// the F8RC register class argument in:
1391///
1392/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1393///
1394/// When Unnamed is false, return the type of a named DAG operand such as the
1395/// GPR:$src operand above.
1396///
Chris Lattnerf1447252010-03-19 21:37:09 +00001397static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001398 bool NotRegisters,
1399 bool Unnamed,
1400 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001401 // Check to see if this is a register operand.
1402 if (R->isSubClassOf("RegisterOperand")) {
1403 assert(ResNo == 0 && "Regoperand ref only has one result!");
1404 if (NotRegisters)
1405 return EEVT::TypeSet(); // Unknown.
1406 Record *RegClass = R->getValueAsDef("RegClass");
1407 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1408 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1409 }
1410
Chris Lattnercabe0372010-03-15 06:00:16 +00001411 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001412 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001413 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001414 // An unnamed register class represents itself as an i32 immediate, for
1415 // example on a COPY_TO_REGCLASS instruction.
1416 if (Unnamed)
1417 return EEVT::TypeSet(MVT::i32, TP);
1418
1419 // In a named operand, the register class provides the possible set of
1420 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001421 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001422 return EEVT::TypeSet(); // Unknown.
1423 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1424 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001425 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001426
Chris Lattner6070ee22010-03-23 23:50:31 +00001427 if (R->isSubClassOf("PatFrag")) {
1428 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001429 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001430 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001431 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001432
Chris Lattner6070ee22010-03-23 23:50:31 +00001433 if (R->isSubClassOf("Register")) {
1434 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001435 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001436 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001437 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001438 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001439 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001440
1441 if (R->isSubClassOf("SubRegIndex")) {
1442 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001443 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001444 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001445
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001446 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001447 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001448 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1449 //
1450 // (sext_inreg GPR:$src, i16)
1451 // ~~~
1452 if (Unnamed)
1453 return EEVT::TypeSet(MVT::Other, TP);
1454 // With a name, the ValueType simply provides the type of the named
1455 // variable.
1456 //
1457 // (sext_inreg i32:$src, i16)
1458 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001459 if (NotRegisters)
1460 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001461 return EEVT::TypeSet(getValueType(R), TP);
1462 }
1463
1464 if (R->isSubClassOf("CondCode")) {
1465 assert(ResNo == 0 && "This node only has one result!");
1466 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001467 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001468 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001469
Chris Lattner6070ee22010-03-23 23:50:31 +00001470 if (R->isSubClassOf("ComplexPattern")) {
1471 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001472 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001473 return EEVT::TypeSet(); // Unknown.
1474 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1475 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001476 }
1477 if (R->isSubClassOf("PointerLikeRegClass")) {
1478 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001479 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001480 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001481
Chris Lattner6070ee22010-03-23 23:50:31 +00001482 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1483 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001484 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001485 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001486 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001487
Tim Northoverc807a172014-05-20 11:52:46 +00001488 if (R->isSubClassOf("Operand"))
1489 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1490
Chris Lattner8cab0212008-01-05 22:25:12 +00001491 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001492 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001493}
1494
Chris Lattner89c65662008-01-06 05:36:50 +00001495
1496/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1497/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1498const CodeGenIntrinsic *TreePatternNode::
1499getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1500 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1501 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1502 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001503 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001504
Sean Silva88eb8dd2012-10-10 20:24:47 +00001505 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001506 return &CDP.getIntrinsicInfo(IID);
1507}
1508
Chris Lattner53c39ba2010-02-14 22:22:58 +00001509/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1510/// return the ComplexPattern information, otherwise return null.
1511const ComplexPattern *
1512TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001513 Record *Rec;
1514 if (isLeaf()) {
1515 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1516 if (!DI)
1517 return nullptr;
1518 Rec = DI->getDef();
1519 } else
1520 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001521
Tim Northoverc807a172014-05-20 11:52:46 +00001522 if (!Rec->isSubClassOf("ComplexPattern"))
1523 return nullptr;
1524 return &CGP.getComplexPattern(Rec);
1525}
1526
1527unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1528 // A ComplexPattern specifically declares how many results it fills in.
1529 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1530 return CP->getNumOperands();
1531
1532 // If MIOperandInfo is specified, that gives the count.
1533 if (isLeaf()) {
1534 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1535 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1536 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1537 if (MIOps->getNumArgs())
1538 return MIOps->getNumArgs();
1539 }
1540 }
1541
1542 // Otherwise there is just one result.
1543 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001544}
1545
1546/// NodeHasProperty - Return true if this node has the specified property.
1547bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001548 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001549 if (isLeaf()) {
1550 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1551 return CP->hasProperty(Property);
1552 return false;
1553 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001554
Chris Lattner53c39ba2010-02-14 22:22:58 +00001555 Record *Operator = getOperator();
1556 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001557
Chris Lattner53c39ba2010-02-14 22:22:58 +00001558 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1559}
1560
1561
1562
1563
1564/// TreeHasProperty - Return true if any node in this tree has the specified
1565/// property.
1566bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001567 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001568 if (NodeHasProperty(Property, CGP))
1569 return true;
1570 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1571 if (getChild(i)->TreeHasProperty(Property, CGP))
1572 return true;
1573 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001574}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001575
Evan Cheng49bad4c2008-06-16 20:29:38 +00001576/// isCommutativeIntrinsic - Return true if the node corresponds to a
1577/// commutative intrinsic.
1578bool
1579TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1580 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1581 return Int->isCommutative;
1582 return false;
1583}
1584
Matt Arsenaulteb492162014-11-02 23:46:51 +00001585static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1586 if (!N->isLeaf())
1587 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001588
Matt Arsenaulteb492162014-11-02 23:46:51 +00001589 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1590 if (DI && DI->getDef()->isSubClassOf(Class))
1591 return true;
1592
1593 return false;
1594}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001595
1596static void emitTooManyOperandsError(TreePattern &TP,
1597 StringRef InstName,
1598 unsigned Expected,
1599 unsigned Actual) {
1600 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1601 " operands but expected only " + Twine(Expected) + "!");
1602}
1603
1604static void emitTooFewOperandsError(TreePattern &TP,
1605 StringRef InstName,
1606 unsigned Actual) {
1607 TP.error("Instruction '" + InstName +
1608 "' expects more than the provided " + Twine(Actual) + " operands!");
1609}
1610
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001611/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001612/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001613/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001614bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001615 if (TP.hasError())
1616 return false;
1617
Chris Lattnerab3242f2008-01-06 01:10:31 +00001618 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001619 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001620 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001621 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001622 bool MadeChange = false;
1623 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1624 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001625 NotRegisters,
1626 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001627 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001628 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001629
Sean Silvafb509ed2012-10-10 20:24:43 +00001630 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001631 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001632
Chris Lattnerf1447252010-03-19 21:37:09 +00001633 // Int inits are always integers. :)
1634 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001635
Chris Lattnerf1447252010-03-19 21:37:09 +00001636 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001637 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001638
Chris Lattnerf1447252010-03-19 21:37:09 +00001639 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001640 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1641 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001642
Craig Topper95198f42013-09-25 06:37:18 +00001643 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001644 // Make sure that the value is representable for this type.
1645 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001646
Richard Smith228e6d42012-08-24 23:29:28 +00001647 // Check that the value doesn't use more bits than we have. It must either
1648 // be a sign- or zero-extended equivalent of the original.
1649 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1650 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001651 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001652
Richard Smith228e6d42012-08-24 23:29:28 +00001653 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001654 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001655 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001656 }
1657 return false;
1658 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001659
Chris Lattner8cab0212008-01-05 22:25:12 +00001660 // special handling for set, which isn't really an SDNode.
1661 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001662 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1663 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001664 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001665
Chris Lattnerf1447252010-03-19 21:37:09 +00001666 TreePatternNode *SetVal = getChild(NC-1);
1667 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1668
Elena Demikhovsky09954792015-03-01 08:23:41 +00001669 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001670 TreePatternNode *Child = getChild(i);
1671 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001672
Chris Lattner8cab0212008-01-05 22:25:12 +00001673 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001674 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1675 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001676 }
1677 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001678 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001679
Chris Lattner5c2182e2010-03-27 02:53:27 +00001680 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001681 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1682
Chris Lattner8cab0212008-01-05 22:25:12 +00001683 bool MadeChange = false;
1684 for (unsigned i = 0; i < getNumChildren(); ++i)
1685 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001686 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001687 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001688
Chris Lattneree820ac2010-02-23 05:51:07 +00001689 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001690 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001691
Chris Lattner8cab0212008-01-05 22:25:12 +00001692 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001693 unsigned NumRetVTs = Int->IS.RetVTs.size();
1694 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001695
Bill Wendling91821472008-11-13 09:08:33 +00001696 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001697 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001698
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001699 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001700 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001701 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001702 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001703 return false;
1704 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001705
1706 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001707 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001708
Chris Lattnerf1447252010-03-19 21:37:09 +00001709 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1710 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001711
Chris Lattnerf1447252010-03-19 21:37:09 +00001712 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1713 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1714 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001715 }
1716 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001717 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001718
Chris Lattneree820ac2010-02-23 05:51:07 +00001719 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001720 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001721
Chris Lattner135091b2010-03-28 08:48:47 +00001722 // Check that the number of operands is sane. Negative operands -> varargs.
1723 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001724 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001725 TP.error(getOperator()->getName() + " node requires exactly " +
1726 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001727 return false;
1728 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001729
Chris Lattner8cab0212008-01-05 22:25:12 +00001730 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1731 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1732 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001733 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001734 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001735
Chris Lattneree820ac2010-02-23 05:51:07 +00001736 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001737 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001738 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001739 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001740
Chris Lattnerd44966f2010-03-27 19:15:02 +00001741 bool MadeChange = false;
1742
1743 // Apply the result types to the node, these come from the things in the
1744 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001745 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1746 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001747 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1748 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001749
Chris Lattnerd44966f2010-03-27 19:15:02 +00001750 // If the instruction has implicit defs, we apply the first one as a result.
1751 // FIXME: This sucks, it should apply all implicit defs.
1752 if (!InstInfo.ImplicitDefs.empty()) {
1753 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001754
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001755 // FIXME: Generalize to multiple possible types and multiple possible
1756 // ImplicitDefs.
1757 MVT::SimpleValueType VT =
1758 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001759
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001760 if (VT != MVT::Other)
1761 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001762 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001763
Chris Lattnercabe0372010-03-15 06:00:16 +00001764 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1765 // be the same.
1766 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001767 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1768 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1769 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001770 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1771 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1772 // variadic.
1773
1774 unsigned NChild = getNumChildren();
1775 if (NChild < 3) {
1776 TP.error("REG_SEQUENCE requires at least 3 operands!");
1777 return false;
1778 }
1779
1780 if (NChild % 2 == 0) {
1781 TP.error("REG_SEQUENCE requires an odd number of operands!");
1782 return false;
1783 }
1784
1785 if (!isOperandClass(getChild(0), "RegisterClass")) {
1786 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1787 return false;
1788 }
1789
1790 for (unsigned I = 1; I < NChild; I += 2) {
1791 TreePatternNode *SubIdxChild = getChild(I + 1);
1792 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1793 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1794 itostr(I + 1) + "!");
1795 return false;
1796 }
1797 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001798 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001799
1800 unsigned ChildNo = 0;
1801 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1802 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001803
Chris Lattner8cab0212008-01-05 22:25:12 +00001804 // If the instruction expects a predicate or optional def operand, we
1805 // codegen this by setting the operand to it's default value if it has a
1806 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001807 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001808 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1809 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001810
Chris Lattner8cab0212008-01-05 22:25:12 +00001811 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001812 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001813 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001814 return false;
1815 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001816
Chris Lattner8cab0212008-01-05 22:25:12 +00001817 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001818 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001819
1820 // If the operand has sub-operands, they may be provided by distinct
1821 // child patterns, so attempt to match each sub-operand separately.
1822 if (OperandNode->isSubClassOf("Operand")) {
1823 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1824 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1825 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001826 // a single ComplexPattern-related Operand.
1827
1828 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001829 // Match first sub-operand against the child we already have.
1830 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1831 MadeChange |=
1832 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1833
1834 // And the remaining sub-operands against subsequent children.
1835 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1836 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001837 emitTooFewOperandsError(TP, getOperator()->getName(),
1838 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001839 return false;
1840 }
1841 Child = getChild(ChildNo++);
1842
1843 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1844 MadeChange |=
1845 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1846 }
1847 continue;
1848 }
1849 }
1850 }
1851
1852 // If we didn't match by pieces above, attempt to match the whole
1853 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001854 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001855 }
Christopher Lamba7312392008-03-11 09:33:47 +00001856
Matt Arsenaulteb492162014-11-02 23:46:51 +00001857 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001858 emitTooManyOperandsError(TP, getOperator()->getName(),
1859 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001860 return false;
1861 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001862
Ulrich Weigande618abd2013-03-19 19:51:09 +00001863 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1864 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001865 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001866 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001867
Tim Northoverc807a172014-05-20 11:52:46 +00001868 if (getOperator()->isSubClassOf("ComplexPattern")) {
1869 bool MadeChange = false;
1870
1871 for (unsigned i = 0; i < getNumChildren(); ++i)
1872 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1873
1874 return MadeChange;
1875 }
1876
Chris Lattneree820ac2010-02-23 05:51:07 +00001877 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001878
Chris Lattneree820ac2010-02-23 05:51:07 +00001879 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001880 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001881 TP.error("Node transform '" + getOperator()->getName() +
1882 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001883 return false;
1884 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001885
Chris Lattnercabe0372010-03-15 06:00:16 +00001886 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1887
Jim Grosbach65586fe2010-12-21 16:16:00 +00001888
Chris Lattneree820ac2010-02-23 05:51:07 +00001889 // If either the output or input of the xform does not have exact
1890 // type info. We assume they must be the same. Otherwise, it is perfectly
1891 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001892#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001893 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001894 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1895 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001896 return MadeChange;
1897 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001898#endif
1899 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001900}
1901
1902/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1903/// RHS of a commutative operation, not the on LHS.
1904static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1905 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1906 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001907 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001908 return true;
1909 return false;
1910}
1911
1912
1913/// canPatternMatch - If it is impossible for this pattern to match on this
1914/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001915/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001916/// that can never possibly work), and to prevent the pattern permuter from
1917/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001918bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001919 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001920 if (isLeaf()) return true;
1921
1922 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1923 if (!getChild(i)->canPatternMatch(Reason, CDP))
1924 return false;
1925
1926 // If this is an intrinsic, handle cases that would make it not match. For
1927 // example, if an operand is required to be an immediate.
1928 if (getOperator()->isSubClassOf("Intrinsic")) {
1929 // TODO:
1930 return true;
1931 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001932
Tim Northoverc807a172014-05-20 11:52:46 +00001933 if (getOperator()->isSubClassOf("ComplexPattern"))
1934 return true;
1935
Chris Lattner8cab0212008-01-05 22:25:12 +00001936 // If this node is a commutative operator, check that the LHS isn't an
1937 // immediate.
1938 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001939 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1940 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001941 // Scan all of the operands of the node and make sure that only the last one
1942 // is a constant node, unless the RHS also is.
1943 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001944 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1945 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001946 if (OnlyOnRHSOfCommutative(getChild(i))) {
1947 Reason="Immediate value must be on the RHS of commutative operators!";
1948 return false;
1949 }
1950 }
1951 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001952
Chris Lattner8cab0212008-01-05 22:25:12 +00001953 return true;
1954}
1955
1956//===----------------------------------------------------------------------===//
1957// TreePattern implementation
1958//
1959
David Greeneaf8ee2c2011-07-29 22:43:06 +00001960TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001961 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1962 isInputPattern(isInput), HasError(false) {
Craig Topperef0578a2015-06-02 04:15:51 +00001963 for (Init *I : RawPat->getValues())
1964 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001965}
1966
David Greeneaf8ee2c2011-07-29 22:43:06 +00001967TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001968 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1969 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001970 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001971}
1972
David Blaikiecf195302014-11-17 22:55:41 +00001973TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001974 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1975 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00001976 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00001977}
1978
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00001979void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001980 if (HasError)
1981 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001982 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001983 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1984 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00001985}
1986
Chris Lattnercabe0372010-03-15 06:00:16 +00001987void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00001988 for (TreePatternNode *Tree : Trees)
1989 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00001990}
1991
1992void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1993 if (!N->getName().empty())
1994 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001995
Chris Lattnercabe0372010-03-15 06:00:16 +00001996 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1997 ComputeNamedNodes(N->getChild(i));
1998}
1999
David Blaikiecf195302014-11-17 22:55:41 +00002000
2001TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002002 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002003 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002004
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002005 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002006 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002007 /// (foo GPR, imm) -> (foo GPR, (imm))
2008 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002009 return ParseTreePattern(
2010 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002011 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002012 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002013
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002014 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002015 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002016 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002017 if (OpName.empty())
2018 error("'node' argument requires a name to match with operand list");
2019 Args.push_back(OpName);
2020 }
2021
2022 Res->setName(OpName);
2023 return Res;
2024 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002025
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002026 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002027 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002028 if (OpName.empty())
2029 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002030 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002031 Args.push_back(OpName);
2032 Res->setName(OpName);
2033 return Res;
2034 }
2035
Sean Silvafb509ed2012-10-10 20:24:43 +00002036 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002037 if (!OpName.empty())
2038 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002039 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002040 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002041
Sean Silvafb509ed2012-10-10 20:24:43 +00002042 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002043 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002044 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002045 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002046 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002047 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002048 }
2049
Sean Silvafb509ed2012-10-10 20:24:43 +00002050 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002051 if (!Dag) {
2052 TheInit->dump();
2053 error("Pattern has unexpected init kind!");
2054 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002055 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002056 if (!OpDef) error("Pattern has unexpected operator type!");
2057 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002058
Chris Lattner8cab0212008-01-05 22:25:12 +00002059 if (Operator->isSubClassOf("ValueType")) {
2060 // If the operator is a ValueType, then this must be "type cast" of a leaf
2061 // node.
2062 if (Dag->getNumArgs() != 1)
2063 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002064
David Blaikiecf195302014-11-17 22:55:41 +00002065 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002066
Chris Lattner8cab0212008-01-05 22:25:12 +00002067 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002068 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2069 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002070
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002071 if (!OpName.empty())
2072 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002073 return New;
2074 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002075
Chris Lattner8cab0212008-01-05 22:25:12 +00002076 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002077 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002078 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002079 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002080 !Operator->isSubClassOf("SDNodeXForm") &&
2081 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002082 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002083 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002084 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002085 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002086
Chris Lattner8cab0212008-01-05 22:25:12 +00002087 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002088 if (isInputPattern) {
2089 if (Operator->isSubClassOf("Instruction") ||
2090 Operator->isSubClassOf("SDNodeXForm"))
2091 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2092 } else {
2093 if (Operator->isSubClassOf("Intrinsic"))
2094 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002095
Chris Lattner2e9eae12010-03-28 06:57:56 +00002096 if (Operator->isSubClassOf("SDNode") &&
2097 Operator->getName() != "imm" &&
2098 Operator->getName() != "fpimm" &&
2099 Operator->getName() != "tglobaltlsaddr" &&
2100 Operator->getName() != "tconstpool" &&
2101 Operator->getName() != "tjumptable" &&
2102 Operator->getName() != "tframeindex" &&
2103 Operator->getName() != "texternalsym" &&
2104 Operator->getName() != "tblockaddress" &&
2105 Operator->getName() != "tglobaladdr" &&
2106 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002107 Operator->getName() != "vt" &&
2108 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002109 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2110 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002111
Chris Lattner8cab0212008-01-05 22:25:12 +00002112 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002113
2114 // Parse all the operands.
2115 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002116 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002117
Chris Lattner8cab0212008-01-05 22:25:12 +00002118 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002119 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002120 // convert the intrinsic name to a number.
2121 if (Operator->isSubClassOf("Intrinsic")) {
2122 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2123 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2124
2125 // If this intrinsic returns void, it must have side-effects and thus a
2126 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002127 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002128 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002129 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002130 // Has side-effects, requires chain.
2131 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002132 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002133 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002134
David Greenee32ebf22011-07-29 19:07:07 +00002135 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002136 Children.insert(Children.begin(), IIDNode);
2137 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002138
Tim Northoverc807a172014-05-20 11:52:46 +00002139 if (Operator->isSubClassOf("ComplexPattern")) {
2140 for (unsigned i = 0; i < Children.size(); ++i) {
2141 TreePatternNode *Child = Children[i];
2142
2143 if (Child->getName().empty())
2144 error("All arguments to a ComplexPattern must be named");
2145
2146 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2147 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2148 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2149 auto OperandId = std::make_pair(Operator, i);
2150 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2151 if (PrevOp != ComplexPatternOperands.end()) {
2152 if (PrevOp->getValue() != OperandId)
2153 error("All ComplexPattern operands must appear consistently: "
2154 "in the same order in just one ComplexPattern instance.");
2155 } else
2156 ComplexPatternOperands[Child->getName()] = OperandId;
2157 }
2158 }
2159
Chris Lattnerf1447252010-03-19 21:37:09 +00002160 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002161 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002162 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002163
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002164 if (!Dag->getName().empty()) {
2165 assert(Result->getName().empty());
2166 Result->setName(Dag->getName());
2167 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002168 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002169}
2170
Chris Lattnera787c9e2010-03-28 08:38:32 +00002171/// SimplifyTree - See if we can simplify this tree to eliminate something that
2172/// will never match in favor of something obvious that will. This is here
2173/// strictly as a convenience to target authors because it allows them to write
2174/// more type generic things and have useless type casts fold away.
2175///
2176/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002177static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002178 if (N->isLeaf())
2179 return false;
2180
2181 // If we have a bitconvert with a resolved type and if the source and
2182 // destination types are the same, then the bitconvert is useless, remove it.
2183 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002184 N->getExtType(0).isConcrete() &&
2185 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2186 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002187 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002188 SimplifyTree(N);
2189 return true;
2190 }
2191
2192 // Walk all children.
2193 bool MadeChange = false;
2194 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002195 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002196 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002197 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002198 }
2199 return MadeChange;
2200}
2201
2202
2203
Chris Lattner8cab0212008-01-05 22:25:12 +00002204/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002205/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002206/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002207bool TreePattern::
2208InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2209 if (NamedNodes.empty())
2210 ComputeNamedNodes();
2211
Chris Lattner8cab0212008-01-05 22:25:12 +00002212 bool MadeChange = true;
2213 while (MadeChange) {
2214 MadeChange = false;
Craig Topper306cb122015-11-22 20:46:24 +00002215 for (TreePatternNode *Tree : Trees) {
2216 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2217 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002218 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002219
2220 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002221 for (auto &Entry : NamedNodes) {
2222 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002223
Chris Lattnercabe0372010-03-15 06:00:16 +00002224 // If we have input named node types, propagate their types to the named
2225 // values here.
2226 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002227 if (!InNamedTypes->count(Entry.getKey())) {
2228 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002229 "' in output pattern but not input pattern");
2230 return true;
2231 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002232
2233 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002234 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002235
2236 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002237 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002238 // If this node is a register class, and it is the root of the pattern
2239 // then we're mapping something onto an input register. We allow
2240 // changing the type of the input register in this case. This allows
2241 // us to match things like:
2242 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002243 if (Node == Trees[0] && Node->isLeaf()) {
2244 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002245 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2246 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002247 continue;
2248 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002249
Craig Topper306cb122015-11-22 20:46:24 +00002250 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002251 InNodes[0]->getNumTypes() == 1 &&
2252 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002253 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2254 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002255 }
2256 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002257
Chris Lattnercabe0372010-03-15 06:00:16 +00002258 // If there are multiple nodes with the same name, they must all have the
2259 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002260 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002261 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002262 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002263 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002264 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002265
Chris Lattnerf1447252010-03-19 21:37:09 +00002266 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2267 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002268 }
2269 }
2270 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002271 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002272
Chris Lattner8cab0212008-01-05 22:25:12 +00002273 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002274 for (const TreePatternNode *Tree : Trees)
2275 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
Chris Lattner8cab0212008-01-05 22:25:12 +00002276 return !HasUnresolvedTypes;
2277}
2278
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002279void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002280 OS << getRecord()->getName();
2281 if (!Args.empty()) {
2282 OS << "(" << Args[0];
2283 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2284 OS << ", " << Args[i];
2285 OS << ")";
2286 }
2287 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002288
Chris Lattner8cab0212008-01-05 22:25:12 +00002289 if (Trees.size() > 1)
2290 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002291 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002292 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002293 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002294 OS << "\n";
2295 }
2296
2297 if (Trees.size() > 1)
2298 OS << "]\n";
2299}
2300
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002301void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002302
2303//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002304// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002305//
2306
Jim Grosbach65586fe2010-12-21 16:16:00 +00002307CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002308 Records(R), Target(R) {
2309
Dale Johannesenb842d522009-02-05 01:49:45 +00002310 Intrinsics = LoadIntrinsics(Records, false);
2311 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002312 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002313 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002314 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002315 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002316 ParseDefaultOperands();
2317 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002318 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002319 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002320
Chris Lattner8cab0212008-01-05 22:25:12 +00002321 // Generate variants. For example, commutative patterns can match
2322 // multiple ways. Add them to PatternsToMatch as well.
2323 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002324
2325 // Infer instruction flags. For example, we can detect loads,
2326 // stores, and side effects in many cases by examining an
2327 // instruction's pattern.
2328 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002329
2330 // Verify that instruction flags match the patterns.
2331 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002332}
2333
Chris Lattnerab3242f2008-01-06 01:10:31 +00002334Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002335 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002336 if (!N || !N->isSubClassOf("SDNode"))
2337 PrintFatalError("Error getting SDNode '" + Name + "'!");
2338
Chris Lattner8cab0212008-01-05 22:25:12 +00002339 return N;
2340}
2341
2342// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002343void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002344 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2345 while (!Nodes.empty()) {
2346 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2347 Nodes.pop_back();
2348 }
2349
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002350 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002351 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2352 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2353 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2354}
2355
2356/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2357/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002358void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002359 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2360 while (!Xforms.empty()) {
2361 Record *XFormNode = Xforms.back();
2362 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002363 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002364 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002365
2366 Xforms.pop_back();
2367 }
2368}
2369
Chris Lattnerab3242f2008-01-06 01:10:31 +00002370void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002371 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2372 while (!AMs.empty()) {
2373 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2374 AMs.pop_back();
2375 }
2376}
2377
2378
2379/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2380/// file, building up the PatternFragments map. After we've collected them all,
2381/// inline fragments together as necessary, so that there are no references left
2382/// inside a pattern fragment to a pattern fragment.
2383///
Hal Finkel2756dc12014-02-28 00:26:56 +00002384void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002385 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002386
Chris Lattnere7170df2008-01-05 22:43:57 +00002387 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002388 for (Record *Frag : Fragments) {
2389 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002390 continue;
2391
Craig Topper306cb122015-11-22 20:46:24 +00002392 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002393 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002394 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2395 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002396 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002397
Chris Lattnere7170df2008-01-05 22:43:57 +00002398 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002399 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002400 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002401
Chris Lattnere7170df2008-01-05 22:43:57 +00002402 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002403 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002404
Chris Lattner8cab0212008-01-05 22:25:12 +00002405 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002406 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002407 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002408 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002409 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002410 if (!OpsOp ||
2411 (OpsOp->getDef()->getName() != "ops" &&
2412 OpsOp->getDef()->getName() != "outs" &&
2413 OpsOp->getDef()->getName() != "ins"))
2414 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002415
2416 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002417 Args.clear();
2418 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002419 if (!isa<DefInit>(OpsList->getArg(j)) ||
2420 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002421 P->error("Operands list should all be 'node' values.");
2422 if (OpsList->getArgName(j).empty())
2423 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002424 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002425 P->error("'" + OpsList->getArgName(j) +
2426 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002427 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002428 Args.push_back(OpsList->getArgName(j));
2429 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002430
Chris Lattnere7170df2008-01-05 22:43:57 +00002431 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002432 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002433 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002434
Chris Lattnere7170df2008-01-05 22:43:57 +00002435 // If there is a code init for this fragment, keep track of the fact that
2436 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002437 TreePredicateFn PredFn(P);
2438 if (!PredFn.isAlwaysTrue())
2439 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002440
Chris Lattner8cab0212008-01-05 22:25:12 +00002441 // If there is a node transformation corresponding to this, keep track of
2442 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002443 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002444 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2445 P->getOnlyTree()->setTransformFn(Transform);
2446 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002447
Chris Lattner8cab0212008-01-05 22:25:12 +00002448 // Now that we've parsed all of the tree fragments, do a closure on them so
2449 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002450 for (Record *Frag : Fragments) {
2451 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002452 continue;
2453
Craig Topper306cb122015-11-22 20:46:24 +00002454 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002455 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002456
Chris Lattner8cab0212008-01-05 22:25:12 +00002457 // Infer as many types as possible. Don't worry about it if we don't infer
2458 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002459 ThePat.InferAllTypes();
2460 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002461
Chris Lattner8cab0212008-01-05 22:25:12 +00002462 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002463 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002464 }
2465}
2466
Chris Lattnerab3242f2008-01-06 01:10:31 +00002467void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002468 std::vector<Record*> DefaultOps;
2469 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002470
2471 // Find some SDNode.
2472 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002473 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002474
Tom Stellardb7246a72012-09-06 14:15:52 +00002475 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2476 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002477
Tom Stellardb7246a72012-09-06 14:15:52 +00002478 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2479 // SomeSDnode so that we can parse this.
2480 std::vector<std::pair<Init*, std::string> > Ops;
2481 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2482 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2483 DefaultInfo->getArgName(op)));
2484 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002485
Tom Stellardb7246a72012-09-06 14:15:52 +00002486 // Create a TreePattern to parse this.
2487 TreePattern P(DefaultOps[i], DI, false, *this);
2488 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002489
Tom Stellardb7246a72012-09-06 14:15:52 +00002490 // Copy the operands over into a DAGDefaultOperand.
2491 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002492
Tom Stellardb7246a72012-09-06 14:15:52 +00002493 TreePatternNode *T = P.getTree(0);
2494 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2495 TreePatternNode *TPN = T->getChild(op);
2496 while (TPN->ApplyTypeConstraints(P, false))
2497 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002498
Tom Stellardb7246a72012-09-06 14:15:52 +00002499 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002500 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2501 DefaultOps[i]->getName() +
2502 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002503 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002504 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002505 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002506
2507 // Insert it into the DefaultOperands map so we can find it later.
2508 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002509 }
2510}
2511
2512/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2513/// instruction input. Return true if this is a real use.
2514static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002515 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002516 // No name -> not interesting.
2517 if (Pat->getName().empty()) {
2518 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002519 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002520 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2521 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002522 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002523 }
2524 return false;
2525 }
2526
2527 Record *Rec;
2528 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002529 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002530 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2531 Rec = DI->getDef();
2532 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002533 Rec = Pat->getOperator();
2534 }
2535
2536 // SRCVALUE nodes are ignored.
2537 if (Rec->getName() == "srcvalue")
2538 return false;
2539
2540 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2541 if (!Slot) {
2542 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002543 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002544 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002545 Record *SlotRec;
2546 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002547 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002548 } else {
2549 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2550 SlotRec = Slot->getOperator();
2551 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002552
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002553 // Ensure that the inputs agree if we've already seen this input.
2554 if (Rec != SlotRec)
2555 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002556 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002557 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002558 return true;
2559}
2560
2561/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2562/// part of "I", the instruction), computing the set of inputs and outputs of
2563/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002564void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002565FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2566 std::map<std::string, TreePatternNode*> &InstInputs,
2567 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002568 std::vector<Record*> &InstImpResults) {
2569 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002570 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002571 if (!isUse && Pat->getTransformFn())
2572 I->error("Cannot specify a transform function for a non-input value!");
2573 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002574 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002575
Chris Lattnerf2d70992010-02-17 06:53:36 +00002576 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002577 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2578 TreePatternNode *Dest = Pat->getChild(i);
2579 if (!Dest->isLeaf())
2580 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002581
Sean Silvafb509ed2012-10-10 20:24:43 +00002582 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002583 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2584 I->error("implicitly defined value should be a register!");
2585 InstImpResults.push_back(Val->getDef());
2586 }
2587 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002588 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002589
Chris Lattnerf2d70992010-02-17 06:53:36 +00002590 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002591 // If this is not a set, verify that the children nodes are not void typed,
2592 // and recurse.
2593 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002594 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002595 I->error("Cannot have void nodes inside of patterns!");
2596 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002597 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002598 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002599
Chris Lattner8cab0212008-01-05 22:25:12 +00002600 // If this is a non-leaf node with no children, treat it basically as if
2601 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002602 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002603
Chris Lattner8cab0212008-01-05 22:25:12 +00002604 if (!isUse && Pat->getTransformFn())
2605 I->error("Cannot specify a transform function for a non-input value!");
2606 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002607 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002608
Chris Lattner8cab0212008-01-05 22:25:12 +00002609 // Otherwise, this is a set, validate and collect instruction results.
2610 if (Pat->getNumChildren() == 0)
2611 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002612
Chris Lattner8cab0212008-01-05 22:25:12 +00002613 if (Pat->getTransformFn())
2614 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002615
Chris Lattner8cab0212008-01-05 22:25:12 +00002616 // Check the set destinations.
2617 unsigned NumDests = Pat->getNumChildren()-1;
2618 for (unsigned i = 0; i != NumDests; ++i) {
2619 TreePatternNode *Dest = Pat->getChild(i);
2620 if (!Dest->isLeaf())
2621 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002622
Sean Silvafb509ed2012-10-10 20:24:43 +00002623 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002624 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002625 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002626 continue;
2627 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002628
2629 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002630 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002631 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002632 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002633 if (Dest->getName().empty())
2634 I->error("set destination must have a name!");
2635 if (InstResults.count(Dest->getName()))
2636 I->error("cannot set '" + Dest->getName() +"' multiple times");
2637 InstResults[Dest->getName()] = Dest;
2638 } else if (Val->getDef()->isSubClassOf("Register")) {
2639 InstImpResults.push_back(Val->getDef());
2640 } else {
2641 I->error("set destination should be a register!");
2642 }
2643 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002644
Chris Lattner8cab0212008-01-05 22:25:12 +00002645 // Verify and collect info from the computation.
2646 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002647 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002648}
2649
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002650//===----------------------------------------------------------------------===//
2651// Instruction Analysis
2652//===----------------------------------------------------------------------===//
2653
2654class InstAnalyzer {
2655 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002656public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002657 bool hasSideEffects;
2658 bool mayStore;
2659 bool mayLoad;
2660 bool isBitcast;
2661 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002662
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002663 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2664 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2665 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002666
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002667 void Analyze(const TreePattern *Pat) {
2668 // Assume only the first tree is the pattern. The others are clobber nodes.
2669 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002670 }
2671
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002672 void Analyze(const PatternToMatch *Pat) {
2673 AnalyzeNode(Pat->getSrcPattern());
2674 }
2675
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002676private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002677 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002678 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002679 return false;
2680
2681 if (N->getNumChildren() != 2)
2682 return false;
2683
2684 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002685 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002686 return false;
2687
2688 const TreePatternNode *N1 = N->getChild(1);
2689 if (N1->isLeaf())
2690 return false;
2691 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2692 return false;
2693
2694 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2695 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2696 return false;
2697 return OpInfo.getEnumName() == "ISD::BITCAST";
2698 }
2699
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002700public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002701 void AnalyzeNode(const TreePatternNode *N) {
2702 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002703 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002704 Record *LeafRec = DI->getDef();
2705 // Handle ComplexPattern leaves.
2706 if (LeafRec->isSubClassOf("ComplexPattern")) {
2707 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2708 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2709 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002710 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002711 }
2712 }
2713 return;
2714 }
2715
2716 // Analyze children.
2717 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2718 AnalyzeNode(N->getChild(i));
2719
2720 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002721 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002722 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002723 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002724 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002725
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002726 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002727 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2728 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2729 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2730 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002731
2732 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2733 // If this is an intrinsic, analyze it.
2734 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2735 mayLoad = true;// These may load memory.
2736
Dan Gohmanddb2d652010-08-05 23:36:21 +00002737 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002738 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2739
Dan Gohmanddb2d652010-08-05 23:36:21 +00002740 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002741 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002742 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002743 }
2744 }
2745
2746};
2747
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002748static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002749 const InstAnalyzer &PatInfo,
2750 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002751 bool Error = false;
2752
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002753 // Remember where InstInfo got its flags.
2754 if (InstInfo.hasUndefFlags())
2755 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002756
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002757 // Check explicitly set flags for consistency.
2758 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2759 !InstInfo.hasSideEffects_Unset) {
2760 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2761 // the pattern has no side effects. That could be useful for div/rem
2762 // instructions that may trap.
2763 if (!InstInfo.hasSideEffects) {
2764 Error = true;
2765 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2766 Twine(InstInfo.hasSideEffects));
2767 }
2768 }
2769
2770 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2771 Error = true;
2772 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2773 Twine(InstInfo.mayStore));
2774 }
2775
2776 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2777 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00002778 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002779 if (!InstInfo.mayLoad) {
2780 Error = true;
2781 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2782 Twine(InstInfo.mayLoad));
2783 }
2784 }
2785
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002786 // Transfer inferred flags.
2787 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2788 InstInfo.mayStore |= PatInfo.mayStore;
2789 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002790
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002791 // These flags are silently added without any verification.
2792 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002793
2794 // Don't infer isVariadic. This flag means something different on SDNodes and
2795 // instructions. For example, a CALL SDNode is variadic because it has the
2796 // call arguments as operands, but a CALL instruction is not variadic - it
2797 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002798
2799 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002800}
2801
Jim Grosbach514410b2012-07-17 00:47:06 +00002802/// hasNullFragReference - Return true if the DAG has any reference to the
2803/// null_frag operator.
2804static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002805 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002806 if (!OpDef) return false;
2807 Record *Operator = OpDef->getDef();
2808
2809 // If this is the null fragment, return true.
2810 if (Operator->getName() == "null_frag") return true;
2811 // If any of the arguments reference the null fragment, return true.
2812 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002813 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002814 if (Arg && hasNullFragReference(Arg))
2815 return true;
2816 }
2817
2818 return false;
2819}
2820
2821/// hasNullFragReference - Return true if any DAG in the list references
2822/// the null_frag operator.
2823static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00002824 for (Init *I : LI->getValues()) {
2825 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00002826 assert(DI && "non-dag in an instruction Pattern list?!");
2827 if (hasNullFragReference(DI))
2828 return true;
2829 }
2830 return false;
2831}
2832
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002833/// Get all the instructions in a tree.
2834static void
2835getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2836 if (Tree->isLeaf())
2837 return;
2838 if (Tree->getOperator()->isSubClassOf("Instruction"))
2839 Instrs.push_back(Tree->getOperator());
2840 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2841 getInstructionsInTree(Tree->getChild(i), Instrs);
2842}
2843
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002844/// Check the class of a pattern leaf node against the instruction operand it
2845/// represents.
2846static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2847 Record *Leaf) {
2848 if (OI.Rec == Leaf)
2849 return true;
2850
2851 // Allow direct value types to be used in instruction set patterns.
2852 // The type will be checked later.
2853 if (Leaf->isSubClassOf("ValueType"))
2854 return true;
2855
2856 // Patterns can also be ComplexPattern instances.
2857 if (Leaf->isSubClassOf("ComplexPattern"))
2858 return true;
2859
2860 return false;
2861}
2862
Ahmed Bougacha14107512013-10-28 18:07:21 +00002863const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2864 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002865
Craig Topper0d1fb902015-03-10 03:25:04 +00002866 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002867
Craig Topper0d1fb902015-03-10 03:25:04 +00002868 // Parse the instruction.
2869 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2870 // Inline pattern fragments into it.
2871 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002872
Craig Topper0d1fb902015-03-10 03:25:04 +00002873 // Infer as many types as possible. If we cannot infer all of them, we can
2874 // never do anything with this instruction pattern: report it to the user.
2875 if (!I->InferAllTypes())
2876 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002877
Craig Topper0d1fb902015-03-10 03:25:04 +00002878 // InstInputs - Keep track of all of the inputs of the instruction, along
2879 // with the record they are declared as.
2880 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002881
Craig Topper0d1fb902015-03-10 03:25:04 +00002882 // InstResults - Keep track of all the virtual registers that are 'set'
2883 // in the instruction, including what reg class they are.
2884 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002885
Craig Topper0d1fb902015-03-10 03:25:04 +00002886 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002887
Craig Topper0d1fb902015-03-10 03:25:04 +00002888 // Verify that the top-level forms in the instruction are of void type, and
2889 // fill in the InstResults map.
2890 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2891 TreePatternNode *Pat = I->getTree(j);
2892 if (Pat->getNumTypes() != 0)
2893 I->error("Top-level forms in instruction pattern should have"
2894 " void types");
Chris Lattner8cab0212008-01-05 22:25:12 +00002895
Craig Topper0d1fb902015-03-10 03:25:04 +00002896 // Find inputs and outputs, and verify the structure of the uses/defs.
2897 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2898 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002899 }
2900
Craig Topper0d1fb902015-03-10 03:25:04 +00002901 // Now that we have inputs and outputs of the pattern, inspect the operands
2902 // list for the instruction. This determines the order that operands are
2903 // added to the machine instruction the node corresponds to.
2904 unsigned NumResults = InstResults.size();
2905
2906 // Parse the operands list from the (ops) list, validating it.
2907 assert(I->getArgList().empty() && "Args list should still be empty here!");
2908
2909 // Check that all of the results occur first in the list.
2910 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00002911 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00002912 for (unsigned i = 0; i != NumResults; ++i) {
2913 if (i == CGI.Operands.size())
2914 I->error("'" + InstResults.begin()->first +
2915 "' set but does not appear in operand list!");
2916 const std::string &OpName = CGI.Operands[i].Name;
2917
2918 // Check that it exists in InstResults.
2919 TreePatternNode *RNode = InstResults[OpName];
2920 if (!RNode)
2921 I->error("Operand $" + OpName + " does not exist in operand list!");
2922
Craig Topper3a8eb892015-03-20 05:09:06 +00002923 ResNodes.push_back(RNode);
2924
Craig Topper0d1fb902015-03-10 03:25:04 +00002925 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2926 if (!R)
2927 I->error("Operand $" + OpName + " should be a set destination: all "
2928 "outputs must occur before inputs in operand list!");
2929
2930 if (!checkOperandClass(CGI.Operands[i], R))
2931 I->error("Operand $" + OpName + " class mismatch!");
2932
2933 // Remember the return type.
2934 Results.push_back(CGI.Operands[i].Rec);
2935
2936 // Okay, this one checks out.
2937 InstResults.erase(OpName);
2938 }
2939
2940 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2941 // the copy while we're checking the inputs.
2942 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2943
2944 std::vector<TreePatternNode*> ResultNodeOperands;
2945 std::vector<Record*> Operands;
2946 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2947 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2948 const std::string &OpName = Op.Name;
2949 if (OpName.empty())
2950 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2951
2952 if (!InstInputsCheck.count(OpName)) {
2953 // If this is an operand with a DefaultOps set filled in, we can ignore
2954 // this. When we codegen it, we will do so as always executed.
2955 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2956 // Does it have a non-empty DefaultOps field? If so, ignore this
2957 // operand.
2958 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2959 continue;
2960 }
2961 I->error("Operand $" + OpName +
2962 " does not appear in the instruction pattern");
2963 }
2964 TreePatternNode *InVal = InstInputsCheck[OpName];
2965 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2966
2967 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2968 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2969 if (!checkOperandClass(Op, InRec))
2970 I->error("Operand $" + OpName + "'s register class disagrees"
2971 " between the operand and pattern");
2972 }
2973 Operands.push_back(Op.Rec);
2974
2975 // Construct the result for the dest-pattern operand list.
2976 TreePatternNode *OpNode = InVal->clone();
2977
2978 // No predicate is useful on the result.
2979 OpNode->clearPredicateFns();
2980
2981 // Promote the xform function to be an explicit node if set.
2982 if (Record *Xform = OpNode->getTransformFn()) {
2983 OpNode->setTransformFn(nullptr);
2984 std::vector<TreePatternNode*> Children;
2985 Children.push_back(OpNode);
2986 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2987 }
2988
2989 ResultNodeOperands.push_back(OpNode);
2990 }
2991
2992 if (!InstInputsCheck.empty())
2993 I->error("Input operand $" + InstInputsCheck.begin()->first +
2994 " occurs in pattern but not in operands list!");
2995
2996 TreePatternNode *ResultPattern =
2997 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2998 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00002999 // Copy fully inferred output node types to instruction result pattern.
3000 for (unsigned i = 0; i != NumResults; ++i) {
3001 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3002 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3003 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003004
3005 // Create and insert the instruction.
3006 // FIXME: InstImpResults should not be part of DAGInstruction.
3007 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3008 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3009
3010 // Use a temporary tree pattern to infer all types and make sure that the
3011 // constructed result is correct. This depends on the instruction already
3012 // being inserted into the DAGInsts map.
3013 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3014 Temp.InferAllTypes(&I->getNamedNodesMap());
3015
3016 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3017 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3018
3019 return TheInsertedInst;
3020}
3021
Ahmed Bougacha14107512013-10-28 18:07:21 +00003022/// ParseInstructions - Parse all of the instructions, inlining and resolving
3023/// any fragments involved. This populates the Instructions list with fully
3024/// resolved instructions.
3025void CodeGenDAGPatterns::ParseInstructions() {
3026 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3027
Craig Topper306cb122015-11-22 20:46:24 +00003028 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003029 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003030
Craig Topper306cb122015-11-22 20:46:24 +00003031 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3032 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003033
3034 // If there is no pattern, only collect minimal information about the
3035 // instruction for its operand list. We have to assume that there is one
3036 // result, as we have no detailed info. A pattern which references the
3037 // null_frag operator is as-if no pattern were specified. Normally this
3038 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3039 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003040 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003041 std::vector<Record*> Results;
3042 std::vector<Record*> Operands;
3043
Craig Topper306cb122015-11-22 20:46:24 +00003044 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003045
3046 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003047 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3048 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003049
Craig Topper3a8eb892015-03-20 05:09:06 +00003050 // The rest are inputs.
3051 for (unsigned j = InstInfo.Operands.NumDefs,
3052 e = InstInfo.Operands.size(); j < e; ++j)
3053 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003054 }
3055
3056 // Create and insert the instruction.
3057 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003058 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003059 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003060 continue; // no pattern.
3061 }
3062
Craig Topper306cb122015-11-22 20:46:24 +00003063 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003064 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3065
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003066 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003067 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003068 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003069
Chris Lattner8cab0212008-01-05 22:25:12 +00003070 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003071 for (auto &Entry : Instructions) {
3072 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003073 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003074 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003075
3076 // FIXME: Assume only the first tree is the pattern. The others are clobber
3077 // nodes.
3078 TreePatternNode *Pattern = I->getTree(0);
3079 TreePatternNode *SrcPattern;
3080 if (Pattern->getOperator()->getName() == "set") {
3081 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3082 } else{
3083 // Not a set (store or something?)
3084 SrcPattern = Pattern;
3085 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003086
Craig Topper306cb122015-11-22 20:46:24 +00003087 Record *Instr = Entry.first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003088 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003089 PatternToMatch(Instr,
3090 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003091 SrcPattern,
3092 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003093 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003094 Instr->getValueAsInt("AddedComplexity"),
3095 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003096 }
3097}
3098
Chris Lattnera7722b62010-02-23 06:55:24 +00003099
3100typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3101
Jim Grosbach65586fe2010-12-21 16:16:00 +00003102static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003103 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003104 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003105 if (!P->getName().empty()) {
3106 NameRecord &Rec = Names[P->getName()];
3107 // If this is the first instance of the name, remember the node.
3108 if (Rec.second++ == 0)
3109 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003110 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003111 PatternTop->error("repetition of value: $" + P->getName() +
3112 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003113 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003114
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003115 if (!P->isLeaf()) {
3116 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003117 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003118 }
3119}
3120
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003121void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003122 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003123 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003124 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003125 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3126 PrintWarning(Pattern->getRecord()->getLoc(),
3127 Twine("Pattern can never match: ") + Reason);
3128 return;
3129 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003130
Chris Lattner1e634e32010-03-01 22:29:19 +00003131 // If the source pattern's root is a complex pattern, that complex pattern
3132 // must specify the nodes it can potentially match.
3133 if (const ComplexPattern *CP =
3134 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3135 if (CP->getRootNodes().empty())
3136 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3137 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003138
3139
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003140 // Find all of the named values in the input and output, ensure they have the
3141 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003142 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003143 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3144 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003145
3146 // Scan all of the named values in the destination pattern, rejecting them if
3147 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003148 for (const auto &Entry : DstNames) {
3149 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003150 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003151 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003152 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003153
Chris Lattnera7722b62010-02-23 06:55:24 +00003154 // Scan all of the named values in the source pattern, rejecting them if the
3155 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003156 for (const auto &Entry : SrcNames)
3157 if (DstNames[Entry.first].first == nullptr &&
3158 SrcNames[Entry.first].second == 1)
3159 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003160
Chris Lattner0c0baa92010-02-23 06:16:51 +00003161 PatternsToMatch.push_back(PTM);
3162}
3163
3164
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003165
3166void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003167 const std::vector<const CodeGenInstruction*> &Instructions =
3168 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003169
3170 // First try to infer flags from the primary instruction pattern, if any.
3171 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003172 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003173 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3174 CodeGenInstruction &InstInfo =
3175 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003176
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003177 // Get the primary instruction pattern.
3178 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3179 if (!Pattern) {
3180 if (InstInfo.hasUndefFlags())
3181 Revisit.push_back(&InstInfo);
3182 continue;
3183 }
3184 InstAnalyzer PatInfo(*this);
3185 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003186 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003187 }
3188
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003189 // Second, look for single-instruction patterns defined outside the
3190 // instruction.
3191 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3192 const PatternToMatch &PTM = *I;
3193
3194 // We can only infer from single-instruction patterns, otherwise we won't
3195 // know which instruction should get the flags.
3196 SmallVector<Record*, 8> PatInstrs;
3197 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3198 if (PatInstrs.size() != 1)
3199 continue;
3200
3201 // Get the single instruction.
3202 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3203
3204 // Only infer properties from the first pattern. We'll verify the others.
3205 if (InstInfo.InferredFrom)
3206 continue;
3207
3208 InstAnalyzer PatInfo(*this);
3209 PatInfo.Analyze(&PTM);
3210 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3211 }
3212
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003213 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003214 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003215
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003216 // Revisit instructions with undefined flags and no pattern.
3217 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003218 for (CodeGenInstruction *InstInfo : Revisit) {
3219 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003220 continue;
3221 // The mayLoad and mayStore flags default to false.
3222 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003223 if (InstInfo->hasSideEffects_Unset)
3224 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003225 }
3226 return;
3227 }
3228
3229 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003230 for (CodeGenInstruction *InstInfo : Revisit) {
3231 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003232 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003233 if (InstInfo->hasSideEffects_Unset)
3234 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003235 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003236 if (InstInfo->mayStore_Unset)
3237 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003238 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003239 if (InstInfo->mayLoad_Unset)
3240 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003241 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003242 }
3243}
3244
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003245
3246/// Verify instruction flags against pattern node properties.
3247void CodeGenDAGPatterns::VerifyInstructionFlags() {
3248 unsigned Errors = 0;
3249 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3250 const PatternToMatch &PTM = *I;
3251 SmallVector<Record*, 8> Instrs;
3252 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3253 if (Instrs.empty())
3254 continue;
3255
3256 // Count the number of instructions with each flag set.
3257 unsigned NumSideEffects = 0;
3258 unsigned NumStores = 0;
3259 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003260 for (const Record *Instr : Instrs) {
3261 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003262 NumSideEffects += InstInfo.hasSideEffects;
3263 NumStores += InstInfo.mayStore;
3264 NumLoads += InstInfo.mayLoad;
3265 }
3266
3267 // Analyze the source pattern.
3268 InstAnalyzer PatInfo(*this);
3269 PatInfo.Analyze(&PTM);
3270
3271 // Collect error messages.
3272 SmallVector<std::string, 4> Msgs;
3273
3274 // Check for missing flags in the output.
3275 // Permit extra flags for now at least.
3276 if (PatInfo.hasSideEffects && !NumSideEffects)
3277 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3278
3279 // Don't verify store flags on instructions with side effects. At least for
3280 // intrinsics, side effects implies mayStore.
3281 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3282 Msgs.push_back("pattern may store, but mayStore isn't set");
3283
3284 // Similarly, mayStore implies mayLoad on intrinsics.
3285 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3286 Msgs.push_back("pattern may load, but mayLoad isn't set");
3287
3288 // Print error messages.
3289 if (Msgs.empty())
3290 continue;
3291 ++Errors;
3292
Craig Topper306cb122015-11-22 20:46:24 +00003293 for (const std::string &Msg : Msgs)
3294 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003295 (Instrs.size() == 1 ?
3296 "instruction" : "output instructions"));
3297 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003298 for (const Record *Instr : Instrs) {
3299 if (Instr != PTM.getSrcRecord())
3300 PrintError(Instr->getLoc(), "defined here");
3301 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003302 if (InstInfo.InferredFrom &&
3303 InstInfo.InferredFrom != InstInfo.TheDef &&
3304 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003305 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003306 }
3307 }
3308 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003309 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003310}
3311
Chris Lattnercabe0372010-03-15 06:00:16 +00003312/// Given a pattern result with an unresolved type, see if we can find one
3313/// instruction with an unresolved result type. Force this result type to an
3314/// arbitrary element if it's possible types to converge results.
3315static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3316 if (N->isLeaf())
3317 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003318
Chris Lattnercabe0372010-03-15 06:00:16 +00003319 // Analyze children.
3320 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3321 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3322 return true;
3323
3324 if (!N->getOperator()->isSubClassOf("Instruction"))
3325 return false;
3326
3327 // If this type is already concrete or completely unknown we can't do
3328 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003329 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3330 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3331 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003332
Chris Lattnerf1447252010-03-19 21:37:09 +00003333 // Otherwise, force its type to the first possibility (an arbitrary choice).
3334 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3335 return true;
3336 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003337
Chris Lattnerf1447252010-03-19 21:37:09 +00003338 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003339}
3340
Chris Lattnerab3242f2008-01-06 01:10:31 +00003341void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003342 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3343
Craig Topper306cb122015-11-22 20:46:24 +00003344 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003345 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003346
3347 // If the pattern references the null_frag, there's nothing to do.
3348 if (hasNullFragReference(Tree))
3349 continue;
3350
Chris Lattner5c2182e2010-03-27 02:53:27 +00003351 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003352
3353 // Inline pattern fragments into it.
3354 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003355
David Greeneaf8ee2c2011-07-29 22:43:06 +00003356 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003357 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003358
Chris Lattner8cab0212008-01-05 22:25:12 +00003359 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003360 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003361
Chris Lattner8cab0212008-01-05 22:25:12 +00003362 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003363 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003364
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003365 if (Result.getNumTrees() != 1)
3366 Result.error("Cannot handle instructions producing instructions "
3367 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003368
Chris Lattner8cab0212008-01-05 22:25:12 +00003369 bool IterateInference;
3370 bool InferredAllPatternTypes, InferredAllResultTypes;
3371 do {
3372 // Infer as many types as possible. If we cannot infer all of them, we
3373 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003374 InferredAllPatternTypes =
3375 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003376
Chris Lattner8cab0212008-01-05 22:25:12 +00003377 // Infer as many types as possible. If we cannot infer all of them, we
3378 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003379 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003380 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003381
Chris Lattnerfdc20712010-03-18 23:15:10 +00003382 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003383
Chris Lattner8cab0212008-01-05 22:25:12 +00003384 // Apply the type of the result to the source pattern. This helps us
3385 // resolve cases where the input type is known to be a pointer type (which
3386 // is considered resolved), but the result knows it needs to be 32- or
3387 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003388 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003389 Pattern->getTree(0)->getNumTypes());
3390 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003391 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3392 i, Result.getTree(0)->getExtType(i), Result);
3393 IterateInference |= Result.getTree(0)->UpdateNodeType(
3394 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003395 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003396
Chris Lattnercabe0372010-03-15 06:00:16 +00003397 // If our iteration has converged and the input pattern's types are fully
3398 // resolved but the result pattern is not fully resolved, we may have a
3399 // situation where we have two instructions in the result pattern and
3400 // the instructions require a common register class, but don't care about
3401 // what actual MVT is used. This is actually a bug in our modelling:
3402 // output patterns should have register classes, not MVTs.
3403 //
3404 // In any case, to handle this, we just go through and disambiguate some
3405 // arbitrary types to the result pattern's nodes.
3406 if (!IterateInference && InferredAllPatternTypes &&
3407 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003408 IterateInference =
3409 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003410 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003411
Chris Lattner8cab0212008-01-05 22:25:12 +00003412 // Verify that we inferred enough types that we can do something with the
3413 // pattern and result. If these fire the user has to add type casts.
3414 if (!InferredAllPatternTypes)
3415 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003416 if (!InferredAllResultTypes) {
3417 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003418 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003419 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003420
Chris Lattner8cab0212008-01-05 22:25:12 +00003421 // Validate that the input pattern is correct.
3422 std::map<std::string, TreePatternNode*> InstInputs;
3423 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003424 std::vector<Record*> InstImpResults;
3425 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3426 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3427 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003428 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003429
3430 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003431 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003432 std::vector<TreePatternNode*> ResultNodeOperands;
3433 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3434 TreePatternNode *OpNode = DstPattern->getChild(ii);
3435 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003436 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003437 std::vector<TreePatternNode*> Children;
3438 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003439 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003440 }
3441 ResultNodeOperands.push_back(OpNode);
3442 }
David Blaikiecf195302014-11-17 22:55:41 +00003443 DstPattern = Result.getOnlyTree();
3444 if (!DstPattern->isLeaf())
3445 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3446 ResultNodeOperands,
3447 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003448
David Blaikiecf195302014-11-17 22:55:41 +00003449 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3450 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3451
3452 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003453 Temp.InferAllTypes();
3454
Jim Grosbach65586fe2010-12-21 16:16:00 +00003455
Chris Lattner0c0baa92010-02-23 06:16:51 +00003456 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003457 PatternToMatch(CurPattern,
3458 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003459 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003460 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003461 CurPattern->getValueAsInt("AddedComplexity"),
3462 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003463 }
3464}
3465
3466/// CombineChildVariants - Given a bunch of permutations of each child of the
3467/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003468static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003469 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3470 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003471 CodeGenDAGPatterns &CDP,
3472 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003473 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003474 for (const auto &Variants : ChildVariants)
3475 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003476 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003477
Chris Lattner8cab0212008-01-05 22:25:12 +00003478 // The end result is an all-pairs construction of the resultant pattern.
3479 std::vector<unsigned> Idxs;
3480 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003481 bool NotDone;
3482 do {
3483#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003484 DEBUG(if (!Idxs.empty()) {
3485 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003486 for (unsigned Idx : Idxs) {
3487 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003488 }
3489 errs() << "]\n";
3490 });
Scott Michel94420742008-03-05 17:49:05 +00003491#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003492 // Create the variant and add it to the output list.
3493 std::vector<TreePatternNode*> NewChildren;
3494 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3495 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003496 auto R = llvm::make_unique<TreePatternNode>(
3497 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003498
Chris Lattner8cab0212008-01-05 22:25:12 +00003499 // Copy over properties.
3500 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003501 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003502 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003503 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3504 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003505
Scott Michel94420742008-03-05 17:49:05 +00003506 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003507 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003508 // Scan to see if this pattern has already been emitted. We can get
3509 // duplication due to things like commuting:
3510 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3511 // which are the same pattern. Ignore the dups.
3512 if (R->canPatternMatch(ErrString, CDP) &&
3513 std::none_of(OutVariants.begin(), OutVariants.end(),
3514 [&](TreePatternNode *Variant) {
3515 return R->isIsomorphicTo(Variant, DepVars);
3516 }))
3517 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003518
Scott Michel94420742008-03-05 17:49:05 +00003519 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003520 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003521 // [0, 0], [0, 1], [1, 0], [1, 1].
3522 int IdxsIdx;
3523 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3524 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3525 Idxs[IdxsIdx] = 0;
3526 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003527 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003528 }
Scott Michel94420742008-03-05 17:49:05 +00003529 NotDone = (IdxsIdx >= 0);
3530 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003531}
3532
3533/// CombineChildVariants - A helper function for binary operators.
3534///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003535static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003536 const std::vector<TreePatternNode*> &LHS,
3537 const std::vector<TreePatternNode*> &RHS,
3538 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003539 CodeGenDAGPatterns &CDP,
3540 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003541 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3542 ChildVariants.push_back(LHS);
3543 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003544 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003545}
Chris Lattner8cab0212008-01-05 22:25:12 +00003546
3547
3548static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3549 std::vector<TreePatternNode *> &Children) {
3550 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3551 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003552
Chris Lattner8cab0212008-01-05 22:25:12 +00003553 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003554 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003555 N->getTransformFn()) {
3556 Children.push_back(N);
3557 return;
3558 }
3559
3560 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3561 Children.push_back(N->getChild(0));
3562 else
3563 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3564
3565 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3566 Children.push_back(N->getChild(1));
3567 else
3568 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3569}
3570
3571/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3572/// the (potentially recursive) pattern by using algebraic laws.
3573///
3574static void GenerateVariantsOf(TreePatternNode *N,
3575 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003576 CodeGenDAGPatterns &CDP,
3577 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003578 // We cannot permute leaves or ComplexPattern uses.
3579 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003580 OutVariants.push_back(N);
3581 return;
3582 }
3583
3584 // Look up interesting info about the node.
3585 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3586
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003587 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003588 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003589 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003590 std::vector<TreePatternNode*> MaximalChildren;
3591 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3592
3593 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3594 // permutations.
3595 if (MaximalChildren.size() == 3) {
3596 // Find the variants of all of our maximal children.
3597 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003598 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3599 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3600 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003601
Chris Lattner8cab0212008-01-05 22:25:12 +00003602 // There are only two ways we can permute the tree:
3603 // (A op B) op C and A op (B op C)
3604 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003605
Chris Lattner8cab0212008-01-05 22:25:12 +00003606 // Generate legal pair permutations of A/B/C.
3607 std::vector<TreePatternNode*> ABVariants;
3608 std::vector<TreePatternNode*> BAVariants;
3609 std::vector<TreePatternNode*> ACVariants;
3610 std::vector<TreePatternNode*> CAVariants;
3611 std::vector<TreePatternNode*> BCVariants;
3612 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003613 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3614 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3615 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3616 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3617 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3618 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003619
3620 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003621 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3622 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3623 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3624 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3625 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3626 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003627
3628 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003629 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3630 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3631 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3632 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3633 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3634 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003635 return;
3636 }
3637 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003638
Chris Lattner8cab0212008-01-05 22:25:12 +00003639 // Compute permutations of all children.
3640 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3641 ChildVariants.resize(N->getNumChildren());
3642 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003643 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003644
3645 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003646 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003647
3648 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003649 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3650 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3651 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3652 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003653 // Don't count children which are actually register references.
3654 unsigned NC = 0;
3655 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3656 TreePatternNode *Child = N->getChild(i);
3657 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003658 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003659 Record *RR = DI->getDef();
3660 if (RR->isSubClassOf("Register"))
3661 continue;
3662 }
3663 NC++;
3664 }
3665 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003666 if (isCommIntrinsic) {
3667 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3668 // operands are the commutative operands, and there might be more operands
3669 // after those.
3670 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003671 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00003672 std::vector<std::vector<TreePatternNode*> > Variants;
3673 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3674 Variants.push_back(ChildVariants[2]);
3675 Variants.push_back(ChildVariants[1]);
3676 for (unsigned i = 3; i != NC; ++i)
3677 Variants.push_back(ChildVariants[i]);
3678 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3679 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003680 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003681 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003682 }
3683}
3684
3685
3686// GenerateVariants - Generate variants. For example, commutative patterns can
3687// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003688void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003689 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003690
Chris Lattner8cab0212008-01-05 22:25:12 +00003691 // Loop over all of the patterns we've collected, checking to see if we can
3692 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003693 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003694 // the .td file having to contain tons of variants of instructions.
3695 //
3696 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3697 // intentionally do not reconsider these. Any variants of added patterns have
3698 // already been added.
3699 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00003700 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003701 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003702 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003703 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003704 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003705 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003706 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00003707 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003708 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003709
3710 assert(!Variants.empty() && "Must create at least original variant!");
3711 Variants.erase(Variants.begin()); // Remove the original pattern.
3712
3713 if (Variants.empty()) // No variants for this pattern.
3714 continue;
3715
Chris Lattner34822f62009-08-23 04:44:11 +00003716 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00003717 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00003718 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003719
3720 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3721 TreePatternNode *Variant = Variants[v];
3722
Chris Lattner34822f62009-08-23 04:44:11 +00003723 DEBUG(errs() << " VAR#" << v << ": ";
3724 Variant->dump();
3725 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003726
Chris Lattner8cab0212008-01-05 22:25:12 +00003727 // Scan to see if an instruction or explicit pattern already matches this.
3728 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003729 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003730 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003731 if (PatternsToMatch[i].getPredicates() !=
3732 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00003733 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003734 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003735 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3736 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003737 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003738 AlreadyExists = true;
3739 break;
3740 }
3741 }
3742 // If we already have it, ignore the variant.
3743 if (AlreadyExists) continue;
3744
3745 // Otherwise, add it to the list of patterns we have.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003746 PatternsToMatch.emplace_back(
3747 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3748 Variant, PatternsToMatch[i].getDstPattern(),
3749 PatternsToMatch[i].getDstRegs(),
3750 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
Chris Lattner8cab0212008-01-05 22:25:12 +00003751 }
3752
Chris Lattner34822f62009-08-23 04:44:11 +00003753 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003754 }
3755}