blob: 6ba4a8dbda7721bfa18be6ac7f546e3cf276384e [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
Craig Topper25ce6b82015-11-26 06:30:40 +0000597 // Only keep types that have same elements as 'this'.
Craig Topper0be34582015-03-05 07:11:34 +0000598 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
Craig Topper25ce6b82015-11-26 06:30:40 +0000617 // Only keep types that have same elements as VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000618 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
Craig Topper9a44b3f2015-11-26 07:02:18 +0000638/// EnforceSameSize - 'this' is now constrained to be same size as VTOperand.
639bool EEVT::TypeSet::EnforceSameSize(EEVT::TypeSet &VTOperand,
640 TreePattern &TP) {
641 if (TP.hasError())
642 return false;
643
644 bool MadeChange = false;
645
646 // If we know one of the types, it forces the other type agree.
647 if (isConcrete()) {
648 MVT IVT = getConcrete();
649 unsigned Size = IVT.getSizeInBits();
650
651 // Only keep types that have the same size as 'this'.
652 TypeSet InputSet(VTOperand);
653
654 auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(),
655 [&](MVT VT) {
656 return VT.getSizeInBits() != Size;
657 });
658 MadeChange |= I != VTOperand.TypeVec.end();
659 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
660
661 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
662 TP.error("Type inference contradiction found, forcing '" +
663 InputSet.getName() + "' to have same size as '" +
664 getName() + "'");
665 return false;
666 }
667 } else if (VTOperand.isConcrete()) {
668 MVT IVT = VTOperand.getConcrete();
669 unsigned Size = IVT.getSizeInBits();
670
671 // Only keep types that have the same size as VTOperand.
672 TypeSet InputSet(*this);
673
674 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
675 [&](MVT VT) {
676 return VT.getSizeInBits() != Size;
677 });
678 MadeChange |= I != TypeVec.end();
679 TypeVec.erase(I, TypeVec.end());
680
681 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
682 TP.error("Type inference contradiction found, forcing '" +
683 InputSet.getName() + "' to have same size as '" +
684 VTOperand.getName() + "'");
685 return false;
686 }
687 }
688
689 return MadeChange;
690}
691
Chris Lattnercabe0372010-03-15 06:00:16 +0000692//===----------------------------------------------------------------------===//
693// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000694
Scott Michel94420742008-03-05 17:49:05 +0000695/// Dependent variable map for CodeGenDAGPattern variant generation
696typedef std::map<std::string, int> DepVarMap;
697
Chris Lattner514e2922011-04-17 21:38:24 +0000698static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000699 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000700 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000701 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000702 } else {
703 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
704 FindDepVarsOf(N->getChild(i), DepMap);
705 }
706}
Chris Lattner514e2922011-04-17 21:38:24 +0000707
708/// Find dependent variables within child patterns
709static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000710 DepVarMap depcounts;
711 FindDepVarsOf(N, depcounts);
Craig Topper306cb122015-11-22 20:46:24 +0000712 for (const std::pair<std::string, int> &Pair : depcounts) {
713 if (Pair.second > 1)
714 DepVars.insert(Pair.first);
Scott Michel94420742008-03-05 17:49:05 +0000715 }
716}
717
Daniel Dunbarba66a812010-10-08 02:07:22 +0000718#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000719/// Dump the dependent variable set:
720static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000721 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000722 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000723 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000724 DEBUG(errs() << "[ ");
Craig Topper306cb122015-11-22 20:46:24 +0000725 for (const std::string &DepVar : DepVars) {
726 DEBUG(errs() << DepVar << " ");
Scott Michel94420742008-03-05 17:49:05 +0000727 }
Chris Lattner34822f62009-08-23 04:44:11 +0000728 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000729 }
730}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000731#endif
732
Chris Lattner514e2922011-04-17 21:38:24 +0000733
734//===----------------------------------------------------------------------===//
735// TreePredicateFn Implementation
736//===----------------------------------------------------------------------===//
737
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000738/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
739TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
740 assert((getPredCode().empty() || getImmCode().empty()) &&
741 ".td file corrupt: can't have a node predicate *and* an imm predicate");
742}
743
Chris Lattner514e2922011-04-17 21:38:24 +0000744std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000745 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000746}
747
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000748std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000749 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000750}
751
Chris Lattner514e2922011-04-17 21:38:24 +0000752
753/// isAlwaysTrue - Return true if this is a noop predicate.
754bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000755 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000756}
757
758/// Return the name to use in the generated code to reference this, this is
759/// "Predicate_foo" if from a pattern fragment "foo".
760std::string TreePredicateFn::getFnName() const {
761 return "Predicate_" + PatFragRec->getRecord()->getName();
762}
763
764/// getCodeToRunOnSDNode - Return the code for the function body that
765/// evaluates this predicate. The argument is expected to be in "Node",
766/// not N. This handles casting and conversion to a concrete node type as
767/// appropriate.
768std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000769 // Handle immediate predicates first.
770 std::string ImmCode = getImmCode();
771 if (!ImmCode.empty()) {
772 std::string Result =
773 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000774 return Result + ImmCode;
775 }
776
777 // Handle arbitrary node predicates.
778 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000779 std::string ClassName;
780 if (PatFragRec->getOnlyTree()->isLeaf())
781 ClassName = "SDNode";
782 else {
783 Record *Op = PatFragRec->getOnlyTree()->getOperator();
784 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
785 }
786 std::string Result;
787 if (ClassName == "SDNode")
788 Result = " SDNode *N = Node;\n";
789 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000790 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000791
792 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000793}
794
Chris Lattner8cab0212008-01-05 22:25:12 +0000795//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000796// PatternToMatch implementation
797//
798
Chris Lattner05925fe2010-03-29 01:40:38 +0000799
800/// getPatternSize - Return the 'size' of this pattern. We want to match large
801/// patterns before small ones. This is used to determine the size of a
802/// pattern.
803static unsigned getPatternSize(const TreePatternNode *P,
804 const CodeGenDAGPatterns &CGP) {
805 unsigned Size = 3; // The node itself.
806 // If the root node is a ConstantSDNode, increases its size.
807 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000808 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000809 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000810
Chris Lattner05925fe2010-03-29 01:40:38 +0000811 // FIXME: This is a hack to statically increase the priority of patterns
812 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
813 // Later we can allow complexity / cost for each pattern to be (optionally)
814 // specified. To get best possible pattern match we'll need to dynamically
815 // calculate the complexity of all patterns a dag can potentially map to.
816 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000817 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000818 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000819
Tim Northoverc807a172014-05-20 11:52:46 +0000820 // We don't want to count any children twice, so return early.
821 return Size;
822 }
823
Chris Lattner05925fe2010-03-29 01:40:38 +0000824 // If this node has some predicate function that must match, it adds to the
825 // complexity of this node.
826 if (!P->getPredicateFns().empty())
827 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000828
Chris Lattner05925fe2010-03-29 01:40:38 +0000829 // Count children in the count if they are also nodes.
830 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
831 TreePatternNode *Child = P->getChild(i);
832 if (!Child->isLeaf() && Child->getNumTypes() &&
833 Child->getType(0) != MVT::Other)
834 Size += getPatternSize(Child, CGP);
835 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000836 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000837 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
838 else if (Child->getComplexPatternInfo(CGP))
839 Size += getPatternSize(Child, CGP);
840 else if (!Child->getPredicateFns().empty())
841 ++Size;
842 }
843 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000844
Chris Lattner05925fe2010-03-29 01:40:38 +0000845 return Size;
846}
847
848/// Compute the complexity metric for the input pattern. This roughly
849/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000850int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000851getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
852 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
853}
854
855
Dan Gohman49e19e92008-08-22 00:20:26 +0000856/// getPredicateCheck - Return a single string containing all of this
857/// pattern's predicates concatenated with "&&" operators.
858///
859std::string PatternToMatch::getPredicateCheck() const {
Craig Topper8985efe2015-11-27 05:44:04 +0000860 SmallVector<Record *, 4> PredicateRecs;
Craig Topperef0578a2015-06-02 04:15:51 +0000861 for (Init *I : Predicates->getValues()) {
862 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000863 Record *Def = Pred->getDef();
864 if (!Def->isSubClassOf("Predicate")) {
865#ifndef NDEBUG
866 Def->dump();
867#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000868 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000869 }
Craig Topper8985efe2015-11-27 05:44:04 +0000870 PredicateRecs.push_back(Def);
Dan Gohman49e19e92008-08-22 00:20:26 +0000871 }
872 }
Craig Topper8985efe2015-11-27 05:44:04 +0000873 // Sort so that different orders get canonicalized to the same string.
874 std::sort(PredicateRecs.begin(), PredicateRecs.end(), LessRecord());
875
876 std::string PredicateCheck;
877 for (Record *Pred : PredicateRecs) {
878 if (!PredicateCheck.empty())
879 PredicateCheck += " && ";
880 PredicateCheck += "(" + Pred->getValueAsString("CondString") + ")";
881 }
Dan Gohman49e19e92008-08-22 00:20:26 +0000882
883 return PredicateCheck;
884}
885
886//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000887// SDTypeConstraint implementation
888//
889
890SDTypeConstraint::SDTypeConstraint(Record *R) {
891 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000892
Chris Lattner8cab0212008-01-05 22:25:12 +0000893 if (R->isSubClassOf("SDTCisVT")) {
894 ConstraintType = SDTCisVT;
895 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000896 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000897 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000898
Chris Lattner8cab0212008-01-05 22:25:12 +0000899 } else if (R->isSubClassOf("SDTCisPtrTy")) {
900 ConstraintType = SDTCisPtrTy;
901 } else if (R->isSubClassOf("SDTCisInt")) {
902 ConstraintType = SDTCisInt;
903 } else if (R->isSubClassOf("SDTCisFP")) {
904 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000905 } else if (R->isSubClassOf("SDTCisVec")) {
906 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000907 } else if (R->isSubClassOf("SDTCisSameAs")) {
908 ConstraintType = SDTCisSameAs;
909 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
910 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
911 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000912 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000913 R->getValueAsInt("OtherOperandNum");
914 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
915 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000916 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000917 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000918 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
919 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000920 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000921 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
922 ConstraintType = SDTCisSubVecOfVec;
923 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
924 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000925 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
926 ConstraintType = SDTCVecEltisVT;
927 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
928 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
929 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
930 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
931 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
932 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
933 "as SDTCVecEltisVT");
934 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
935 ConstraintType = SDTCisSameNumEltsAs;
936 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
937 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +0000938 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
939 ConstraintType = SDTCisSameSizeAs;
940 x.SDTCisSameSizeAs_Info.OtherOperandNum =
941 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000942 } else {
James Y Knighte452e272015-05-11 22:17:13 +0000943 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +0000944 }
945}
946
947/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000948/// N, and the result number in ResNo.
949static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
950 const SDNodeInfo &NodeInfo,
951 unsigned &ResNo) {
952 unsigned NumResults = NodeInfo.getNumResults();
953 if (OpNo < NumResults) {
954 ResNo = OpNo;
955 return N;
956 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000957
Chris Lattner2db7aba2010-03-19 21:56:21 +0000958 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000959
Chris Lattner2db7aba2010-03-19 21:56:21 +0000960 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +0000961 std::string S;
962 raw_string_ostream OS(S);
963 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000964 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +0000965 N->print(OS);
966 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +0000967 }
968
Chris Lattner2db7aba2010-03-19 21:56:21 +0000969 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000970}
971
972/// ApplyTypeConstraint - Given a node in a pattern, apply this type
973/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000974/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000975bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
976 const SDNodeInfo &NodeInfo,
977 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000978 if (TP.hasError())
979 return false;
980
Chris Lattner2db7aba2010-03-19 21:56:21 +0000981 unsigned ResNo = 0; // The result number being referenced.
982 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000983
Chris Lattner8cab0212008-01-05 22:25:12 +0000984 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000985 case SDTCisVT:
986 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000987 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000988 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000989 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000990 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000991 case SDTCisInt:
992 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000993 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000994 case SDTCisFP:
995 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000996 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000997 case SDTCisVec:
998 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000999 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001000 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001001 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001002 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001003 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001004 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1005 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001006 }
1007 case SDTCisVTSmallerThanOp: {
1008 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1009 // have an integer type that is smaller than the VT.
1010 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001011 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001012 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001013 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001014 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001015 return false;
1016 }
Owen Anderson9f944592009-08-11 20:47:22 +00001017 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +00001018 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001019
Chris Lattner38c99662010-03-24 00:06:46 +00001020 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001021
Chris Lattner2db7aba2010-03-19 21:56:21 +00001022 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001023 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001024 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1025 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001026
Chris Lattner38c99662010-03-24 00:06:46 +00001027 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001028 }
1029 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001030 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001031 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001032 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1033 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +00001034 return NodeToApply->getExtType(ResNo).
1035 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001036 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001037 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001038 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001039 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001040 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1041 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001042
Chris Lattner57ebf632010-03-24 00:01:16 +00001043 // Filter vector types out of VecOperand that don't have the right element
1044 // type.
1045 return VecOperand->getExtType(VResNo).
1046 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +00001047 }
David Greene127fd1d2011-01-24 20:53:18 +00001048 case SDTCisSubVecOfVec: {
1049 unsigned VResNo = 0;
1050 TreePatternNode *BigVecOperand =
1051 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1052 VResNo);
1053
1054 // Filter vector types out of BigVecOperand that don't have the
1055 // right subvector type.
1056 return BigVecOperand->getExtType(VResNo).
1057 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1058 }
Craig Topper0be34582015-03-05 07:11:34 +00001059 case SDTCVecEltisVT: {
1060 return NodeToApply->getExtType(ResNo).
1061 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1062 }
1063 case SDTCisSameNumEltsAs: {
1064 unsigned OResNo = 0;
1065 TreePatternNode *OtherNode =
1066 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1067 N, NodeInfo, OResNo);
1068 return OtherNode->getExtType(OResNo).
1069 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1070 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001071 case SDTCisSameSizeAs: {
1072 unsigned OResNo = 0;
1073 TreePatternNode *OtherNode =
1074 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1075 N, NodeInfo, OResNo);
1076 return OtherNode->getExtType(OResNo).
1077 EnforceSameSize(NodeToApply->getExtType(ResNo), TP);
1078 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001079 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001080 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001081}
1082
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001083// Update the node type to match an instruction operand or result as specified
1084// in the ins or outs lists on the instruction definition. Return true if the
1085// type was actually changed.
1086bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1087 Record *Operand,
1088 TreePattern &TP) {
1089 // The 'unknown' operand indicates that types should be inferred from the
1090 // context.
1091 if (Operand->isSubClassOf("unknown_class"))
1092 return false;
1093
1094 // The Operand class specifies a type directly.
1095 if (Operand->isSubClassOf("Operand"))
1096 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1097 TP);
1098
1099 // PointerLikeRegClass has a type that is determined at runtime.
1100 if (Operand->isSubClassOf("PointerLikeRegClass"))
1101 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1102
1103 // Both RegisterClass and RegisterOperand operands derive their types from a
1104 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001105 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001106 if (Operand->isSubClassOf("RegisterClass"))
1107 RC = Operand;
1108 else if (Operand->isSubClassOf("RegisterOperand"))
1109 RC = Operand->getValueAsDef("RegClass");
1110
1111 assert(RC && "Unknown operand type");
1112 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1113 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1114}
1115
1116
Chris Lattner8cab0212008-01-05 22:25:12 +00001117//===----------------------------------------------------------------------===//
1118// SDNodeInfo implementation
1119//
1120SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1121 EnumName = R->getValueAsString("Opcode");
1122 SDClassName = R->getValueAsString("SDClass");
1123 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1124 NumResults = TypeProfile->getValueAsInt("NumResults");
1125 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001126
Chris Lattner8cab0212008-01-05 22:25:12 +00001127 // Parse the properties.
1128 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001129 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1130 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001131 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001132 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001133 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001134 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001135 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001136 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001137 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001138 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001139 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001140 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001141 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001142 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001143 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001144 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001145 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001146 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001147 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001148 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001149 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001150 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001151 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001152 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001153 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001154 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001155 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001156 }
1157 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001158
1159
Chris Lattner8cab0212008-01-05 22:25:12 +00001160 // Parse the type constraints.
1161 std::vector<Record*> ConstraintList =
1162 TypeProfile->getValueAsListOfDefs("Constraints");
1163 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1164}
1165
Chris Lattner99e53b32010-02-28 00:22:30 +00001166/// getKnownType - If the type constraints on this node imply a fixed type
1167/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001168/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001169MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001170 unsigned NumResults = getNumResults();
1171 assert(NumResults <= 1 &&
1172 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001173 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001174
Craig Topper306cb122015-11-22 20:46:24 +00001175 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001176 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001177 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001178 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001179
Craig Topper306cb122015-11-22 20:46:24 +00001180 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001181 default: break;
1182 case SDTypeConstraint::SDTCisVT:
Craig Topper306cb122015-11-22 20:46:24 +00001183 return Constraint.x.SDTCisVT_Info.VT;
Chris Lattner99e53b32010-02-28 00:22:30 +00001184 case SDTypeConstraint::SDTCisPtrTy:
1185 return MVT::iPTR;
1186 }
1187 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001188 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001189}
1190
Chris Lattner8cab0212008-01-05 22:25:12 +00001191//===----------------------------------------------------------------------===//
1192// TreePatternNode implementation
1193//
1194
1195TreePatternNode::~TreePatternNode() {
1196#if 0 // FIXME: implement refcounted tree nodes!
1197 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1198 delete getChild(i);
1199#endif
1200}
1201
Chris Lattnerf1447252010-03-19 21:37:09 +00001202static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1203 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001204 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001205 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001206
Chris Lattner2109cb42010-03-22 20:56:36 +00001207 if (Operator->isSubClassOf("Intrinsic"))
1208 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001209
Chris Lattnerf1447252010-03-19 21:37:09 +00001210 if (Operator->isSubClassOf("SDNode"))
1211 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001212
Chris Lattnerf1447252010-03-19 21:37:09 +00001213 if (Operator->isSubClassOf("PatFrag")) {
1214 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1215 // the forward reference case where one pattern fragment references another
1216 // before it is processed.
1217 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1218 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001219
Chris Lattnerf1447252010-03-19 21:37:09 +00001220 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001221 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001222 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001223 if (Tree)
1224 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1225 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001226 assert(Op && "Invalid Fragment");
1227 return GetNumNodeResults(Op, CDP);
1228 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001229
Chris Lattnerf1447252010-03-19 21:37:09 +00001230 if (Operator->isSubClassOf("Instruction")) {
1231 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001232
Craig Topper3a8eb892015-03-20 05:09:06 +00001233 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1234
1235 // Subtract any defaulted outputs.
1236 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1237 Record *OperandNode = InstInfo.Operands[i].Rec;
1238
1239 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1240 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1241 --NumDefsToAdd;
1242 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001243
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001244 // Add on one implicit def if it has a resolvable type.
1245 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1246 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001247 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001248 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001249
Chris Lattnerf1447252010-03-19 21:37:09 +00001250 if (Operator->isSubClassOf("SDNodeXForm"))
1251 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001252
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001253 if (Operator->isSubClassOf("ValueType"))
1254 return 1; // A type-cast of one result.
1255
Tim Northoverc807a172014-05-20 11:52:46 +00001256 if (Operator->isSubClassOf("ComplexPattern"))
1257 return 1;
1258
Chris Lattnerf1447252010-03-19 21:37:09 +00001259 Operator->dump();
James Y Knighte452e272015-05-11 22:17:13 +00001260 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001261}
1262
1263void TreePatternNode::print(raw_ostream &OS) const {
1264 if (isLeaf())
1265 OS << *getLeafValue();
1266 else
1267 OS << '(' << getOperator()->getName();
1268
1269 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1270 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001271
1272 if (!isLeaf()) {
1273 if (getNumChildren() != 0) {
1274 OS << " ";
1275 getChild(0)->print(OS);
1276 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1277 OS << ", ";
1278 getChild(i)->print(OS);
1279 }
1280 }
1281 OS << ")";
1282 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001283
Craig Topper306cb122015-11-22 20:46:24 +00001284 for (const TreePredicateFn &Pred : PredicateFns)
1285 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001286 if (TransformFn)
1287 OS << "<<X:" << TransformFn->getName() << ">>";
1288 if (!getName().empty())
1289 OS << ":$" << getName();
1290
1291}
1292void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001293 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001294}
1295
Scott Michel94420742008-03-05 17:49:05 +00001296/// isIsomorphicTo - Return true if this node is recursively
1297/// isomorphic to the specified node. For this comparison, the node's
1298/// entire state is considered. The assigned name is ignored, since
1299/// nodes with differing names are considered isomorphic. However, if
1300/// the assigned name is present in the dependent variable set, then
1301/// the assigned name is considered significant and the node is
1302/// isomorphic if the names match.
1303bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1304 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001305 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001306 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001307 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001308 getTransformFn() != N->getTransformFn())
1309 return false;
1310
1311 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001312 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1313 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001314 return ((DI->getDef() == NDI->getDef())
1315 && (DepVars.find(getName()) == DepVars.end()
1316 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001317 }
1318 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001319 return getLeafValue() == N->getLeafValue();
1320 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001321
Chris Lattner8cab0212008-01-05 22:25:12 +00001322 if (N->getOperator() != getOperator() ||
1323 N->getNumChildren() != getNumChildren()) return false;
1324 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001325 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001326 return false;
1327 return true;
1328}
1329
1330/// clone - Make a copy of this tree and all of its children.
1331///
1332TreePatternNode *TreePatternNode::clone() const {
1333 TreePatternNode *New;
1334 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001335 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001336 } else {
1337 std::vector<TreePatternNode*> CChildren;
1338 CChildren.reserve(Children.size());
1339 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1340 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001341 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001342 }
1343 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001344 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001345 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001346 New->setTransformFn(getTransformFn());
1347 return New;
1348}
1349
Chris Lattner53c39ba2010-02-14 22:22:58 +00001350/// RemoveAllTypes - Recursively strip all the types of this tree.
1351void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001352 // Reset to unknown type.
1353 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001354 if (isLeaf()) return;
1355 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1356 getChild(i)->RemoveAllTypes();
1357}
1358
1359
Chris Lattner8cab0212008-01-05 22:25:12 +00001360/// SubstituteFormalArguments - Replace the formal arguments in this tree
1361/// with actual values specified by ArgMap.
1362void TreePatternNode::
1363SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1364 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001365
Chris Lattner8cab0212008-01-05 22:25:12 +00001366 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1367 TreePatternNode *Child = getChild(i);
1368 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001369 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001370 // Note that, when substituting into an output pattern, Val might be an
1371 // UnsetInit.
1372 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1373 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001374 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001375 TreePatternNode *NewChild = ArgMap[Child->getName()];
1376 assert(NewChild && "Couldn't find formal argument!");
1377 assert((Child->getPredicateFns().empty() ||
1378 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1379 "Non-empty child predicate clobbered!");
1380 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001381 }
1382 } else {
1383 getChild(i)->SubstituteFormalArguments(ArgMap);
1384 }
1385 }
1386}
1387
1388
1389/// InlinePatternFragments - If this pattern refers to any pattern
1390/// fragments, inline them into place, giving us a pattern without any
1391/// PatFrag references.
1392TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001393 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001394 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001395
1396 if (isLeaf())
1397 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001398 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001399
Chris Lattner8cab0212008-01-05 22:25:12 +00001400 if (!Op->isSubClassOf("PatFrag")) {
1401 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001402 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1403 TreePatternNode *Child = getChild(i);
1404 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1405
1406 assert((Child->getPredicateFns().empty() ||
1407 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1408 "Non-empty child predicate clobbered!");
1409
1410 setChild(i, NewChild);
1411 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001412 return this;
1413 }
1414
1415 // Otherwise, we found a reference to a fragment. First, look up its
1416 // TreePattern record.
1417 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001418
Chris Lattner8cab0212008-01-05 22:25:12 +00001419 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001420 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001421 TP.error("'" + Op->getName() + "' fragment requires " +
1422 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001423 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001424 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001425
1426 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1427
Chris Lattner514e2922011-04-17 21:38:24 +00001428 TreePredicateFn PredFn(Frag);
1429 if (!PredFn.isAlwaysTrue())
1430 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001431
Chris Lattner8cab0212008-01-05 22:25:12 +00001432 // Resolve formal arguments to their actual value.
1433 if (Frag->getNumArgs()) {
1434 // Compute the map of formal to actual arguments.
1435 std::map<std::string, TreePatternNode*> ArgMap;
1436 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1437 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001438
Chris Lattner8cab0212008-01-05 22:25:12 +00001439 FragTree->SubstituteFormalArguments(ArgMap);
1440 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001441
Chris Lattner8cab0212008-01-05 22:25:12 +00001442 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001443 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1444 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001445
1446 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001447 for (const TreePredicateFn &Pred : getPredicateFns())
1448 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001449
Chris Lattner8cab0212008-01-05 22:25:12 +00001450 // Get a new copy of this fragment to stitch into here.
1451 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001452
Chris Lattner2e253b42008-06-30 03:02:03 +00001453 // The fragment we inlined could have recursive inlining that is needed. See
1454 // if there are any pattern fragments in it and inline them as needed.
1455 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001456}
1457
1458/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001459/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001460/// references from the register file information, for example.
1461///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001462/// When Unnamed is set, return the type of a DAG operand with no name, such as
1463/// the F8RC register class argument in:
1464///
1465/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1466///
1467/// When Unnamed is false, return the type of a named DAG operand such as the
1468/// GPR:$src operand above.
1469///
Chris Lattnerf1447252010-03-19 21:37:09 +00001470static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001471 bool NotRegisters,
1472 bool Unnamed,
1473 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001474 // Check to see if this is a register operand.
1475 if (R->isSubClassOf("RegisterOperand")) {
1476 assert(ResNo == 0 && "Regoperand ref only has one result!");
1477 if (NotRegisters)
1478 return EEVT::TypeSet(); // Unknown.
1479 Record *RegClass = R->getValueAsDef("RegClass");
1480 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1481 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1482 }
1483
Chris Lattnercabe0372010-03-15 06:00:16 +00001484 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001485 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001486 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001487 // An unnamed register class represents itself as an i32 immediate, for
1488 // example on a COPY_TO_REGCLASS instruction.
1489 if (Unnamed)
1490 return EEVT::TypeSet(MVT::i32, TP);
1491
1492 // In a named operand, the register class provides the possible set of
1493 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001494 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001495 return EEVT::TypeSet(); // Unknown.
1496 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1497 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001498 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001499
Chris Lattner6070ee22010-03-23 23:50:31 +00001500 if (R->isSubClassOf("PatFrag")) {
1501 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001502 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001503 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001504 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001505
Chris Lattner6070ee22010-03-23 23:50:31 +00001506 if (R->isSubClassOf("Register")) {
1507 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001508 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001509 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001510 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001511 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001512 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001513
1514 if (R->isSubClassOf("SubRegIndex")) {
1515 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001516 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001517 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001518
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001519 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001520 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001521 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1522 //
1523 // (sext_inreg GPR:$src, i16)
1524 // ~~~
1525 if (Unnamed)
1526 return EEVT::TypeSet(MVT::Other, TP);
1527 // With a name, the ValueType simply provides the type of the named
1528 // variable.
1529 //
1530 // (sext_inreg i32:$src, i16)
1531 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001532 if (NotRegisters)
1533 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001534 return EEVT::TypeSet(getValueType(R), TP);
1535 }
1536
1537 if (R->isSubClassOf("CondCode")) {
1538 assert(ResNo == 0 && "This node only has one result!");
1539 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001540 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001541 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001542
Chris Lattner6070ee22010-03-23 23:50:31 +00001543 if (R->isSubClassOf("ComplexPattern")) {
1544 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001545 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001546 return EEVT::TypeSet(); // Unknown.
1547 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1548 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001549 }
1550 if (R->isSubClassOf("PointerLikeRegClass")) {
1551 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001552 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001553 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001554
Chris Lattner6070ee22010-03-23 23:50:31 +00001555 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1556 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001557 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001558 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001559 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001560
Tim Northoverc807a172014-05-20 11:52:46 +00001561 if (R->isSubClassOf("Operand"))
1562 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1563
Chris Lattner8cab0212008-01-05 22:25:12 +00001564 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001565 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001566}
1567
Chris Lattner89c65662008-01-06 05:36:50 +00001568
1569/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1570/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1571const CodeGenIntrinsic *TreePatternNode::
1572getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1573 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1574 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1575 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001576 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001577
Sean Silva88eb8dd2012-10-10 20:24:47 +00001578 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001579 return &CDP.getIntrinsicInfo(IID);
1580}
1581
Chris Lattner53c39ba2010-02-14 22:22:58 +00001582/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1583/// return the ComplexPattern information, otherwise return null.
1584const ComplexPattern *
1585TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001586 Record *Rec;
1587 if (isLeaf()) {
1588 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1589 if (!DI)
1590 return nullptr;
1591 Rec = DI->getDef();
1592 } else
1593 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001594
Tim Northoverc807a172014-05-20 11:52:46 +00001595 if (!Rec->isSubClassOf("ComplexPattern"))
1596 return nullptr;
1597 return &CGP.getComplexPattern(Rec);
1598}
1599
1600unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1601 // A ComplexPattern specifically declares how many results it fills in.
1602 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1603 return CP->getNumOperands();
1604
1605 // If MIOperandInfo is specified, that gives the count.
1606 if (isLeaf()) {
1607 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1608 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1609 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1610 if (MIOps->getNumArgs())
1611 return MIOps->getNumArgs();
1612 }
1613 }
1614
1615 // Otherwise there is just one result.
1616 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001617}
1618
1619/// NodeHasProperty - Return true if this node has the specified property.
1620bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001621 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001622 if (isLeaf()) {
1623 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1624 return CP->hasProperty(Property);
1625 return false;
1626 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001627
Chris Lattner53c39ba2010-02-14 22:22:58 +00001628 Record *Operator = getOperator();
1629 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001630
Chris Lattner53c39ba2010-02-14 22:22:58 +00001631 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1632}
1633
1634
1635
1636
1637/// TreeHasProperty - Return true if any node in this tree has the specified
1638/// property.
1639bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001640 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001641 if (NodeHasProperty(Property, CGP))
1642 return true;
1643 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1644 if (getChild(i)->TreeHasProperty(Property, CGP))
1645 return true;
1646 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001647}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001648
Evan Cheng49bad4c2008-06-16 20:29:38 +00001649/// isCommutativeIntrinsic - Return true if the node corresponds to a
1650/// commutative intrinsic.
1651bool
1652TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1653 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1654 return Int->isCommutative;
1655 return false;
1656}
1657
Matt Arsenaulteb492162014-11-02 23:46:51 +00001658static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1659 if (!N->isLeaf())
1660 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001661
Matt Arsenaulteb492162014-11-02 23:46:51 +00001662 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1663 if (DI && DI->getDef()->isSubClassOf(Class))
1664 return true;
1665
1666 return false;
1667}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001668
1669static void emitTooManyOperandsError(TreePattern &TP,
1670 StringRef InstName,
1671 unsigned Expected,
1672 unsigned Actual) {
1673 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1674 " operands but expected only " + Twine(Expected) + "!");
1675}
1676
1677static void emitTooFewOperandsError(TreePattern &TP,
1678 StringRef InstName,
1679 unsigned Actual) {
1680 TP.error("Instruction '" + InstName +
1681 "' expects more than the provided " + Twine(Actual) + " operands!");
1682}
1683
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001684/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001685/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001686/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001687bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001688 if (TP.hasError())
1689 return false;
1690
Chris Lattnerab3242f2008-01-06 01:10:31 +00001691 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001692 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001693 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001694 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001695 bool MadeChange = false;
1696 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1697 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001698 NotRegisters,
1699 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001700 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001701 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001702
Sean Silvafb509ed2012-10-10 20:24:43 +00001703 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001704 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001705
Chris Lattnerf1447252010-03-19 21:37:09 +00001706 // Int inits are always integers. :)
1707 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001708
Chris Lattnerf1447252010-03-19 21:37:09 +00001709 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001710 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001711
Chris Lattnerf1447252010-03-19 21:37:09 +00001712 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001713 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1714 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001715
Craig Topper95198f42013-09-25 06:37:18 +00001716 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001717 // Make sure that the value is representable for this type.
1718 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001719
Richard Smith228e6d42012-08-24 23:29:28 +00001720 // Check that the value doesn't use more bits than we have. It must either
1721 // be a sign- or zero-extended equivalent of the original.
1722 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1723 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001724 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001725
Richard Smith228e6d42012-08-24 23:29:28 +00001726 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001727 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001728 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001729 }
1730 return false;
1731 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001732
Chris Lattner8cab0212008-01-05 22:25:12 +00001733 // special handling for set, which isn't really an SDNode.
1734 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001735 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1736 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001737 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001738
Chris Lattnerf1447252010-03-19 21:37:09 +00001739 TreePatternNode *SetVal = getChild(NC-1);
1740 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1741
Elena Demikhovsky09954792015-03-01 08:23:41 +00001742 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001743 TreePatternNode *Child = getChild(i);
1744 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001745
Chris Lattner8cab0212008-01-05 22:25:12 +00001746 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001747 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1748 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001749 }
1750 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001751 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001752
Chris Lattner5c2182e2010-03-27 02:53:27 +00001753 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001754 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1755
Chris Lattner8cab0212008-01-05 22:25:12 +00001756 bool MadeChange = false;
1757 for (unsigned i = 0; i < getNumChildren(); ++i)
1758 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001759 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001760 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001761
Chris Lattneree820ac2010-02-23 05:51:07 +00001762 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001763 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001764
Chris Lattner8cab0212008-01-05 22:25:12 +00001765 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001766 unsigned NumRetVTs = Int->IS.RetVTs.size();
1767 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001768
Bill Wendling91821472008-11-13 09:08:33 +00001769 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001770 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001771
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001772 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001773 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001774 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001775 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001776 return false;
1777 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001778
1779 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001780 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001781
Chris Lattnerf1447252010-03-19 21:37:09 +00001782 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1783 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001784
Chris Lattnerf1447252010-03-19 21:37:09 +00001785 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1786 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1787 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001788 }
1789 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001790 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001791
Chris Lattneree820ac2010-02-23 05:51:07 +00001792 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001793 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001794
Chris Lattner135091b2010-03-28 08:48:47 +00001795 // Check that the number of operands is sane. Negative operands -> varargs.
1796 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001797 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001798 TP.error(getOperator()->getName() + " node requires exactly " +
1799 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001800 return false;
1801 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001802
Chris Lattner8cab0212008-01-05 22:25:12 +00001803 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1804 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1805 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001806 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001807 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001808
Chris Lattneree820ac2010-02-23 05:51:07 +00001809 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001810 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001811 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001812 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001813
Chris Lattnerd44966f2010-03-27 19:15:02 +00001814 bool MadeChange = false;
1815
1816 // Apply the result types to the node, these come from the things in the
1817 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001818 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1819 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001820 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1821 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001822
Chris Lattnerd44966f2010-03-27 19:15:02 +00001823 // If the instruction has implicit defs, we apply the first one as a result.
1824 // FIXME: This sucks, it should apply all implicit defs.
1825 if (!InstInfo.ImplicitDefs.empty()) {
1826 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001827
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001828 // FIXME: Generalize to multiple possible types and multiple possible
1829 // ImplicitDefs.
1830 MVT::SimpleValueType VT =
1831 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001832
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001833 if (VT != MVT::Other)
1834 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001835 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001836
Chris Lattnercabe0372010-03-15 06:00:16 +00001837 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1838 // be the same.
1839 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001840 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1841 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1842 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001843 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1844 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1845 // variadic.
1846
1847 unsigned NChild = getNumChildren();
1848 if (NChild < 3) {
1849 TP.error("REG_SEQUENCE requires at least 3 operands!");
1850 return false;
1851 }
1852
1853 if (NChild % 2 == 0) {
1854 TP.error("REG_SEQUENCE requires an odd number of operands!");
1855 return false;
1856 }
1857
1858 if (!isOperandClass(getChild(0), "RegisterClass")) {
1859 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1860 return false;
1861 }
1862
1863 for (unsigned I = 1; I < NChild; I += 2) {
1864 TreePatternNode *SubIdxChild = getChild(I + 1);
1865 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1866 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1867 itostr(I + 1) + "!");
1868 return false;
1869 }
1870 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001871 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001872
1873 unsigned ChildNo = 0;
1874 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1875 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001876
Chris Lattner8cab0212008-01-05 22:25:12 +00001877 // If the instruction expects a predicate or optional def operand, we
1878 // codegen this by setting the operand to it's default value if it has a
1879 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001880 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001881 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1882 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001883
Chris Lattner8cab0212008-01-05 22:25:12 +00001884 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001885 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001886 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001887 return false;
1888 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001889
Chris Lattner8cab0212008-01-05 22:25:12 +00001890 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001891 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001892
1893 // If the operand has sub-operands, they may be provided by distinct
1894 // child patterns, so attempt to match each sub-operand separately.
1895 if (OperandNode->isSubClassOf("Operand")) {
1896 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1897 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1898 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001899 // a single ComplexPattern-related Operand.
1900
1901 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001902 // Match first sub-operand against the child we already have.
1903 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1904 MadeChange |=
1905 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1906
1907 // And the remaining sub-operands against subsequent children.
1908 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1909 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001910 emitTooFewOperandsError(TP, getOperator()->getName(),
1911 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001912 return false;
1913 }
1914 Child = getChild(ChildNo++);
1915
1916 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1917 MadeChange |=
1918 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1919 }
1920 continue;
1921 }
1922 }
1923 }
1924
1925 // If we didn't match by pieces above, attempt to match the whole
1926 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001927 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001928 }
Christopher Lamba7312392008-03-11 09:33:47 +00001929
Matt Arsenaulteb492162014-11-02 23:46:51 +00001930 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001931 emitTooManyOperandsError(TP, getOperator()->getName(),
1932 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001933 return false;
1934 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001935
Ulrich Weigande618abd2013-03-19 19:51:09 +00001936 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1937 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001938 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001939 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001940
Tim Northoverc807a172014-05-20 11:52:46 +00001941 if (getOperator()->isSubClassOf("ComplexPattern")) {
1942 bool MadeChange = false;
1943
1944 for (unsigned i = 0; i < getNumChildren(); ++i)
1945 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1946
1947 return MadeChange;
1948 }
1949
Chris Lattneree820ac2010-02-23 05:51:07 +00001950 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001951
Chris Lattneree820ac2010-02-23 05:51:07 +00001952 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001953 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001954 TP.error("Node transform '" + getOperator()->getName() +
1955 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001956 return false;
1957 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001958
Chris Lattnercabe0372010-03-15 06:00:16 +00001959 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1960
Jim Grosbach65586fe2010-12-21 16:16:00 +00001961
Chris Lattneree820ac2010-02-23 05:51:07 +00001962 // If either the output or input of the xform does not have exact
1963 // type info. We assume they must be the same. Otherwise, it is perfectly
1964 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001965#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001966 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001967 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1968 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001969 return MadeChange;
1970 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001971#endif
1972 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001973}
1974
1975/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1976/// RHS of a commutative operation, not the on LHS.
1977static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1978 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1979 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001980 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001981 return true;
1982 return false;
1983}
1984
1985
1986/// canPatternMatch - If it is impossible for this pattern to match on this
1987/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001988/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001989/// that can never possibly work), and to prevent the pattern permuter from
1990/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001991bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001992 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001993 if (isLeaf()) return true;
1994
1995 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1996 if (!getChild(i)->canPatternMatch(Reason, CDP))
1997 return false;
1998
1999 // If this is an intrinsic, handle cases that would make it not match. For
2000 // example, if an operand is required to be an immediate.
2001 if (getOperator()->isSubClassOf("Intrinsic")) {
2002 // TODO:
2003 return true;
2004 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002005
Tim Northoverc807a172014-05-20 11:52:46 +00002006 if (getOperator()->isSubClassOf("ComplexPattern"))
2007 return true;
2008
Chris Lattner8cab0212008-01-05 22:25:12 +00002009 // If this node is a commutative operator, check that the LHS isn't an
2010 // immediate.
2011 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002012 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2013 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002014 // Scan all of the operands of the node and make sure that only the last one
2015 // is a constant node, unless the RHS also is.
2016 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00002017 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2018 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002019 if (OnlyOnRHSOfCommutative(getChild(i))) {
2020 Reason="Immediate value must be on the RHS of commutative operators!";
2021 return false;
2022 }
2023 }
2024 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002025
Chris Lattner8cab0212008-01-05 22:25:12 +00002026 return true;
2027}
2028
2029//===----------------------------------------------------------------------===//
2030// TreePattern implementation
2031//
2032
David Greeneaf8ee2c2011-07-29 22:43:06 +00002033TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002034 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2035 isInputPattern(isInput), HasError(false) {
Craig Topperef0578a2015-06-02 04:15:51 +00002036 for (Init *I : RawPat->getValues())
2037 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002038}
2039
David Greeneaf8ee2c2011-07-29 22:43:06 +00002040TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002041 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2042 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002043 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002044}
2045
David Blaikiecf195302014-11-17 22:55:41 +00002046TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002047 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2048 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00002049 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002050}
2051
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002052void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002053 if (HasError)
2054 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002055 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002056 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2057 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002058}
2059
Chris Lattnercabe0372010-03-15 06:00:16 +00002060void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002061 for (TreePatternNode *Tree : Trees)
2062 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002063}
2064
2065void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2066 if (!N->getName().empty())
2067 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002068
Chris Lattnercabe0372010-03-15 06:00:16 +00002069 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2070 ComputeNamedNodes(N->getChild(i));
2071}
2072
David Blaikiecf195302014-11-17 22:55:41 +00002073
2074TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002075 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002076 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002077
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002078 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002079 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002080 /// (foo GPR, imm) -> (foo GPR, (imm))
2081 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002082 return ParseTreePattern(
2083 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002084 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002085 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002086
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002087 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002088 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002089 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002090 if (OpName.empty())
2091 error("'node' argument requires a name to match with operand list");
2092 Args.push_back(OpName);
2093 }
2094
2095 Res->setName(OpName);
2096 return Res;
2097 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002098
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002099 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002100 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002101 if (OpName.empty())
2102 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002103 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002104 Args.push_back(OpName);
2105 Res->setName(OpName);
2106 return Res;
2107 }
2108
Sean Silvafb509ed2012-10-10 20:24:43 +00002109 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002110 if (!OpName.empty())
2111 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002112 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002113 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002114
Sean Silvafb509ed2012-10-10 20:24:43 +00002115 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002116 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002117 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002118 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002119 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002120 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002121 }
2122
Sean Silvafb509ed2012-10-10 20:24:43 +00002123 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002124 if (!Dag) {
2125 TheInit->dump();
2126 error("Pattern has unexpected init kind!");
2127 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002128 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002129 if (!OpDef) error("Pattern has unexpected operator type!");
2130 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002131
Chris Lattner8cab0212008-01-05 22:25:12 +00002132 if (Operator->isSubClassOf("ValueType")) {
2133 // If the operator is a ValueType, then this must be "type cast" of a leaf
2134 // node.
2135 if (Dag->getNumArgs() != 1)
2136 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002137
David Blaikiecf195302014-11-17 22:55:41 +00002138 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002139
Chris Lattner8cab0212008-01-05 22:25:12 +00002140 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002141 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2142 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002143
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002144 if (!OpName.empty())
2145 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002146 return New;
2147 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002148
Chris Lattner8cab0212008-01-05 22:25:12 +00002149 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002150 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002151 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002152 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002153 !Operator->isSubClassOf("SDNodeXForm") &&
2154 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002155 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002156 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002157 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002158 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002159
Chris Lattner8cab0212008-01-05 22:25:12 +00002160 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002161 if (isInputPattern) {
2162 if (Operator->isSubClassOf("Instruction") ||
2163 Operator->isSubClassOf("SDNodeXForm"))
2164 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2165 } else {
2166 if (Operator->isSubClassOf("Intrinsic"))
2167 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002168
Chris Lattner2e9eae12010-03-28 06:57:56 +00002169 if (Operator->isSubClassOf("SDNode") &&
2170 Operator->getName() != "imm" &&
2171 Operator->getName() != "fpimm" &&
2172 Operator->getName() != "tglobaltlsaddr" &&
2173 Operator->getName() != "tconstpool" &&
2174 Operator->getName() != "tjumptable" &&
2175 Operator->getName() != "tframeindex" &&
2176 Operator->getName() != "texternalsym" &&
2177 Operator->getName() != "tblockaddress" &&
2178 Operator->getName() != "tglobaladdr" &&
2179 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002180 Operator->getName() != "vt" &&
2181 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002182 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2183 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002184
Chris Lattner8cab0212008-01-05 22:25:12 +00002185 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002186
2187 // Parse all the operands.
2188 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002189 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002190
Chris Lattner8cab0212008-01-05 22:25:12 +00002191 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002192 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002193 // convert the intrinsic name to a number.
2194 if (Operator->isSubClassOf("Intrinsic")) {
2195 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2196 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2197
2198 // If this intrinsic returns void, it must have side-effects and thus a
2199 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002200 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002201 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002202 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002203 // Has side-effects, requires chain.
2204 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002205 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002206 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002207
David Greenee32ebf22011-07-29 19:07:07 +00002208 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002209 Children.insert(Children.begin(), IIDNode);
2210 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002211
Tim Northoverc807a172014-05-20 11:52:46 +00002212 if (Operator->isSubClassOf("ComplexPattern")) {
2213 for (unsigned i = 0; i < Children.size(); ++i) {
2214 TreePatternNode *Child = Children[i];
2215
2216 if (Child->getName().empty())
2217 error("All arguments to a ComplexPattern must be named");
2218
2219 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2220 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2221 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2222 auto OperandId = std::make_pair(Operator, i);
2223 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2224 if (PrevOp != ComplexPatternOperands.end()) {
2225 if (PrevOp->getValue() != OperandId)
2226 error("All ComplexPattern operands must appear consistently: "
2227 "in the same order in just one ComplexPattern instance.");
2228 } else
2229 ComplexPatternOperands[Child->getName()] = OperandId;
2230 }
2231 }
2232
Chris Lattnerf1447252010-03-19 21:37:09 +00002233 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002234 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002235 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002236
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002237 if (!Dag->getName().empty()) {
2238 assert(Result->getName().empty());
2239 Result->setName(Dag->getName());
2240 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002241 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002242}
2243
Chris Lattnera787c9e2010-03-28 08:38:32 +00002244/// SimplifyTree - See if we can simplify this tree to eliminate something that
2245/// will never match in favor of something obvious that will. This is here
2246/// strictly as a convenience to target authors because it allows them to write
2247/// more type generic things and have useless type casts fold away.
2248///
2249/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002250static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002251 if (N->isLeaf())
2252 return false;
2253
2254 // If we have a bitconvert with a resolved type and if the source and
2255 // destination types are the same, then the bitconvert is useless, remove it.
2256 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002257 N->getExtType(0).isConcrete() &&
2258 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2259 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002260 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002261 SimplifyTree(N);
2262 return true;
2263 }
2264
2265 // Walk all children.
2266 bool MadeChange = false;
2267 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002268 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002269 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002270 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002271 }
2272 return MadeChange;
2273}
2274
2275
2276
Chris Lattner8cab0212008-01-05 22:25:12 +00002277/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002278/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002279/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002280bool TreePattern::
2281InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2282 if (NamedNodes.empty())
2283 ComputeNamedNodes();
2284
Chris Lattner8cab0212008-01-05 22:25:12 +00002285 bool MadeChange = true;
2286 while (MadeChange) {
2287 MadeChange = false;
Craig Topper306cb122015-11-22 20:46:24 +00002288 for (TreePatternNode *Tree : Trees) {
2289 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2290 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002291 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002292
2293 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002294 for (auto &Entry : NamedNodes) {
2295 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002296
Chris Lattnercabe0372010-03-15 06:00:16 +00002297 // If we have input named node types, propagate their types to the named
2298 // values here.
2299 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002300 if (!InNamedTypes->count(Entry.getKey())) {
2301 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002302 "' in output pattern but not input pattern");
2303 return true;
2304 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002305
2306 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002307 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002308
2309 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002310 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002311 // If this node is a register class, and it is the root of the pattern
2312 // then we're mapping something onto an input register. We allow
2313 // changing the type of the input register in this case. This allows
2314 // us to match things like:
2315 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002316 if (Node == Trees[0] && Node->isLeaf()) {
2317 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002318 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2319 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002320 continue;
2321 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002322
Craig Topper306cb122015-11-22 20:46:24 +00002323 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002324 InNodes[0]->getNumTypes() == 1 &&
2325 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002326 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2327 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002328 }
2329 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002330
Chris Lattnercabe0372010-03-15 06:00:16 +00002331 // If there are multiple nodes with the same name, they must all have the
2332 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002333 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002334 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002335 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002336 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002337 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002338
Chris Lattnerf1447252010-03-19 21:37:09 +00002339 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2340 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002341 }
2342 }
2343 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002344 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002345
Chris Lattner8cab0212008-01-05 22:25:12 +00002346 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002347 for (const TreePatternNode *Tree : Trees)
2348 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
Chris Lattner8cab0212008-01-05 22:25:12 +00002349 return !HasUnresolvedTypes;
2350}
2351
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002352void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002353 OS << getRecord()->getName();
2354 if (!Args.empty()) {
2355 OS << "(" << Args[0];
2356 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2357 OS << ", " << Args[i];
2358 OS << ")";
2359 }
2360 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002361
Chris Lattner8cab0212008-01-05 22:25:12 +00002362 if (Trees.size() > 1)
2363 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002364 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002365 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002366 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002367 OS << "\n";
2368 }
2369
2370 if (Trees.size() > 1)
2371 OS << "]\n";
2372}
2373
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002374void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002375
2376//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002377// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002378//
2379
Jim Grosbach65586fe2010-12-21 16:16:00 +00002380CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002381 Records(R), Target(R) {
2382
Dale Johannesenb842d522009-02-05 01:49:45 +00002383 Intrinsics = LoadIntrinsics(Records, false);
2384 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002385 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002386 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002387 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002388 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002389 ParseDefaultOperands();
2390 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002391 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002392 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002393
Chris Lattner8cab0212008-01-05 22:25:12 +00002394 // Generate variants. For example, commutative patterns can match
2395 // multiple ways. Add them to PatternsToMatch as well.
2396 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002397
2398 // Infer instruction flags. For example, we can detect loads,
2399 // stores, and side effects in many cases by examining an
2400 // instruction's pattern.
2401 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002402
2403 // Verify that instruction flags match the patterns.
2404 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002405}
2406
Chris Lattnerab3242f2008-01-06 01:10:31 +00002407Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002408 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002409 if (!N || !N->isSubClassOf("SDNode"))
2410 PrintFatalError("Error getting SDNode '" + Name + "'!");
2411
Chris Lattner8cab0212008-01-05 22:25:12 +00002412 return N;
2413}
2414
2415// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002416void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002417 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2418 while (!Nodes.empty()) {
2419 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2420 Nodes.pop_back();
2421 }
2422
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002423 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002424 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2425 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2426 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2427}
2428
2429/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2430/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002431void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002432 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2433 while (!Xforms.empty()) {
2434 Record *XFormNode = Xforms.back();
2435 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002436 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002437 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002438
2439 Xforms.pop_back();
2440 }
2441}
2442
Chris Lattnerab3242f2008-01-06 01:10:31 +00002443void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002444 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2445 while (!AMs.empty()) {
2446 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2447 AMs.pop_back();
2448 }
2449}
2450
2451
2452/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2453/// file, building up the PatternFragments map. After we've collected them all,
2454/// inline fragments together as necessary, so that there are no references left
2455/// inside a pattern fragment to a pattern fragment.
2456///
Hal Finkel2756dc12014-02-28 00:26:56 +00002457void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002458 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002459
Chris Lattnere7170df2008-01-05 22:43:57 +00002460 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002461 for (Record *Frag : Fragments) {
2462 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002463 continue;
2464
Craig Topper306cb122015-11-22 20:46:24 +00002465 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002466 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002467 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2468 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002469 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002470
Chris Lattnere7170df2008-01-05 22:43:57 +00002471 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002472 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002473 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002474
Chris Lattnere7170df2008-01-05 22:43:57 +00002475 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002476 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002477
Chris Lattner8cab0212008-01-05 22:25:12 +00002478 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002479 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002480 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002481 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002482 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002483 if (!OpsOp ||
2484 (OpsOp->getDef()->getName() != "ops" &&
2485 OpsOp->getDef()->getName() != "outs" &&
2486 OpsOp->getDef()->getName() != "ins"))
2487 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002488
2489 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002490 Args.clear();
2491 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002492 if (!isa<DefInit>(OpsList->getArg(j)) ||
2493 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002494 P->error("Operands list should all be 'node' values.");
2495 if (OpsList->getArgName(j).empty())
2496 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002497 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002498 P->error("'" + OpsList->getArgName(j) +
2499 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002500 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002501 Args.push_back(OpsList->getArgName(j));
2502 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002503
Chris Lattnere7170df2008-01-05 22:43:57 +00002504 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002505 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002506 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002507
Chris Lattnere7170df2008-01-05 22:43:57 +00002508 // If there is a code init for this fragment, keep track of the fact that
2509 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002510 TreePredicateFn PredFn(P);
2511 if (!PredFn.isAlwaysTrue())
2512 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002513
Chris Lattner8cab0212008-01-05 22:25:12 +00002514 // If there is a node transformation corresponding to this, keep track of
2515 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002516 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002517 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2518 P->getOnlyTree()->setTransformFn(Transform);
2519 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002520
Chris Lattner8cab0212008-01-05 22:25:12 +00002521 // Now that we've parsed all of the tree fragments, do a closure on them so
2522 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002523 for (Record *Frag : Fragments) {
2524 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002525 continue;
2526
Craig Topper306cb122015-11-22 20:46:24 +00002527 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002528 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002529
Chris Lattner8cab0212008-01-05 22:25:12 +00002530 // Infer as many types as possible. Don't worry about it if we don't infer
2531 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002532 ThePat.InferAllTypes();
2533 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002534
Chris Lattner8cab0212008-01-05 22:25:12 +00002535 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002536 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002537 }
2538}
2539
Chris Lattnerab3242f2008-01-06 01:10:31 +00002540void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002541 std::vector<Record*> DefaultOps;
2542 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002543
2544 // Find some SDNode.
2545 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002546 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002547
Tom Stellardb7246a72012-09-06 14:15:52 +00002548 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2549 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002550
Tom Stellardb7246a72012-09-06 14:15:52 +00002551 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2552 // SomeSDnode so that we can parse this.
2553 std::vector<std::pair<Init*, std::string> > Ops;
2554 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2555 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2556 DefaultInfo->getArgName(op)));
2557 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002558
Tom Stellardb7246a72012-09-06 14:15:52 +00002559 // Create a TreePattern to parse this.
2560 TreePattern P(DefaultOps[i], DI, false, *this);
2561 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002562
Tom Stellardb7246a72012-09-06 14:15:52 +00002563 // Copy the operands over into a DAGDefaultOperand.
2564 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002565
Tom Stellardb7246a72012-09-06 14:15:52 +00002566 TreePatternNode *T = P.getTree(0);
2567 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2568 TreePatternNode *TPN = T->getChild(op);
2569 while (TPN->ApplyTypeConstraints(P, false))
2570 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002571
Tom Stellardb7246a72012-09-06 14:15:52 +00002572 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002573 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2574 DefaultOps[i]->getName() +
2575 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002576 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002577 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002578 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002579
2580 // Insert it into the DefaultOperands map so we can find it later.
2581 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002582 }
2583}
2584
2585/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2586/// instruction input. Return true if this is a real use.
2587static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002588 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002589 // No name -> not interesting.
2590 if (Pat->getName().empty()) {
2591 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002592 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002593 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2594 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002595 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002596 }
2597 return false;
2598 }
2599
2600 Record *Rec;
2601 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002602 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002603 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2604 Rec = DI->getDef();
2605 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002606 Rec = Pat->getOperator();
2607 }
2608
2609 // SRCVALUE nodes are ignored.
2610 if (Rec->getName() == "srcvalue")
2611 return false;
2612
2613 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2614 if (!Slot) {
2615 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002616 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002617 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002618 Record *SlotRec;
2619 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002620 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002621 } else {
2622 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2623 SlotRec = Slot->getOperator();
2624 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002625
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002626 // Ensure that the inputs agree if we've already seen this input.
2627 if (Rec != SlotRec)
2628 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002629 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002630 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002631 return true;
2632}
2633
2634/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2635/// part of "I", the instruction), computing the set of inputs and outputs of
2636/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002637void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002638FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2639 std::map<std::string, TreePatternNode*> &InstInputs,
2640 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002641 std::vector<Record*> &InstImpResults) {
2642 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002643 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002644 if (!isUse && Pat->getTransformFn())
2645 I->error("Cannot specify a transform function for a non-input value!");
2646 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002647 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002648
Chris Lattnerf2d70992010-02-17 06:53:36 +00002649 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002650 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2651 TreePatternNode *Dest = Pat->getChild(i);
2652 if (!Dest->isLeaf())
2653 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002654
Sean Silvafb509ed2012-10-10 20:24:43 +00002655 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002656 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2657 I->error("implicitly defined value should be a register!");
2658 InstImpResults.push_back(Val->getDef());
2659 }
2660 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002661 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002662
Chris Lattnerf2d70992010-02-17 06:53:36 +00002663 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002664 // If this is not a set, verify that the children nodes are not void typed,
2665 // and recurse.
2666 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002667 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002668 I->error("Cannot have void nodes inside of patterns!");
2669 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002670 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002671 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002672
Chris Lattner8cab0212008-01-05 22:25:12 +00002673 // If this is a non-leaf node with no children, treat it basically as if
2674 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002675 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002676
Chris Lattner8cab0212008-01-05 22:25:12 +00002677 if (!isUse && Pat->getTransformFn())
2678 I->error("Cannot specify a transform function for a non-input value!");
2679 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002680 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002681
Chris Lattner8cab0212008-01-05 22:25:12 +00002682 // Otherwise, this is a set, validate and collect instruction results.
2683 if (Pat->getNumChildren() == 0)
2684 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002685
Chris Lattner8cab0212008-01-05 22:25:12 +00002686 if (Pat->getTransformFn())
2687 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002688
Chris Lattner8cab0212008-01-05 22:25:12 +00002689 // Check the set destinations.
2690 unsigned NumDests = Pat->getNumChildren()-1;
2691 for (unsigned i = 0; i != NumDests; ++i) {
2692 TreePatternNode *Dest = Pat->getChild(i);
2693 if (!Dest->isLeaf())
2694 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002695
Sean Silvafb509ed2012-10-10 20:24:43 +00002696 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002697 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002698 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002699 continue;
2700 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002701
2702 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002703 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002704 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002705 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002706 if (Dest->getName().empty())
2707 I->error("set destination must have a name!");
2708 if (InstResults.count(Dest->getName()))
2709 I->error("cannot set '" + Dest->getName() +"' multiple times");
2710 InstResults[Dest->getName()] = Dest;
2711 } else if (Val->getDef()->isSubClassOf("Register")) {
2712 InstImpResults.push_back(Val->getDef());
2713 } else {
2714 I->error("set destination should be a register!");
2715 }
2716 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002717
Chris Lattner8cab0212008-01-05 22:25:12 +00002718 // Verify and collect info from the computation.
2719 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002720 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002721}
2722
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002723//===----------------------------------------------------------------------===//
2724// Instruction Analysis
2725//===----------------------------------------------------------------------===//
2726
2727class InstAnalyzer {
2728 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002729public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002730 bool hasSideEffects;
2731 bool mayStore;
2732 bool mayLoad;
2733 bool isBitcast;
2734 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002735
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002736 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2737 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2738 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002739
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002740 void Analyze(const TreePattern *Pat) {
2741 // Assume only the first tree is the pattern. The others are clobber nodes.
2742 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002743 }
2744
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002745 void Analyze(const PatternToMatch *Pat) {
2746 AnalyzeNode(Pat->getSrcPattern());
2747 }
2748
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002749private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002750 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002751 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002752 return false;
2753
2754 if (N->getNumChildren() != 2)
2755 return false;
2756
2757 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002758 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002759 return false;
2760
2761 const TreePatternNode *N1 = N->getChild(1);
2762 if (N1->isLeaf())
2763 return false;
2764 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2765 return false;
2766
2767 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2768 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2769 return false;
2770 return OpInfo.getEnumName() == "ISD::BITCAST";
2771 }
2772
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002773public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002774 void AnalyzeNode(const TreePatternNode *N) {
2775 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002776 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002777 Record *LeafRec = DI->getDef();
2778 // Handle ComplexPattern leaves.
2779 if (LeafRec->isSubClassOf("ComplexPattern")) {
2780 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2781 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2782 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002783 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002784 }
2785 }
2786 return;
2787 }
2788
2789 // Analyze children.
2790 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2791 AnalyzeNode(N->getChild(i));
2792
2793 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002794 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002795 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002796 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002797 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002798
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002799 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002800 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2801 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2802 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2803 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002804
2805 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2806 // If this is an intrinsic, analyze it.
2807 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2808 mayLoad = true;// These may load memory.
2809
Dan Gohmanddb2d652010-08-05 23:36:21 +00002810 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002811 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2812
Dan Gohmanddb2d652010-08-05 23:36:21 +00002813 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002814 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002815 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002816 }
2817 }
2818
2819};
2820
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002821static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002822 const InstAnalyzer &PatInfo,
2823 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002824 bool Error = false;
2825
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002826 // Remember where InstInfo got its flags.
2827 if (InstInfo.hasUndefFlags())
2828 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002829
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002830 // Check explicitly set flags for consistency.
2831 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2832 !InstInfo.hasSideEffects_Unset) {
2833 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2834 // the pattern has no side effects. That could be useful for div/rem
2835 // instructions that may trap.
2836 if (!InstInfo.hasSideEffects) {
2837 Error = true;
2838 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2839 Twine(InstInfo.hasSideEffects));
2840 }
2841 }
2842
2843 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2844 Error = true;
2845 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2846 Twine(InstInfo.mayStore));
2847 }
2848
2849 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2850 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00002851 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002852 if (!InstInfo.mayLoad) {
2853 Error = true;
2854 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2855 Twine(InstInfo.mayLoad));
2856 }
2857 }
2858
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002859 // Transfer inferred flags.
2860 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2861 InstInfo.mayStore |= PatInfo.mayStore;
2862 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002863
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002864 // These flags are silently added without any verification.
2865 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002866
2867 // Don't infer isVariadic. This flag means something different on SDNodes and
2868 // instructions. For example, a CALL SDNode is variadic because it has the
2869 // call arguments as operands, but a CALL instruction is not variadic - it
2870 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002871
2872 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002873}
2874
Jim Grosbach514410b2012-07-17 00:47:06 +00002875/// hasNullFragReference - Return true if the DAG has any reference to the
2876/// null_frag operator.
2877static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002878 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002879 if (!OpDef) return false;
2880 Record *Operator = OpDef->getDef();
2881
2882 // If this is the null fragment, return true.
2883 if (Operator->getName() == "null_frag") return true;
2884 // If any of the arguments reference the null fragment, return true.
2885 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002886 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002887 if (Arg && hasNullFragReference(Arg))
2888 return true;
2889 }
2890
2891 return false;
2892}
2893
2894/// hasNullFragReference - Return true if any DAG in the list references
2895/// the null_frag operator.
2896static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00002897 for (Init *I : LI->getValues()) {
2898 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00002899 assert(DI && "non-dag in an instruction Pattern list?!");
2900 if (hasNullFragReference(DI))
2901 return true;
2902 }
2903 return false;
2904}
2905
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002906/// Get all the instructions in a tree.
2907static void
2908getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2909 if (Tree->isLeaf())
2910 return;
2911 if (Tree->getOperator()->isSubClassOf("Instruction"))
2912 Instrs.push_back(Tree->getOperator());
2913 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2914 getInstructionsInTree(Tree->getChild(i), Instrs);
2915}
2916
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002917/// Check the class of a pattern leaf node against the instruction operand it
2918/// represents.
2919static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2920 Record *Leaf) {
2921 if (OI.Rec == Leaf)
2922 return true;
2923
2924 // Allow direct value types to be used in instruction set patterns.
2925 // The type will be checked later.
2926 if (Leaf->isSubClassOf("ValueType"))
2927 return true;
2928
2929 // Patterns can also be ComplexPattern instances.
2930 if (Leaf->isSubClassOf("ComplexPattern"))
2931 return true;
2932
2933 return false;
2934}
2935
Ahmed Bougacha14107512013-10-28 18:07:21 +00002936const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2937 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002938
Craig Topper0d1fb902015-03-10 03:25:04 +00002939 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002940
Craig Topper0d1fb902015-03-10 03:25:04 +00002941 // Parse the instruction.
2942 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2943 // Inline pattern fragments into it.
2944 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002945
Craig Topper0d1fb902015-03-10 03:25:04 +00002946 // Infer as many types as possible. If we cannot infer all of them, we can
2947 // never do anything with this instruction pattern: report it to the user.
2948 if (!I->InferAllTypes())
2949 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002950
Craig Topper0d1fb902015-03-10 03:25:04 +00002951 // InstInputs - Keep track of all of the inputs of the instruction, along
2952 // with the record they are declared as.
2953 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002954
Craig Topper0d1fb902015-03-10 03:25:04 +00002955 // InstResults - Keep track of all the virtual registers that are 'set'
2956 // in the instruction, including what reg class they are.
2957 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002958
Craig Topper0d1fb902015-03-10 03:25:04 +00002959 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002960
Craig Topper0d1fb902015-03-10 03:25:04 +00002961 // Verify that the top-level forms in the instruction are of void type, and
2962 // fill in the InstResults map.
2963 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2964 TreePatternNode *Pat = I->getTree(j);
2965 if (Pat->getNumTypes() != 0)
2966 I->error("Top-level forms in instruction pattern should have"
2967 " void types");
Chris Lattner8cab0212008-01-05 22:25:12 +00002968
Craig Topper0d1fb902015-03-10 03:25:04 +00002969 // Find inputs and outputs, and verify the structure of the uses/defs.
2970 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2971 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002972 }
2973
Craig Topper0d1fb902015-03-10 03:25:04 +00002974 // Now that we have inputs and outputs of the pattern, inspect the operands
2975 // list for the instruction. This determines the order that operands are
2976 // added to the machine instruction the node corresponds to.
2977 unsigned NumResults = InstResults.size();
2978
2979 // Parse the operands list from the (ops) list, validating it.
2980 assert(I->getArgList().empty() && "Args list should still be empty here!");
2981
2982 // Check that all of the results occur first in the list.
2983 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00002984 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00002985 for (unsigned i = 0; i != NumResults; ++i) {
2986 if (i == CGI.Operands.size())
2987 I->error("'" + InstResults.begin()->first +
2988 "' set but does not appear in operand list!");
2989 const std::string &OpName = CGI.Operands[i].Name;
2990
2991 // Check that it exists in InstResults.
2992 TreePatternNode *RNode = InstResults[OpName];
2993 if (!RNode)
2994 I->error("Operand $" + OpName + " does not exist in operand list!");
2995
Craig Topper3a8eb892015-03-20 05:09:06 +00002996 ResNodes.push_back(RNode);
2997
Craig Topper0d1fb902015-03-10 03:25:04 +00002998 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2999 if (!R)
3000 I->error("Operand $" + OpName + " should be a set destination: all "
3001 "outputs must occur before inputs in operand list!");
3002
3003 if (!checkOperandClass(CGI.Operands[i], R))
3004 I->error("Operand $" + OpName + " class mismatch!");
3005
3006 // Remember the return type.
3007 Results.push_back(CGI.Operands[i].Rec);
3008
3009 // Okay, this one checks out.
3010 InstResults.erase(OpName);
3011 }
3012
3013 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3014 // the copy while we're checking the inputs.
3015 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3016
3017 std::vector<TreePatternNode*> ResultNodeOperands;
3018 std::vector<Record*> Operands;
3019 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3020 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3021 const std::string &OpName = Op.Name;
3022 if (OpName.empty())
3023 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3024
3025 if (!InstInputsCheck.count(OpName)) {
3026 // If this is an operand with a DefaultOps set filled in, we can ignore
3027 // this. When we codegen it, we will do so as always executed.
3028 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3029 // Does it have a non-empty DefaultOps field? If so, ignore this
3030 // operand.
3031 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3032 continue;
3033 }
3034 I->error("Operand $" + OpName +
3035 " does not appear in the instruction pattern");
3036 }
3037 TreePatternNode *InVal = InstInputsCheck[OpName];
3038 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3039
3040 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3041 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3042 if (!checkOperandClass(Op, InRec))
3043 I->error("Operand $" + OpName + "'s register class disagrees"
3044 " between the operand and pattern");
3045 }
3046 Operands.push_back(Op.Rec);
3047
3048 // Construct the result for the dest-pattern operand list.
3049 TreePatternNode *OpNode = InVal->clone();
3050
3051 // No predicate is useful on the result.
3052 OpNode->clearPredicateFns();
3053
3054 // Promote the xform function to be an explicit node if set.
3055 if (Record *Xform = OpNode->getTransformFn()) {
3056 OpNode->setTransformFn(nullptr);
3057 std::vector<TreePatternNode*> Children;
3058 Children.push_back(OpNode);
3059 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3060 }
3061
3062 ResultNodeOperands.push_back(OpNode);
3063 }
3064
3065 if (!InstInputsCheck.empty())
3066 I->error("Input operand $" + InstInputsCheck.begin()->first +
3067 " occurs in pattern but not in operands list!");
3068
3069 TreePatternNode *ResultPattern =
3070 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3071 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003072 // Copy fully inferred output node types to instruction result pattern.
3073 for (unsigned i = 0; i != NumResults; ++i) {
3074 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3075 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3076 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003077
3078 // Create and insert the instruction.
3079 // FIXME: InstImpResults should not be part of DAGInstruction.
3080 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3081 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3082
3083 // Use a temporary tree pattern to infer all types and make sure that the
3084 // constructed result is correct. This depends on the instruction already
3085 // being inserted into the DAGInsts map.
3086 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3087 Temp.InferAllTypes(&I->getNamedNodesMap());
3088
3089 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3090 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3091
3092 return TheInsertedInst;
3093}
3094
Ahmed Bougacha14107512013-10-28 18:07:21 +00003095/// ParseInstructions - Parse all of the instructions, inlining and resolving
3096/// any fragments involved. This populates the Instructions list with fully
3097/// resolved instructions.
3098void CodeGenDAGPatterns::ParseInstructions() {
3099 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3100
Craig Topper306cb122015-11-22 20:46:24 +00003101 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003102 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003103
Craig Topper306cb122015-11-22 20:46:24 +00003104 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3105 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003106
3107 // If there is no pattern, only collect minimal information about the
3108 // instruction for its operand list. We have to assume that there is one
3109 // result, as we have no detailed info. A pattern which references the
3110 // null_frag operator is as-if no pattern were specified. Normally this
3111 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3112 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003113 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003114 std::vector<Record*> Results;
3115 std::vector<Record*> Operands;
3116
Craig Topper306cb122015-11-22 20:46:24 +00003117 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003118
3119 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003120 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3121 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003122
Craig Topper3a8eb892015-03-20 05:09:06 +00003123 // The rest are inputs.
3124 for (unsigned j = InstInfo.Operands.NumDefs,
3125 e = InstInfo.Operands.size(); j < e; ++j)
3126 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003127 }
3128
3129 // Create and insert the instruction.
3130 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003131 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003132 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003133 continue; // no pattern.
3134 }
3135
Craig Topper306cb122015-11-22 20:46:24 +00003136 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003137 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3138
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003139 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003140 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003141 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003142
Chris Lattner8cab0212008-01-05 22:25:12 +00003143 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003144 for (auto &Entry : Instructions) {
3145 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003146 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003147 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003148
3149 // FIXME: Assume only the first tree is the pattern. The others are clobber
3150 // nodes.
3151 TreePatternNode *Pattern = I->getTree(0);
3152 TreePatternNode *SrcPattern;
3153 if (Pattern->getOperator()->getName() == "set") {
3154 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3155 } else{
3156 // Not a set (store or something?)
3157 SrcPattern = Pattern;
3158 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003159
Craig Topper306cb122015-11-22 20:46:24 +00003160 Record *Instr = Entry.first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003161 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003162 PatternToMatch(Instr,
3163 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003164 SrcPattern,
3165 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003166 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003167 Instr->getValueAsInt("AddedComplexity"),
3168 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003169 }
3170}
3171
Chris Lattnera7722b62010-02-23 06:55:24 +00003172
3173typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3174
Jim Grosbach65586fe2010-12-21 16:16:00 +00003175static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003176 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003177 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003178 if (!P->getName().empty()) {
3179 NameRecord &Rec = Names[P->getName()];
3180 // If this is the first instance of the name, remember the node.
3181 if (Rec.second++ == 0)
3182 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003183 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003184 PatternTop->error("repetition of value: $" + P->getName() +
3185 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003186 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003187
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003188 if (!P->isLeaf()) {
3189 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003190 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003191 }
3192}
3193
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003194void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003195 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003196 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003197 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003198 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3199 PrintWarning(Pattern->getRecord()->getLoc(),
3200 Twine("Pattern can never match: ") + Reason);
3201 return;
3202 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003203
Chris Lattner1e634e32010-03-01 22:29:19 +00003204 // If the source pattern's root is a complex pattern, that complex pattern
3205 // must specify the nodes it can potentially match.
3206 if (const ComplexPattern *CP =
3207 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3208 if (CP->getRootNodes().empty())
3209 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3210 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003211
3212
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003213 // Find all of the named values in the input and output, ensure they have the
3214 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003215 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003216 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3217 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003218
3219 // Scan all of the named values in the destination pattern, rejecting them if
3220 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003221 for (const auto &Entry : DstNames) {
3222 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003223 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003224 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003225 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003226
Chris Lattnera7722b62010-02-23 06:55:24 +00003227 // Scan all of the named values in the source pattern, rejecting them if the
3228 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003229 for (const auto &Entry : SrcNames)
3230 if (DstNames[Entry.first].first == nullptr &&
3231 SrcNames[Entry.first].second == 1)
3232 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003233
Chris Lattner0c0baa92010-02-23 06:16:51 +00003234 PatternsToMatch.push_back(PTM);
3235}
3236
3237
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003238
3239void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003240 const std::vector<const CodeGenInstruction*> &Instructions =
3241 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003242
3243 // First try to infer flags from the primary instruction pattern, if any.
3244 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003245 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003246 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3247 CodeGenInstruction &InstInfo =
3248 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003249
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003250 // Get the primary instruction pattern.
3251 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3252 if (!Pattern) {
3253 if (InstInfo.hasUndefFlags())
3254 Revisit.push_back(&InstInfo);
3255 continue;
3256 }
3257 InstAnalyzer PatInfo(*this);
3258 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003259 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003260 }
3261
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003262 // Second, look for single-instruction patterns defined outside the
3263 // instruction.
3264 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3265 const PatternToMatch &PTM = *I;
3266
3267 // We can only infer from single-instruction patterns, otherwise we won't
3268 // know which instruction should get the flags.
3269 SmallVector<Record*, 8> PatInstrs;
3270 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3271 if (PatInstrs.size() != 1)
3272 continue;
3273
3274 // Get the single instruction.
3275 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3276
3277 // Only infer properties from the first pattern. We'll verify the others.
3278 if (InstInfo.InferredFrom)
3279 continue;
3280
3281 InstAnalyzer PatInfo(*this);
3282 PatInfo.Analyze(&PTM);
3283 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3284 }
3285
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003286 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003287 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003288
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003289 // Revisit instructions with undefined flags and no pattern.
3290 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003291 for (CodeGenInstruction *InstInfo : Revisit) {
3292 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003293 continue;
3294 // The mayLoad and mayStore flags default to false.
3295 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003296 if (InstInfo->hasSideEffects_Unset)
3297 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003298 }
3299 return;
3300 }
3301
3302 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003303 for (CodeGenInstruction *InstInfo : Revisit) {
3304 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003305 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003306 if (InstInfo->hasSideEffects_Unset)
3307 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003308 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003309 if (InstInfo->mayStore_Unset)
3310 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003311 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003312 if (InstInfo->mayLoad_Unset)
3313 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003314 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003315 }
3316}
3317
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003318
3319/// Verify instruction flags against pattern node properties.
3320void CodeGenDAGPatterns::VerifyInstructionFlags() {
3321 unsigned Errors = 0;
3322 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3323 const PatternToMatch &PTM = *I;
3324 SmallVector<Record*, 8> Instrs;
3325 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3326 if (Instrs.empty())
3327 continue;
3328
3329 // Count the number of instructions with each flag set.
3330 unsigned NumSideEffects = 0;
3331 unsigned NumStores = 0;
3332 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003333 for (const Record *Instr : Instrs) {
3334 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003335 NumSideEffects += InstInfo.hasSideEffects;
3336 NumStores += InstInfo.mayStore;
3337 NumLoads += InstInfo.mayLoad;
3338 }
3339
3340 // Analyze the source pattern.
3341 InstAnalyzer PatInfo(*this);
3342 PatInfo.Analyze(&PTM);
3343
3344 // Collect error messages.
3345 SmallVector<std::string, 4> Msgs;
3346
3347 // Check for missing flags in the output.
3348 // Permit extra flags for now at least.
3349 if (PatInfo.hasSideEffects && !NumSideEffects)
3350 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3351
3352 // Don't verify store flags on instructions with side effects. At least for
3353 // intrinsics, side effects implies mayStore.
3354 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3355 Msgs.push_back("pattern may store, but mayStore isn't set");
3356
3357 // Similarly, mayStore implies mayLoad on intrinsics.
3358 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3359 Msgs.push_back("pattern may load, but mayLoad isn't set");
3360
3361 // Print error messages.
3362 if (Msgs.empty())
3363 continue;
3364 ++Errors;
3365
Craig Topper306cb122015-11-22 20:46:24 +00003366 for (const std::string &Msg : Msgs)
3367 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003368 (Instrs.size() == 1 ?
3369 "instruction" : "output instructions"));
3370 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003371 for (const Record *Instr : Instrs) {
3372 if (Instr != PTM.getSrcRecord())
3373 PrintError(Instr->getLoc(), "defined here");
3374 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003375 if (InstInfo.InferredFrom &&
3376 InstInfo.InferredFrom != InstInfo.TheDef &&
3377 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003378 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003379 }
3380 }
3381 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003382 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003383}
3384
Chris Lattnercabe0372010-03-15 06:00:16 +00003385/// Given a pattern result with an unresolved type, see if we can find one
3386/// instruction with an unresolved result type. Force this result type to an
3387/// arbitrary element if it's possible types to converge results.
3388static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3389 if (N->isLeaf())
3390 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003391
Chris Lattnercabe0372010-03-15 06:00:16 +00003392 // Analyze children.
3393 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3394 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3395 return true;
3396
3397 if (!N->getOperator()->isSubClassOf("Instruction"))
3398 return false;
3399
3400 // If this type is already concrete or completely unknown we can't do
3401 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003402 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3403 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3404 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003405
Chris Lattnerf1447252010-03-19 21:37:09 +00003406 // Otherwise, force its type to the first possibility (an arbitrary choice).
3407 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3408 return true;
3409 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003410
Chris Lattnerf1447252010-03-19 21:37:09 +00003411 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003412}
3413
Chris Lattnerab3242f2008-01-06 01:10:31 +00003414void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003415 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3416
Craig Topper306cb122015-11-22 20:46:24 +00003417 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003418 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003419
3420 // If the pattern references the null_frag, there's nothing to do.
3421 if (hasNullFragReference(Tree))
3422 continue;
3423
Chris Lattner5c2182e2010-03-27 02:53:27 +00003424 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003425
3426 // Inline pattern fragments into it.
3427 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003428
David Greeneaf8ee2c2011-07-29 22:43:06 +00003429 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003430 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003431
Chris Lattner8cab0212008-01-05 22:25:12 +00003432 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003433 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003434
Chris Lattner8cab0212008-01-05 22:25:12 +00003435 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003436 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003437
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003438 if (Result.getNumTrees() != 1)
3439 Result.error("Cannot handle instructions producing instructions "
3440 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003441
Chris Lattner8cab0212008-01-05 22:25:12 +00003442 bool IterateInference;
3443 bool InferredAllPatternTypes, InferredAllResultTypes;
3444 do {
3445 // Infer as many types as possible. If we cannot infer all of them, we
3446 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003447 InferredAllPatternTypes =
3448 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003449
Chris Lattner8cab0212008-01-05 22:25:12 +00003450 // Infer as many types as possible. If we cannot infer all of them, we
3451 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003452 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003453 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003454
Chris Lattnerfdc20712010-03-18 23:15:10 +00003455 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003456
Chris Lattner8cab0212008-01-05 22:25:12 +00003457 // Apply the type of the result to the source pattern. This helps us
3458 // resolve cases where the input type is known to be a pointer type (which
3459 // is considered resolved), but the result knows it needs to be 32- or
3460 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003461 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003462 Pattern->getTree(0)->getNumTypes());
3463 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003464 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3465 i, Result.getTree(0)->getExtType(i), Result);
3466 IterateInference |= Result.getTree(0)->UpdateNodeType(
3467 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003468 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003469
Chris Lattnercabe0372010-03-15 06:00:16 +00003470 // If our iteration has converged and the input pattern's types are fully
3471 // resolved but the result pattern is not fully resolved, we may have a
3472 // situation where we have two instructions in the result pattern and
3473 // the instructions require a common register class, but don't care about
3474 // what actual MVT is used. This is actually a bug in our modelling:
3475 // output patterns should have register classes, not MVTs.
3476 //
3477 // In any case, to handle this, we just go through and disambiguate some
3478 // arbitrary types to the result pattern's nodes.
3479 if (!IterateInference && InferredAllPatternTypes &&
3480 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003481 IterateInference =
3482 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003483 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003484
Chris Lattner8cab0212008-01-05 22:25:12 +00003485 // Verify that we inferred enough types that we can do something with the
3486 // pattern and result. If these fire the user has to add type casts.
3487 if (!InferredAllPatternTypes)
3488 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003489 if (!InferredAllResultTypes) {
3490 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003491 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003492 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003493
Chris Lattner8cab0212008-01-05 22:25:12 +00003494 // Validate that the input pattern is correct.
3495 std::map<std::string, TreePatternNode*> InstInputs;
3496 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003497 std::vector<Record*> InstImpResults;
3498 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3499 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3500 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003501 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003502
3503 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003504 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003505 std::vector<TreePatternNode*> ResultNodeOperands;
3506 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3507 TreePatternNode *OpNode = DstPattern->getChild(ii);
3508 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003509 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003510 std::vector<TreePatternNode*> Children;
3511 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003512 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003513 }
3514 ResultNodeOperands.push_back(OpNode);
3515 }
David Blaikiecf195302014-11-17 22:55:41 +00003516 DstPattern = Result.getOnlyTree();
3517 if (!DstPattern->isLeaf())
3518 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3519 ResultNodeOperands,
3520 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003521
David Blaikiecf195302014-11-17 22:55:41 +00003522 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3523 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3524
3525 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003526 Temp.InferAllTypes();
3527
Jim Grosbach65586fe2010-12-21 16:16:00 +00003528
Chris Lattner0c0baa92010-02-23 06:16:51 +00003529 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003530 PatternToMatch(CurPattern,
3531 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003532 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003533 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003534 CurPattern->getValueAsInt("AddedComplexity"),
3535 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003536 }
3537}
3538
3539/// CombineChildVariants - Given a bunch of permutations of each child of the
3540/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003541static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003542 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3543 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003544 CodeGenDAGPatterns &CDP,
3545 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003546 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003547 for (const auto &Variants : ChildVariants)
3548 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003549 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003550
Chris Lattner8cab0212008-01-05 22:25:12 +00003551 // The end result is an all-pairs construction of the resultant pattern.
3552 std::vector<unsigned> Idxs;
3553 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003554 bool NotDone;
3555 do {
3556#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003557 DEBUG(if (!Idxs.empty()) {
3558 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003559 for (unsigned Idx : Idxs) {
3560 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003561 }
3562 errs() << "]\n";
3563 });
Scott Michel94420742008-03-05 17:49:05 +00003564#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003565 // Create the variant and add it to the output list.
3566 std::vector<TreePatternNode*> NewChildren;
3567 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3568 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003569 auto R = llvm::make_unique<TreePatternNode>(
3570 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003571
Chris Lattner8cab0212008-01-05 22:25:12 +00003572 // Copy over properties.
3573 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003574 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003575 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003576 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3577 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003578
Scott Michel94420742008-03-05 17:49:05 +00003579 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003580 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003581 // Scan to see if this pattern has already been emitted. We can get
3582 // duplication due to things like commuting:
3583 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3584 // which are the same pattern. Ignore the dups.
3585 if (R->canPatternMatch(ErrString, CDP) &&
3586 std::none_of(OutVariants.begin(), OutVariants.end(),
3587 [&](TreePatternNode *Variant) {
3588 return R->isIsomorphicTo(Variant, DepVars);
3589 }))
3590 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003591
Scott Michel94420742008-03-05 17:49:05 +00003592 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003593 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003594 // [0, 0], [0, 1], [1, 0], [1, 1].
3595 int IdxsIdx;
3596 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3597 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3598 Idxs[IdxsIdx] = 0;
3599 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003600 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003601 }
Scott Michel94420742008-03-05 17:49:05 +00003602 NotDone = (IdxsIdx >= 0);
3603 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003604}
3605
3606/// CombineChildVariants - A helper function for binary operators.
3607///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003608static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003609 const std::vector<TreePatternNode*> &LHS,
3610 const std::vector<TreePatternNode*> &RHS,
3611 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003612 CodeGenDAGPatterns &CDP,
3613 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003614 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3615 ChildVariants.push_back(LHS);
3616 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003617 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003618}
Chris Lattner8cab0212008-01-05 22:25:12 +00003619
3620
3621static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3622 std::vector<TreePatternNode *> &Children) {
3623 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3624 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003625
Chris Lattner8cab0212008-01-05 22:25:12 +00003626 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003627 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003628 N->getTransformFn()) {
3629 Children.push_back(N);
3630 return;
3631 }
3632
3633 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3634 Children.push_back(N->getChild(0));
3635 else
3636 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3637
3638 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3639 Children.push_back(N->getChild(1));
3640 else
3641 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3642}
3643
3644/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3645/// the (potentially recursive) pattern by using algebraic laws.
3646///
3647static void GenerateVariantsOf(TreePatternNode *N,
3648 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003649 CodeGenDAGPatterns &CDP,
3650 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003651 // We cannot permute leaves or ComplexPattern uses.
3652 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003653 OutVariants.push_back(N);
3654 return;
3655 }
3656
3657 // Look up interesting info about the node.
3658 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3659
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003660 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003661 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003662 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003663 std::vector<TreePatternNode*> MaximalChildren;
3664 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3665
3666 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3667 // permutations.
3668 if (MaximalChildren.size() == 3) {
3669 // Find the variants of all of our maximal children.
3670 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003671 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3672 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3673 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003674
Chris Lattner8cab0212008-01-05 22:25:12 +00003675 // There are only two ways we can permute the tree:
3676 // (A op B) op C and A op (B op C)
3677 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003678
Chris Lattner8cab0212008-01-05 22:25:12 +00003679 // Generate legal pair permutations of A/B/C.
3680 std::vector<TreePatternNode*> ABVariants;
3681 std::vector<TreePatternNode*> BAVariants;
3682 std::vector<TreePatternNode*> ACVariants;
3683 std::vector<TreePatternNode*> CAVariants;
3684 std::vector<TreePatternNode*> BCVariants;
3685 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003686 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3687 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3688 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3689 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3690 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3691 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003692
3693 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003694 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3695 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3696 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3697 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3698 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3699 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003700
3701 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003702 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3703 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3704 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3705 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3706 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3707 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003708 return;
3709 }
3710 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003711
Chris Lattner8cab0212008-01-05 22:25:12 +00003712 // Compute permutations of all children.
3713 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3714 ChildVariants.resize(N->getNumChildren());
3715 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003716 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003717
3718 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003719 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003720
3721 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003722 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3723 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3724 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3725 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003726 // Don't count children which are actually register references.
3727 unsigned NC = 0;
3728 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3729 TreePatternNode *Child = N->getChild(i);
3730 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003731 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003732 Record *RR = DI->getDef();
3733 if (RR->isSubClassOf("Register"))
3734 continue;
3735 }
3736 NC++;
3737 }
3738 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003739 if (isCommIntrinsic) {
3740 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3741 // operands are the commutative operands, and there might be more operands
3742 // after those.
3743 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003744 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00003745 std::vector<std::vector<TreePatternNode*> > Variants;
3746 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3747 Variants.push_back(ChildVariants[2]);
3748 Variants.push_back(ChildVariants[1]);
3749 for (unsigned i = 3; i != NC; ++i)
3750 Variants.push_back(ChildVariants[i]);
3751 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3752 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003753 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003754 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003755 }
3756}
3757
3758
3759// GenerateVariants - Generate variants. For example, commutative patterns can
3760// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003761void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003762 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003763
Chris Lattner8cab0212008-01-05 22:25:12 +00003764 // Loop over all of the patterns we've collected, checking to see if we can
3765 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003766 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003767 // the .td file having to contain tons of variants of instructions.
3768 //
3769 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3770 // intentionally do not reconsider these. Any variants of added patterns have
3771 // already been added.
3772 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00003773 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003774 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003775 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003776 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003777 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003778 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003779 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00003780 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003781 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003782
3783 assert(!Variants.empty() && "Must create at least original variant!");
3784 Variants.erase(Variants.begin()); // Remove the original pattern.
3785
3786 if (Variants.empty()) // No variants for this pattern.
3787 continue;
3788
Chris Lattner34822f62009-08-23 04:44:11 +00003789 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00003790 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00003791 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003792
3793 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3794 TreePatternNode *Variant = Variants[v];
3795
Chris Lattner34822f62009-08-23 04:44:11 +00003796 DEBUG(errs() << " VAR#" << v << ": ";
3797 Variant->dump();
3798 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003799
Chris Lattner8cab0212008-01-05 22:25:12 +00003800 // Scan to see if an instruction or explicit pattern already matches this.
3801 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003802 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003803 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003804 if (PatternsToMatch[i].getPredicates() !=
3805 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00003806 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003807 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003808 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3809 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003810 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003811 AlreadyExists = true;
3812 break;
3813 }
3814 }
3815 // If we already have it, ignore the variant.
3816 if (AlreadyExists) continue;
3817
3818 // Otherwise, add it to the list of patterns we have.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003819 PatternsToMatch.emplace_back(
3820 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3821 Variant, PatternsToMatch[i].getDstPattern(),
3822 PatternsToMatch[i].getDstRegs(),
3823 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
Chris Lattner8cab0212008-01-05 22:25:12 +00003824 }
3825
Chris Lattner34822f62009-08-23 04:44:11 +00003826 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003827 }
3828}