blob: 35b6bf4416b50d6b8c575da48f9e8c153ced98f7 [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 Topper74169dc2014-01-28 04:49:01 +0000388 TypeSet InputSet(Other);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000389 MVT Smallest = TypeVec[0];
Craig Topper74169dc2014-01-28 04:49:01 +0000390 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000391 MVT OtherVT = Other.TypeVec[i];
392 // Don't compare vector and non-vector types.
393 if (OtherVT.isVector() != Smallest.isVector())
394 continue;
395 // The getSizeInBits() check here is only needed for vectors, but is
396 // a subset of the scalar check for scalars so no need to qualify.
397 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
398 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000399 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
400 MadeChange = true;
401 }
402 }
403
404 if (Other.TypeVec.empty()) {
405 TP.error("Type inference contradiction found, '" + InputSet.getName() +
406 "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000407 return false;
408 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000409
Craig Topper7bbd37b2015-03-10 03:25:07 +0000410 // Okay, find the largest type from the other set and remove anything the
411 // same or smaller from the current set. We need to ensure that the scalar
412 // type size is larger than the scalar size of the largest type. For
413 // vectors, we also need to make sure that the total size is no smaller than
414 // the size of the largest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000415 InputSet = TypeSet(*this);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000416 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
Craig Topper74169dc2014-01-28 04:49:01 +0000417 for (unsigned i = 0; i != TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000418 MVT OtherVT = TypeVec[i];
419 // Don't compare vector and non-vector types.
420 if (OtherVT.isVector() != Largest.isVector())
421 continue;
422 // The getSizeInBits() check here is only needed for vectors, but is
423 // a subset of the scalar check for scalars so no need to qualify.
424 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
425 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000426 TypeVec.erase(TypeVec.begin()+i--);
427 MadeChange = true;
David Greene433c6182011-02-01 19:12:32 +0000428 }
David Greene433c6182011-02-01 19:12:32 +0000429 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000430
Craig Topper74169dc2014-01-28 04:49:01 +0000431 if (TypeVec.empty()) {
432 TP.error("Type inference contradiction found, '" + InputSet.getName() +
433 "' has nothing smaller than '" + Other.getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000434 return false;
435 }
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.
451 for (unsigned i = 0; i != TypeVec.size(); ++i) {
452 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
453 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
454 TypeVec.erase(TypeVec.begin()+i--);
455 MadeChange = true;
456 }
457 }
458
459 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
460 TP.error("Type inference contradiction found, forcing '" +
461 InputSet.getName() + "' to have a vector element");
462 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();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000484 return MadeChange |
Craig Topper95198f42013-09-25 06:37:18 +0000485 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000486 }
487
488 // If the scalar type is known, filter out vector types whose element types
489 // disagree.
490 if (!VTOperand.isConcrete())
491 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000492
Chris Lattner57ebf632010-03-24 00:01:16 +0000493 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000494
Chris Lattner57ebf632010-03-24 00:01:16 +0000495 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000496
Chris Lattner57ebf632010-03-24 00:01:16 +0000497 // Filter out all the types which don't have the right element type.
498 for (unsigned i = 0; i != TypeVec.size(); ++i) {
499 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
Craig Topper95198f42013-09-25 06:37:18 +0000500 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000501 TypeVec.erase(TypeVec.begin()+i--);
502 MadeChange = true;
503 }
Chris Lattner57ebf632010-03-24 00:01:16 +0000504 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000505
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000506 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattnercabe0372010-03-15 06:00:16 +0000507 TP.error("Type inference contradiction found, forcing '" +
508 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000509 return false;
510 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000511 return MadeChange;
512}
513
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000514/// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
David Greene127fd1d2011-01-24 20:53:18 +0000515/// vector type specified by VTOperand.
516bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
517 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000518 if (TP.hasError())
519 return false;
520
David Greene127fd1d2011-01-24 20:53:18 +0000521 // "This" must be a vector and "VTOperand" must be a vector.
522 bool MadeChange = false;
523 MadeChange |= EnforceVector(TP);
524 MadeChange |= VTOperand.EnforceVector(TP);
525
Craig Topper6e1faaf2014-01-25 17:40:33 +0000526 // If one side is known to be integer or known to be FP but the other side has
527 // no information, get at least the type integrality info in there.
528 if (!hasFloatingPointTypes())
529 MadeChange |= VTOperand.EnforceInteger(TP);
530 else if (!hasIntegerTypes())
531 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
532 if (!VTOperand.hasFloatingPointTypes())
533 MadeChange |= EnforceInteger(TP);
534 else if (!VTOperand.hasIntegerTypes())
535 MadeChange |= EnforceFloatingPoint(TP);
536
537 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
538 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000539
540 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000541 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000542 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000543 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000544 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000545 IVT = IVT.getVectorElementType();
546
Craig Topper95198f42013-09-25 06:37:18 +0000547 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000548 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000549
550 // Only keep types that have less elements than VTOperand.
551 TypeSet InputSet(VTOperand);
552
553 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
554 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
555 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
556 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
557 MadeChange = true;
558 }
559 }
560 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
561 TP.error("Type inference contradiction found, forcing '" +
562 InputSet.getName() + "' to have less vector elements than '" +
563 getName() + "'");
564 return false;
565 }
David Greene127fd1d2011-01-24 20:53:18 +0000566 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000567 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000568 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000569 IVT = IVT.getVectorElementType();
570
Craig Topper95198f42013-09-25 06:37:18 +0000571 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000572 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000573
574 // Only keep types that have more elements than 'this'.
575 TypeSet InputSet(*this);
576
577 for (unsigned i = 0; i != TypeVec.size(); ++i) {
578 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
579 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
580 TypeVec.erase(TypeVec.begin()+i--);
581 MadeChange = true;
582 }
583 }
584 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
585 TP.error("Type inference contradiction found, forcing '" +
586 InputSet.getName() + "' to have more vector elements than '" +
587 VTOperand.getName() + "'");
588 return false;
589 }
David Greene127fd1d2011-01-24 20:53:18 +0000590 }
591
592 return MadeChange;
593}
594
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000595/// EnforceVectorSameNumElts - 'this' is now constrained to
Craig Topper0be34582015-03-05 07:11:34 +0000596/// be a vector with same num elements as VTOperand.
597bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
598 TreePattern &TP) {
599 if (TP.hasError())
600 return false;
601
602 // "This" must be a vector and "VTOperand" must be a vector.
603 bool MadeChange = false;
604 MadeChange |= EnforceVector(TP);
605 MadeChange |= VTOperand.EnforceVector(TP);
606
607 // If we know one of the vector types, it forces the other type to agree.
608 if (isConcrete()) {
609 MVT IVT = getConcrete();
610 unsigned NumElems = IVT.getVectorNumElements();
611
612 // Only keep types that have same elements as VTOperand.
613 TypeSet InputSet(VTOperand);
614
615 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
616 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
617 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
618 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
619 MadeChange = true;
620 }
621 }
622 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
623 TP.error("Type inference contradiction found, forcing '" +
624 InputSet.getName() + "' to have same number elements as '" +
625 getName() + "'");
626 return false;
627 }
628 } else if (VTOperand.isConcrete()) {
629 MVT IVT = VTOperand.getConcrete();
630 unsigned NumElems = IVT.getVectorNumElements();
631
632 // Only keep types that have same elements as 'this'.
633 TypeSet InputSet(*this);
634
635 for (unsigned i = 0; i != TypeVec.size(); ++i) {
636 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
637 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
638 TypeVec.erase(TypeVec.begin()+i--);
639 MadeChange = true;
640 }
641 }
642 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
643 TP.error("Type inference contradiction found, forcing '" +
644 InputSet.getName() + "' to have same number elements than '" +
645 VTOperand.getName() + "'");
646 return false;
647 }
648 }
649
650 return MadeChange;
651}
652
Chris Lattnercabe0372010-03-15 06:00:16 +0000653//===----------------------------------------------------------------------===//
654// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000655
Scott Michel94420742008-03-05 17:49:05 +0000656/// Dependent variable map for CodeGenDAGPattern variant generation
657typedef std::map<std::string, int> DepVarMap;
658
Chris Lattner514e2922011-04-17 21:38:24 +0000659static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000660 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000661 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000662 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000663 } else {
664 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
665 FindDepVarsOf(N->getChild(i), DepMap);
666 }
667}
Chris Lattner514e2922011-04-17 21:38:24 +0000668
669/// Find dependent variables within child patterns
670static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000671 DepVarMap depcounts;
672 FindDepVarsOf(N, depcounts);
Craig Topper306cb122015-11-22 20:46:24 +0000673 for (const std::pair<std::string, int> &Pair : depcounts) {
674 if (Pair.second > 1)
675 DepVars.insert(Pair.first);
Scott Michel94420742008-03-05 17:49:05 +0000676 }
677}
678
Daniel Dunbarba66a812010-10-08 02:07:22 +0000679#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000680/// Dump the dependent variable set:
681static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000682 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000683 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000684 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000685 DEBUG(errs() << "[ ");
Craig Topper306cb122015-11-22 20:46:24 +0000686 for (const std::string &DepVar : DepVars) {
687 DEBUG(errs() << DepVar << " ");
Scott Michel94420742008-03-05 17:49:05 +0000688 }
Chris Lattner34822f62009-08-23 04:44:11 +0000689 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000690 }
691}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000692#endif
693
Chris Lattner514e2922011-04-17 21:38:24 +0000694
695//===----------------------------------------------------------------------===//
696// TreePredicateFn Implementation
697//===----------------------------------------------------------------------===//
698
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000699/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
700TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
701 assert((getPredCode().empty() || getImmCode().empty()) &&
702 ".td file corrupt: can't have a node predicate *and* an imm predicate");
703}
704
Chris Lattner514e2922011-04-17 21:38:24 +0000705std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000706 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000707}
708
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000709std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000710 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000711}
712
Chris Lattner514e2922011-04-17 21:38:24 +0000713
714/// isAlwaysTrue - Return true if this is a noop predicate.
715bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000716 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000717}
718
719/// Return the name to use in the generated code to reference this, this is
720/// "Predicate_foo" if from a pattern fragment "foo".
721std::string TreePredicateFn::getFnName() const {
722 return "Predicate_" + PatFragRec->getRecord()->getName();
723}
724
725/// getCodeToRunOnSDNode - Return the code for the function body that
726/// evaluates this predicate. The argument is expected to be in "Node",
727/// not N. This handles casting and conversion to a concrete node type as
728/// appropriate.
729std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000730 // Handle immediate predicates first.
731 std::string ImmCode = getImmCode();
732 if (!ImmCode.empty()) {
733 std::string Result =
734 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000735 return Result + ImmCode;
736 }
737
738 // Handle arbitrary node predicates.
739 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000740 std::string ClassName;
741 if (PatFragRec->getOnlyTree()->isLeaf())
742 ClassName = "SDNode";
743 else {
744 Record *Op = PatFragRec->getOnlyTree()->getOperator();
745 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
746 }
747 std::string Result;
748 if (ClassName == "SDNode")
749 Result = " SDNode *N = Node;\n";
750 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000751 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000752
753 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000754}
755
Chris Lattner8cab0212008-01-05 22:25:12 +0000756//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000757// PatternToMatch implementation
758//
759
Chris Lattner05925fe2010-03-29 01:40:38 +0000760
761/// getPatternSize - Return the 'size' of this pattern. We want to match large
762/// patterns before small ones. This is used to determine the size of a
763/// pattern.
764static unsigned getPatternSize(const TreePatternNode *P,
765 const CodeGenDAGPatterns &CGP) {
766 unsigned Size = 3; // The node itself.
767 // If the root node is a ConstantSDNode, increases its size.
768 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000769 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000770 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000771
Chris Lattner05925fe2010-03-29 01:40:38 +0000772 // FIXME: This is a hack to statically increase the priority of patterns
773 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
774 // Later we can allow complexity / cost for each pattern to be (optionally)
775 // specified. To get best possible pattern match we'll need to dynamically
776 // calculate the complexity of all patterns a dag can potentially map to.
777 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000778 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000779 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000780
Tim Northoverc807a172014-05-20 11:52:46 +0000781 // We don't want to count any children twice, so return early.
782 return Size;
783 }
784
Chris Lattner05925fe2010-03-29 01:40:38 +0000785 // If this node has some predicate function that must match, it adds to the
786 // complexity of this node.
787 if (!P->getPredicateFns().empty())
788 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000789
Chris Lattner05925fe2010-03-29 01:40:38 +0000790 // Count children in the count if they are also nodes.
791 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
792 TreePatternNode *Child = P->getChild(i);
793 if (!Child->isLeaf() && Child->getNumTypes() &&
794 Child->getType(0) != MVT::Other)
795 Size += getPatternSize(Child, CGP);
796 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000797 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000798 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
799 else if (Child->getComplexPatternInfo(CGP))
800 Size += getPatternSize(Child, CGP);
801 else if (!Child->getPredicateFns().empty())
802 ++Size;
803 }
804 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000805
Chris Lattner05925fe2010-03-29 01:40:38 +0000806 return Size;
807}
808
809/// Compute the complexity metric for the input pattern. This roughly
810/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000811int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000812getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
813 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
814}
815
816
Dan Gohman49e19e92008-08-22 00:20:26 +0000817/// getPredicateCheck - Return a single string containing all of this
818/// pattern's predicates concatenated with "&&" operators.
819///
820std::string PatternToMatch::getPredicateCheck() const {
821 std::string PredicateCheck;
Craig Topperef0578a2015-06-02 04:15:51 +0000822 for (Init *I : Predicates->getValues()) {
823 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000824 Record *Def = Pred->getDef();
825 if (!Def->isSubClassOf("Predicate")) {
826#ifndef NDEBUG
827 Def->dump();
828#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000829 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000830 }
831 if (!PredicateCheck.empty())
832 PredicateCheck += " && ";
833 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
834 }
835 }
836
837 return PredicateCheck;
838}
839
840//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000841// SDTypeConstraint implementation
842//
843
844SDTypeConstraint::SDTypeConstraint(Record *R) {
845 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000846
Chris Lattner8cab0212008-01-05 22:25:12 +0000847 if (R->isSubClassOf("SDTCisVT")) {
848 ConstraintType = SDTCisVT;
849 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000850 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000851 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000852
Chris Lattner8cab0212008-01-05 22:25:12 +0000853 } else if (R->isSubClassOf("SDTCisPtrTy")) {
854 ConstraintType = SDTCisPtrTy;
855 } else if (R->isSubClassOf("SDTCisInt")) {
856 ConstraintType = SDTCisInt;
857 } else if (R->isSubClassOf("SDTCisFP")) {
858 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000859 } else if (R->isSubClassOf("SDTCisVec")) {
860 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000861 } else if (R->isSubClassOf("SDTCisSameAs")) {
862 ConstraintType = SDTCisSameAs;
863 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
864 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
865 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000866 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000867 R->getValueAsInt("OtherOperandNum");
868 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
869 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000870 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000871 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000872 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
873 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000874 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000875 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
876 ConstraintType = SDTCisSubVecOfVec;
877 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
878 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000879 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
880 ConstraintType = SDTCVecEltisVT;
881 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
882 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
883 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
884 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
885 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
886 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
887 "as SDTCVecEltisVT");
888 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
889 ConstraintType = SDTCisSameNumEltsAs;
890 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
891 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000892 } else {
James Y Knighte452e272015-05-11 22:17:13 +0000893 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +0000894 }
895}
896
897/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000898/// N, and the result number in ResNo.
899static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
900 const SDNodeInfo &NodeInfo,
901 unsigned &ResNo) {
902 unsigned NumResults = NodeInfo.getNumResults();
903 if (OpNo < NumResults) {
904 ResNo = OpNo;
905 return N;
906 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000907
Chris Lattner2db7aba2010-03-19 21:56:21 +0000908 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000909
Chris Lattner2db7aba2010-03-19 21:56:21 +0000910 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +0000911 std::string S;
912 raw_string_ostream OS(S);
913 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000914 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +0000915 N->print(OS);
916 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +0000917 }
918
Chris Lattner2db7aba2010-03-19 21:56:21 +0000919 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000920}
921
922/// ApplyTypeConstraint - Given a node in a pattern, apply this type
923/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000924/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000925bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
926 const SDNodeInfo &NodeInfo,
927 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000928 if (TP.hasError())
929 return false;
930
Chris Lattner2db7aba2010-03-19 21:56:21 +0000931 unsigned ResNo = 0; // The result number being referenced.
932 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000933
Chris Lattner8cab0212008-01-05 22:25:12 +0000934 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000935 case SDTCisVT:
936 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000937 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000938 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000939 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000940 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000941 case SDTCisInt:
942 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000943 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000944 case SDTCisFP:
945 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000946 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000947 case SDTCisVec:
948 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000949 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000950 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000951 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000952 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000953 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +0000954 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
955 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000956 }
957 case SDTCisVTSmallerThanOp: {
958 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
959 // have an integer type that is smaller than the VT.
960 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +0000961 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +0000962 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000963 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000964 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000965 return false;
966 }
Owen Anderson9f944592009-08-11 20:47:22 +0000967 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +0000968 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000969
Chris Lattner38c99662010-03-24 00:06:46 +0000970 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000971
Chris Lattner2db7aba2010-03-19 21:56:21 +0000972 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000973 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000974 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
975 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +0000976
Chris Lattner38c99662010-03-24 00:06:46 +0000977 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000978 }
979 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000980 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000981 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000982 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
983 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000984 return NodeToApply->getExtType(ResNo).
985 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000986 }
Nate Begeman17bedbc2008-02-09 01:37:05 +0000987 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000988 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +0000989 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000990 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
991 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000992
Chris Lattner57ebf632010-03-24 00:01:16 +0000993 // Filter vector types out of VecOperand that don't have the right element
994 // type.
995 return VecOperand->getExtType(VResNo).
996 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +0000997 }
David Greene127fd1d2011-01-24 20:53:18 +0000998 case SDTCisSubVecOfVec: {
999 unsigned VResNo = 0;
1000 TreePatternNode *BigVecOperand =
1001 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1002 VResNo);
1003
1004 // Filter vector types out of BigVecOperand that don't have the
1005 // right subvector type.
1006 return BigVecOperand->getExtType(VResNo).
1007 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1008 }
Craig Topper0be34582015-03-05 07:11:34 +00001009 case SDTCVecEltisVT: {
1010 return NodeToApply->getExtType(ResNo).
1011 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1012 }
1013 case SDTCisSameNumEltsAs: {
1014 unsigned OResNo = 0;
1015 TreePatternNode *OtherNode =
1016 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1017 N, NodeInfo, OResNo);
1018 return OtherNode->getExtType(OResNo).
1019 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1020 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001021 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001022 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001023}
1024
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001025// Update the node type to match an instruction operand or result as specified
1026// in the ins or outs lists on the instruction definition. Return true if the
1027// type was actually changed.
1028bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1029 Record *Operand,
1030 TreePattern &TP) {
1031 // The 'unknown' operand indicates that types should be inferred from the
1032 // context.
1033 if (Operand->isSubClassOf("unknown_class"))
1034 return false;
1035
1036 // The Operand class specifies a type directly.
1037 if (Operand->isSubClassOf("Operand"))
1038 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1039 TP);
1040
1041 // PointerLikeRegClass has a type that is determined at runtime.
1042 if (Operand->isSubClassOf("PointerLikeRegClass"))
1043 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1044
1045 // Both RegisterClass and RegisterOperand operands derive their types from a
1046 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001047 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001048 if (Operand->isSubClassOf("RegisterClass"))
1049 RC = Operand;
1050 else if (Operand->isSubClassOf("RegisterOperand"))
1051 RC = Operand->getValueAsDef("RegClass");
1052
1053 assert(RC && "Unknown operand type");
1054 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1055 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1056}
1057
1058
Chris Lattner8cab0212008-01-05 22:25:12 +00001059//===----------------------------------------------------------------------===//
1060// SDNodeInfo implementation
1061//
1062SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1063 EnumName = R->getValueAsString("Opcode");
1064 SDClassName = R->getValueAsString("SDClass");
1065 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1066 NumResults = TypeProfile->getValueAsInt("NumResults");
1067 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001068
Chris Lattner8cab0212008-01-05 22:25:12 +00001069 // Parse the properties.
1070 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001071 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1072 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001073 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001074 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001075 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001076 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001077 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001078 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001079 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001080 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001081 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001082 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001083 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001084 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001085 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001086 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001087 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001088 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001089 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001090 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001091 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001092 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001093 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001094 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001095 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001096 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001097 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001098 }
1099 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001100
1101
Chris Lattner8cab0212008-01-05 22:25:12 +00001102 // Parse the type constraints.
1103 std::vector<Record*> ConstraintList =
1104 TypeProfile->getValueAsListOfDefs("Constraints");
1105 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1106}
1107
Chris Lattner99e53b32010-02-28 00:22:30 +00001108/// getKnownType - If the type constraints on this node imply a fixed type
1109/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001110/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001111MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001112 unsigned NumResults = getNumResults();
1113 assert(NumResults <= 1 &&
1114 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001115 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001116
Craig Topper306cb122015-11-22 20:46:24 +00001117 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001118 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001119 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001120 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001121
Craig Topper306cb122015-11-22 20:46:24 +00001122 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001123 default: break;
1124 case SDTypeConstraint::SDTCisVT:
Craig Topper306cb122015-11-22 20:46:24 +00001125 return Constraint.x.SDTCisVT_Info.VT;
Chris Lattner99e53b32010-02-28 00:22:30 +00001126 case SDTypeConstraint::SDTCisPtrTy:
1127 return MVT::iPTR;
1128 }
1129 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001130 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001131}
1132
Chris Lattner8cab0212008-01-05 22:25:12 +00001133//===----------------------------------------------------------------------===//
1134// TreePatternNode implementation
1135//
1136
1137TreePatternNode::~TreePatternNode() {
1138#if 0 // FIXME: implement refcounted tree nodes!
1139 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1140 delete getChild(i);
1141#endif
1142}
1143
Chris Lattnerf1447252010-03-19 21:37:09 +00001144static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1145 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001146 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001147 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001148
Chris Lattner2109cb42010-03-22 20:56:36 +00001149 if (Operator->isSubClassOf("Intrinsic"))
1150 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001151
Chris Lattnerf1447252010-03-19 21:37:09 +00001152 if (Operator->isSubClassOf("SDNode"))
1153 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001154
Chris Lattnerf1447252010-03-19 21:37:09 +00001155 if (Operator->isSubClassOf("PatFrag")) {
1156 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1157 // the forward reference case where one pattern fragment references another
1158 // before it is processed.
1159 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1160 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001161
Chris Lattnerf1447252010-03-19 21:37:09 +00001162 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001163 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001164 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001165 if (Tree)
1166 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1167 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001168 assert(Op && "Invalid Fragment");
1169 return GetNumNodeResults(Op, CDP);
1170 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001171
Chris Lattnerf1447252010-03-19 21:37:09 +00001172 if (Operator->isSubClassOf("Instruction")) {
1173 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001174
Craig Topper3a8eb892015-03-20 05:09:06 +00001175 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1176
1177 // Subtract any defaulted outputs.
1178 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1179 Record *OperandNode = InstInfo.Operands[i].Rec;
1180
1181 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1182 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1183 --NumDefsToAdd;
1184 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001185
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001186 // Add on one implicit def if it has a resolvable type.
1187 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1188 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001189 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001190 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001191
Chris Lattnerf1447252010-03-19 21:37:09 +00001192 if (Operator->isSubClassOf("SDNodeXForm"))
1193 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001194
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001195 if (Operator->isSubClassOf("ValueType"))
1196 return 1; // A type-cast of one result.
1197
Tim Northoverc807a172014-05-20 11:52:46 +00001198 if (Operator->isSubClassOf("ComplexPattern"))
1199 return 1;
1200
Chris Lattnerf1447252010-03-19 21:37:09 +00001201 Operator->dump();
James Y Knighte452e272015-05-11 22:17:13 +00001202 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001203}
1204
1205void TreePatternNode::print(raw_ostream &OS) const {
1206 if (isLeaf())
1207 OS << *getLeafValue();
1208 else
1209 OS << '(' << getOperator()->getName();
1210
1211 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1212 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001213
1214 if (!isLeaf()) {
1215 if (getNumChildren() != 0) {
1216 OS << " ";
1217 getChild(0)->print(OS);
1218 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1219 OS << ", ";
1220 getChild(i)->print(OS);
1221 }
1222 }
1223 OS << ")";
1224 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001225
Craig Topper306cb122015-11-22 20:46:24 +00001226 for (const TreePredicateFn &Pred : PredicateFns)
1227 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001228 if (TransformFn)
1229 OS << "<<X:" << TransformFn->getName() << ">>";
1230 if (!getName().empty())
1231 OS << ":$" << getName();
1232
1233}
1234void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001235 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001236}
1237
Scott Michel94420742008-03-05 17:49:05 +00001238/// isIsomorphicTo - Return true if this node is recursively
1239/// isomorphic to the specified node. For this comparison, the node's
1240/// entire state is considered. The assigned name is ignored, since
1241/// nodes with differing names are considered isomorphic. However, if
1242/// the assigned name is present in the dependent variable set, then
1243/// the assigned name is considered significant and the node is
1244/// isomorphic if the names match.
1245bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1246 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001247 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001248 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001249 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001250 getTransformFn() != N->getTransformFn())
1251 return false;
1252
1253 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001254 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1255 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001256 return ((DI->getDef() == NDI->getDef())
1257 && (DepVars.find(getName()) == DepVars.end()
1258 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001259 }
1260 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001261 return getLeafValue() == N->getLeafValue();
1262 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001263
Chris Lattner8cab0212008-01-05 22:25:12 +00001264 if (N->getOperator() != getOperator() ||
1265 N->getNumChildren() != getNumChildren()) return false;
1266 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001267 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001268 return false;
1269 return true;
1270}
1271
1272/// clone - Make a copy of this tree and all of its children.
1273///
1274TreePatternNode *TreePatternNode::clone() const {
1275 TreePatternNode *New;
1276 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001277 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001278 } else {
1279 std::vector<TreePatternNode*> CChildren;
1280 CChildren.reserve(Children.size());
1281 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1282 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001283 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001284 }
1285 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001286 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001287 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001288 New->setTransformFn(getTransformFn());
1289 return New;
1290}
1291
Chris Lattner53c39ba2010-02-14 22:22:58 +00001292/// RemoveAllTypes - Recursively strip all the types of this tree.
1293void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001294 // Reset to unknown type.
1295 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001296 if (isLeaf()) return;
1297 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1298 getChild(i)->RemoveAllTypes();
1299}
1300
1301
Chris Lattner8cab0212008-01-05 22:25:12 +00001302/// SubstituteFormalArguments - Replace the formal arguments in this tree
1303/// with actual values specified by ArgMap.
1304void TreePatternNode::
1305SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1306 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001307
Chris Lattner8cab0212008-01-05 22:25:12 +00001308 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1309 TreePatternNode *Child = getChild(i);
1310 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001311 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001312 // Note that, when substituting into an output pattern, Val might be an
1313 // UnsetInit.
1314 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1315 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001316 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001317 TreePatternNode *NewChild = ArgMap[Child->getName()];
1318 assert(NewChild && "Couldn't find formal argument!");
1319 assert((Child->getPredicateFns().empty() ||
1320 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1321 "Non-empty child predicate clobbered!");
1322 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001323 }
1324 } else {
1325 getChild(i)->SubstituteFormalArguments(ArgMap);
1326 }
1327 }
1328}
1329
1330
1331/// InlinePatternFragments - If this pattern refers to any pattern
1332/// fragments, inline them into place, giving us a pattern without any
1333/// PatFrag references.
1334TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001335 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001336 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001337
1338 if (isLeaf())
1339 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001340 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001341
Chris Lattner8cab0212008-01-05 22:25:12 +00001342 if (!Op->isSubClassOf("PatFrag")) {
1343 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001344 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1345 TreePatternNode *Child = getChild(i);
1346 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1347
1348 assert((Child->getPredicateFns().empty() ||
1349 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1350 "Non-empty child predicate clobbered!");
1351
1352 setChild(i, NewChild);
1353 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001354 return this;
1355 }
1356
1357 // Otherwise, we found a reference to a fragment. First, look up its
1358 // TreePattern record.
1359 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001360
Chris Lattner8cab0212008-01-05 22:25:12 +00001361 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001362 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001363 TP.error("'" + Op->getName() + "' fragment requires " +
1364 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001365 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001366 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001367
1368 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1369
Chris Lattner514e2922011-04-17 21:38:24 +00001370 TreePredicateFn PredFn(Frag);
1371 if (!PredFn.isAlwaysTrue())
1372 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001373
Chris Lattner8cab0212008-01-05 22:25:12 +00001374 // Resolve formal arguments to their actual value.
1375 if (Frag->getNumArgs()) {
1376 // Compute the map of formal to actual arguments.
1377 std::map<std::string, TreePatternNode*> ArgMap;
1378 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1379 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001380
Chris Lattner8cab0212008-01-05 22:25:12 +00001381 FragTree->SubstituteFormalArguments(ArgMap);
1382 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001383
Chris Lattner8cab0212008-01-05 22:25:12 +00001384 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001385 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1386 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001387
1388 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001389 for (const TreePredicateFn &Pred : getPredicateFns())
1390 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001391
Chris Lattner8cab0212008-01-05 22:25:12 +00001392 // Get a new copy of this fragment to stitch into here.
1393 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001394
Chris Lattner2e253b42008-06-30 03:02:03 +00001395 // The fragment we inlined could have recursive inlining that is needed. See
1396 // if there are any pattern fragments in it and inline them as needed.
1397 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001398}
1399
1400/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001401/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001402/// references from the register file information, for example.
1403///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001404/// When Unnamed is set, return the type of a DAG operand with no name, such as
1405/// the F8RC register class argument in:
1406///
1407/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1408///
1409/// When Unnamed is false, return the type of a named DAG operand such as the
1410/// GPR:$src operand above.
1411///
Chris Lattnerf1447252010-03-19 21:37:09 +00001412static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001413 bool NotRegisters,
1414 bool Unnamed,
1415 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001416 // Check to see if this is a register operand.
1417 if (R->isSubClassOf("RegisterOperand")) {
1418 assert(ResNo == 0 && "Regoperand ref only has one result!");
1419 if (NotRegisters)
1420 return EEVT::TypeSet(); // Unknown.
1421 Record *RegClass = R->getValueAsDef("RegClass");
1422 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1423 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1424 }
1425
Chris Lattnercabe0372010-03-15 06:00:16 +00001426 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001427 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001428 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001429 // An unnamed register class represents itself as an i32 immediate, for
1430 // example on a COPY_TO_REGCLASS instruction.
1431 if (Unnamed)
1432 return EEVT::TypeSet(MVT::i32, TP);
1433
1434 // In a named operand, the register class provides the possible set of
1435 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001436 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001437 return EEVT::TypeSet(); // Unknown.
1438 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1439 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001440 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001441
Chris Lattner6070ee22010-03-23 23:50:31 +00001442 if (R->isSubClassOf("PatFrag")) {
1443 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001444 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001445 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001446 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001447
Chris Lattner6070ee22010-03-23 23:50:31 +00001448 if (R->isSubClassOf("Register")) {
1449 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001450 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001451 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001452 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001453 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001454 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001455
1456 if (R->isSubClassOf("SubRegIndex")) {
1457 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001458 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001459 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001460
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001461 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001462 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001463 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1464 //
1465 // (sext_inreg GPR:$src, i16)
1466 // ~~~
1467 if (Unnamed)
1468 return EEVT::TypeSet(MVT::Other, TP);
1469 // With a name, the ValueType simply provides the type of the named
1470 // variable.
1471 //
1472 // (sext_inreg i32:$src, i16)
1473 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001474 if (NotRegisters)
1475 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001476 return EEVT::TypeSet(getValueType(R), TP);
1477 }
1478
1479 if (R->isSubClassOf("CondCode")) {
1480 assert(ResNo == 0 && "This node only has one result!");
1481 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001482 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001483 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001484
Chris Lattner6070ee22010-03-23 23:50:31 +00001485 if (R->isSubClassOf("ComplexPattern")) {
1486 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001487 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001488 return EEVT::TypeSet(); // Unknown.
1489 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1490 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001491 }
1492 if (R->isSubClassOf("PointerLikeRegClass")) {
1493 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001494 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001495 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001496
Chris Lattner6070ee22010-03-23 23:50:31 +00001497 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1498 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001499 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001500 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001501 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001502
Tim Northoverc807a172014-05-20 11:52:46 +00001503 if (R->isSubClassOf("Operand"))
1504 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1505
Chris Lattner8cab0212008-01-05 22:25:12 +00001506 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001507 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001508}
1509
Chris Lattner89c65662008-01-06 05:36:50 +00001510
1511/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1512/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1513const CodeGenIntrinsic *TreePatternNode::
1514getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1515 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1516 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1517 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001518 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001519
Sean Silva88eb8dd2012-10-10 20:24:47 +00001520 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001521 return &CDP.getIntrinsicInfo(IID);
1522}
1523
Chris Lattner53c39ba2010-02-14 22:22:58 +00001524/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1525/// return the ComplexPattern information, otherwise return null.
1526const ComplexPattern *
1527TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001528 Record *Rec;
1529 if (isLeaf()) {
1530 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1531 if (!DI)
1532 return nullptr;
1533 Rec = DI->getDef();
1534 } else
1535 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001536
Tim Northoverc807a172014-05-20 11:52:46 +00001537 if (!Rec->isSubClassOf("ComplexPattern"))
1538 return nullptr;
1539 return &CGP.getComplexPattern(Rec);
1540}
1541
1542unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1543 // A ComplexPattern specifically declares how many results it fills in.
1544 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1545 return CP->getNumOperands();
1546
1547 // If MIOperandInfo is specified, that gives the count.
1548 if (isLeaf()) {
1549 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1550 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1551 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1552 if (MIOps->getNumArgs())
1553 return MIOps->getNumArgs();
1554 }
1555 }
1556
1557 // Otherwise there is just one result.
1558 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001559}
1560
1561/// NodeHasProperty - Return true if this node has the specified property.
1562bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001563 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001564 if (isLeaf()) {
1565 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1566 return CP->hasProperty(Property);
1567 return false;
1568 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001569
Chris Lattner53c39ba2010-02-14 22:22:58 +00001570 Record *Operator = getOperator();
1571 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001572
Chris Lattner53c39ba2010-02-14 22:22:58 +00001573 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1574}
1575
1576
1577
1578
1579/// TreeHasProperty - Return true if any node in this tree has the specified
1580/// property.
1581bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001582 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001583 if (NodeHasProperty(Property, CGP))
1584 return true;
1585 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1586 if (getChild(i)->TreeHasProperty(Property, CGP))
1587 return true;
1588 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001589}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001590
Evan Cheng49bad4c2008-06-16 20:29:38 +00001591/// isCommutativeIntrinsic - Return true if the node corresponds to a
1592/// commutative intrinsic.
1593bool
1594TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1595 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1596 return Int->isCommutative;
1597 return false;
1598}
1599
Matt Arsenaulteb492162014-11-02 23:46:51 +00001600static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1601 if (!N->isLeaf())
1602 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001603
Matt Arsenaulteb492162014-11-02 23:46:51 +00001604 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1605 if (DI && DI->getDef()->isSubClassOf(Class))
1606 return true;
1607
1608 return false;
1609}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001610
1611static void emitTooManyOperandsError(TreePattern &TP,
1612 StringRef InstName,
1613 unsigned Expected,
1614 unsigned Actual) {
1615 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1616 " operands but expected only " + Twine(Expected) + "!");
1617}
1618
1619static void emitTooFewOperandsError(TreePattern &TP,
1620 StringRef InstName,
1621 unsigned Actual) {
1622 TP.error("Instruction '" + InstName +
1623 "' expects more than the provided " + Twine(Actual) + " operands!");
1624}
1625
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001626/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001627/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001628/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001629bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001630 if (TP.hasError())
1631 return false;
1632
Chris Lattnerab3242f2008-01-06 01:10:31 +00001633 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001634 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001635 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001636 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001637 bool MadeChange = false;
1638 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1639 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001640 NotRegisters,
1641 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001642 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001643 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001644
Sean Silvafb509ed2012-10-10 20:24:43 +00001645 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001646 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001647
Chris Lattnerf1447252010-03-19 21:37:09 +00001648 // Int inits are always integers. :)
1649 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001650
Chris Lattnerf1447252010-03-19 21:37:09 +00001651 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001652 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001653
Chris Lattnerf1447252010-03-19 21:37:09 +00001654 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001655 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1656 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001657
Craig Topper95198f42013-09-25 06:37:18 +00001658 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001659 // Make sure that the value is representable for this type.
1660 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001661
Richard Smith228e6d42012-08-24 23:29:28 +00001662 // Check that the value doesn't use more bits than we have. It must either
1663 // be a sign- or zero-extended equivalent of the original.
1664 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1665 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001666 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001667
Richard Smith228e6d42012-08-24 23:29:28 +00001668 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001669 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001670 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001671 }
1672 return false;
1673 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001674
Chris Lattner8cab0212008-01-05 22:25:12 +00001675 // special handling for set, which isn't really an SDNode.
1676 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001677 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1678 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001679 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001680
Chris Lattnerf1447252010-03-19 21:37:09 +00001681 TreePatternNode *SetVal = getChild(NC-1);
1682 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1683
Elena Demikhovsky09954792015-03-01 08:23:41 +00001684 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001685 TreePatternNode *Child = getChild(i);
1686 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001687
Chris Lattner8cab0212008-01-05 22:25:12 +00001688 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001689 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1690 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001691 }
1692 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001693 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001694
Chris Lattner5c2182e2010-03-27 02:53:27 +00001695 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001696 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1697
Chris Lattner8cab0212008-01-05 22:25:12 +00001698 bool MadeChange = false;
1699 for (unsigned i = 0; i < getNumChildren(); ++i)
1700 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001701 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001702 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001703
Chris Lattneree820ac2010-02-23 05:51:07 +00001704 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001705 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001706
Chris Lattner8cab0212008-01-05 22:25:12 +00001707 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001708 unsigned NumRetVTs = Int->IS.RetVTs.size();
1709 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001710
Bill Wendling91821472008-11-13 09:08:33 +00001711 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001712 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001713
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001714 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001715 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001716 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001717 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001718 return false;
1719 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001720
1721 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001722 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001723
Chris Lattnerf1447252010-03-19 21:37:09 +00001724 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1725 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001726
Chris Lattnerf1447252010-03-19 21:37:09 +00001727 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1728 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1729 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001730 }
1731 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001732 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001733
Chris Lattneree820ac2010-02-23 05:51:07 +00001734 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001735 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001736
Chris Lattner135091b2010-03-28 08:48:47 +00001737 // Check that the number of operands is sane. Negative operands -> varargs.
1738 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001739 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001740 TP.error(getOperator()->getName() + " node requires exactly " +
1741 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001742 return false;
1743 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001744
Chris Lattner8cab0212008-01-05 22:25:12 +00001745 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1746 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1747 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001748 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001749 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001750
Chris Lattneree820ac2010-02-23 05:51:07 +00001751 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001752 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001753 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001754 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001755
Chris Lattnerd44966f2010-03-27 19:15:02 +00001756 bool MadeChange = false;
1757
1758 // Apply the result types to the node, these come from the things in the
1759 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001760 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1761 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001762 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1763 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001764
Chris Lattnerd44966f2010-03-27 19:15:02 +00001765 // If the instruction has implicit defs, we apply the first one as a result.
1766 // FIXME: This sucks, it should apply all implicit defs.
1767 if (!InstInfo.ImplicitDefs.empty()) {
1768 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001769
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001770 // FIXME: Generalize to multiple possible types and multiple possible
1771 // ImplicitDefs.
1772 MVT::SimpleValueType VT =
1773 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001774
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001775 if (VT != MVT::Other)
1776 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001777 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001778
Chris Lattnercabe0372010-03-15 06:00:16 +00001779 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1780 // be the same.
1781 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001782 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1783 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1784 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001785 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1786 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1787 // variadic.
1788
1789 unsigned NChild = getNumChildren();
1790 if (NChild < 3) {
1791 TP.error("REG_SEQUENCE requires at least 3 operands!");
1792 return false;
1793 }
1794
1795 if (NChild % 2 == 0) {
1796 TP.error("REG_SEQUENCE requires an odd number of operands!");
1797 return false;
1798 }
1799
1800 if (!isOperandClass(getChild(0), "RegisterClass")) {
1801 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1802 return false;
1803 }
1804
1805 for (unsigned I = 1; I < NChild; I += 2) {
1806 TreePatternNode *SubIdxChild = getChild(I + 1);
1807 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1808 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1809 itostr(I + 1) + "!");
1810 return false;
1811 }
1812 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001813 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001814
1815 unsigned ChildNo = 0;
1816 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1817 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001818
Chris Lattner8cab0212008-01-05 22:25:12 +00001819 // If the instruction expects a predicate or optional def operand, we
1820 // codegen this by setting the operand to it's default value if it has a
1821 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001822 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001823 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1824 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001825
Chris Lattner8cab0212008-01-05 22:25:12 +00001826 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001827 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001828 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001829 return false;
1830 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001831
Chris Lattner8cab0212008-01-05 22:25:12 +00001832 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001833 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001834
1835 // If the operand has sub-operands, they may be provided by distinct
1836 // child patterns, so attempt to match each sub-operand separately.
1837 if (OperandNode->isSubClassOf("Operand")) {
1838 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1839 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1840 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001841 // a single ComplexPattern-related Operand.
1842
1843 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001844 // Match first sub-operand against the child we already have.
1845 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1846 MadeChange |=
1847 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1848
1849 // And the remaining sub-operands against subsequent children.
1850 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1851 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001852 emitTooFewOperandsError(TP, getOperator()->getName(),
1853 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001854 return false;
1855 }
1856 Child = getChild(ChildNo++);
1857
1858 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1859 MadeChange |=
1860 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1861 }
1862 continue;
1863 }
1864 }
1865 }
1866
1867 // If we didn't match by pieces above, attempt to match the whole
1868 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001869 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001870 }
Christopher Lamba7312392008-03-11 09:33:47 +00001871
Matt Arsenaulteb492162014-11-02 23:46:51 +00001872 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001873 emitTooManyOperandsError(TP, getOperator()->getName(),
1874 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001875 return false;
1876 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001877
Ulrich Weigande618abd2013-03-19 19:51:09 +00001878 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1879 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001880 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001881 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001882
Tim Northoverc807a172014-05-20 11:52:46 +00001883 if (getOperator()->isSubClassOf("ComplexPattern")) {
1884 bool MadeChange = false;
1885
1886 for (unsigned i = 0; i < getNumChildren(); ++i)
1887 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1888
1889 return MadeChange;
1890 }
1891
Chris Lattneree820ac2010-02-23 05:51:07 +00001892 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001893
Chris Lattneree820ac2010-02-23 05:51:07 +00001894 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001895 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001896 TP.error("Node transform '" + getOperator()->getName() +
1897 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001898 return false;
1899 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001900
Chris Lattnercabe0372010-03-15 06:00:16 +00001901 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1902
Jim Grosbach65586fe2010-12-21 16:16:00 +00001903
Chris Lattneree820ac2010-02-23 05:51:07 +00001904 // If either the output or input of the xform does not have exact
1905 // type info. We assume they must be the same. Otherwise, it is perfectly
1906 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001907#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001908 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001909 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1910 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001911 return MadeChange;
1912 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001913#endif
1914 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001915}
1916
1917/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1918/// RHS of a commutative operation, not the on LHS.
1919static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1920 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1921 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001922 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001923 return true;
1924 return false;
1925}
1926
1927
1928/// canPatternMatch - If it is impossible for this pattern to match on this
1929/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001930/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001931/// that can never possibly work), and to prevent the pattern permuter from
1932/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001933bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001934 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001935 if (isLeaf()) return true;
1936
1937 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1938 if (!getChild(i)->canPatternMatch(Reason, CDP))
1939 return false;
1940
1941 // If this is an intrinsic, handle cases that would make it not match. For
1942 // example, if an operand is required to be an immediate.
1943 if (getOperator()->isSubClassOf("Intrinsic")) {
1944 // TODO:
1945 return true;
1946 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001947
Tim Northoverc807a172014-05-20 11:52:46 +00001948 if (getOperator()->isSubClassOf("ComplexPattern"))
1949 return true;
1950
Chris Lattner8cab0212008-01-05 22:25:12 +00001951 // If this node is a commutative operator, check that the LHS isn't an
1952 // immediate.
1953 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001954 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1955 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001956 // Scan all of the operands of the node and make sure that only the last one
1957 // is a constant node, unless the RHS also is.
1958 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001959 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1960 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001961 if (OnlyOnRHSOfCommutative(getChild(i))) {
1962 Reason="Immediate value must be on the RHS of commutative operators!";
1963 return false;
1964 }
1965 }
1966 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001967
Chris Lattner8cab0212008-01-05 22:25:12 +00001968 return true;
1969}
1970
1971//===----------------------------------------------------------------------===//
1972// TreePattern implementation
1973//
1974
David Greeneaf8ee2c2011-07-29 22:43:06 +00001975TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001976 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1977 isInputPattern(isInput), HasError(false) {
Craig Topperef0578a2015-06-02 04:15:51 +00001978 for (Init *I : RawPat->getValues())
1979 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001980}
1981
David Greeneaf8ee2c2011-07-29 22:43:06 +00001982TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001983 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1984 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001985 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001986}
1987
David Blaikiecf195302014-11-17 22:55:41 +00001988TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001989 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1990 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00001991 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00001992}
1993
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00001994void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001995 if (HasError)
1996 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001997 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001998 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1999 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002000}
2001
Chris Lattnercabe0372010-03-15 06:00:16 +00002002void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002003 for (TreePatternNode *Tree : Trees)
2004 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002005}
2006
2007void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2008 if (!N->getName().empty())
2009 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002010
Chris Lattnercabe0372010-03-15 06:00:16 +00002011 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2012 ComputeNamedNodes(N->getChild(i));
2013}
2014
David Blaikiecf195302014-11-17 22:55:41 +00002015
2016TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002017 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002018 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002019
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002020 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002021 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002022 /// (foo GPR, imm) -> (foo GPR, (imm))
2023 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002024 return ParseTreePattern(
2025 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002026 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002027 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002028
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002029 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002030 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002031 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002032 if (OpName.empty())
2033 error("'node' argument requires a name to match with operand list");
2034 Args.push_back(OpName);
2035 }
2036
2037 Res->setName(OpName);
2038 return Res;
2039 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002040
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002041 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002042 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002043 if (OpName.empty())
2044 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002045 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002046 Args.push_back(OpName);
2047 Res->setName(OpName);
2048 return Res;
2049 }
2050
Sean Silvafb509ed2012-10-10 20:24:43 +00002051 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002052 if (!OpName.empty())
2053 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002054 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002055 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002056
Sean Silvafb509ed2012-10-10 20:24:43 +00002057 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002058 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002059 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002060 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002061 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002062 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002063 }
2064
Sean Silvafb509ed2012-10-10 20:24:43 +00002065 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002066 if (!Dag) {
2067 TheInit->dump();
2068 error("Pattern has unexpected init kind!");
2069 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002070 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002071 if (!OpDef) error("Pattern has unexpected operator type!");
2072 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002073
Chris Lattner8cab0212008-01-05 22:25:12 +00002074 if (Operator->isSubClassOf("ValueType")) {
2075 // If the operator is a ValueType, then this must be "type cast" of a leaf
2076 // node.
2077 if (Dag->getNumArgs() != 1)
2078 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002079
David Blaikiecf195302014-11-17 22:55:41 +00002080 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002081
Chris Lattner8cab0212008-01-05 22:25:12 +00002082 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002083 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2084 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002085
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002086 if (!OpName.empty())
2087 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002088 return New;
2089 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002090
Chris Lattner8cab0212008-01-05 22:25:12 +00002091 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002092 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002093 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002094 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002095 !Operator->isSubClassOf("SDNodeXForm") &&
2096 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002097 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002098 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002099 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002100 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002101
Chris Lattner8cab0212008-01-05 22:25:12 +00002102 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002103 if (isInputPattern) {
2104 if (Operator->isSubClassOf("Instruction") ||
2105 Operator->isSubClassOf("SDNodeXForm"))
2106 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2107 } else {
2108 if (Operator->isSubClassOf("Intrinsic"))
2109 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002110
Chris Lattner2e9eae12010-03-28 06:57:56 +00002111 if (Operator->isSubClassOf("SDNode") &&
2112 Operator->getName() != "imm" &&
2113 Operator->getName() != "fpimm" &&
2114 Operator->getName() != "tglobaltlsaddr" &&
2115 Operator->getName() != "tconstpool" &&
2116 Operator->getName() != "tjumptable" &&
2117 Operator->getName() != "tframeindex" &&
2118 Operator->getName() != "texternalsym" &&
2119 Operator->getName() != "tblockaddress" &&
2120 Operator->getName() != "tglobaladdr" &&
2121 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002122 Operator->getName() != "vt" &&
2123 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002124 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2125 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002126
Chris Lattner8cab0212008-01-05 22:25:12 +00002127 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002128
2129 // Parse all the operands.
2130 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002131 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002132
Chris Lattner8cab0212008-01-05 22:25:12 +00002133 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002134 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002135 // convert the intrinsic name to a number.
2136 if (Operator->isSubClassOf("Intrinsic")) {
2137 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2138 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2139
2140 // If this intrinsic returns void, it must have side-effects and thus a
2141 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002142 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002143 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002144 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002145 // Has side-effects, requires chain.
2146 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002147 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002148 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002149
David Greenee32ebf22011-07-29 19:07:07 +00002150 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002151 Children.insert(Children.begin(), IIDNode);
2152 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002153
Tim Northoverc807a172014-05-20 11:52:46 +00002154 if (Operator->isSubClassOf("ComplexPattern")) {
2155 for (unsigned i = 0; i < Children.size(); ++i) {
2156 TreePatternNode *Child = Children[i];
2157
2158 if (Child->getName().empty())
2159 error("All arguments to a ComplexPattern must be named");
2160
2161 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2162 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2163 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2164 auto OperandId = std::make_pair(Operator, i);
2165 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2166 if (PrevOp != ComplexPatternOperands.end()) {
2167 if (PrevOp->getValue() != OperandId)
2168 error("All ComplexPattern operands must appear consistently: "
2169 "in the same order in just one ComplexPattern instance.");
2170 } else
2171 ComplexPatternOperands[Child->getName()] = OperandId;
2172 }
2173 }
2174
Chris Lattnerf1447252010-03-19 21:37:09 +00002175 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002176 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002177 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002178
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002179 if (!Dag->getName().empty()) {
2180 assert(Result->getName().empty());
2181 Result->setName(Dag->getName());
2182 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002183 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002184}
2185
Chris Lattnera787c9e2010-03-28 08:38:32 +00002186/// SimplifyTree - See if we can simplify this tree to eliminate something that
2187/// will never match in favor of something obvious that will. This is here
2188/// strictly as a convenience to target authors because it allows them to write
2189/// more type generic things and have useless type casts fold away.
2190///
2191/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002192static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002193 if (N->isLeaf())
2194 return false;
2195
2196 // If we have a bitconvert with a resolved type and if the source and
2197 // destination types are the same, then the bitconvert is useless, remove it.
2198 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002199 N->getExtType(0).isConcrete() &&
2200 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2201 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002202 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002203 SimplifyTree(N);
2204 return true;
2205 }
2206
2207 // Walk all children.
2208 bool MadeChange = false;
2209 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002210 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002211 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002212 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002213 }
2214 return MadeChange;
2215}
2216
2217
2218
Chris Lattner8cab0212008-01-05 22:25:12 +00002219/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002220/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002221/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002222bool TreePattern::
2223InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2224 if (NamedNodes.empty())
2225 ComputeNamedNodes();
2226
Chris Lattner8cab0212008-01-05 22:25:12 +00002227 bool MadeChange = true;
2228 while (MadeChange) {
2229 MadeChange = false;
Craig Topper306cb122015-11-22 20:46:24 +00002230 for (TreePatternNode *Tree : Trees) {
2231 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2232 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002233 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002234
2235 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002236 for (auto &Entry : NamedNodes) {
2237 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002238
Chris Lattnercabe0372010-03-15 06:00:16 +00002239 // If we have input named node types, propagate their types to the named
2240 // values here.
2241 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002242 if (!InNamedTypes->count(Entry.getKey())) {
2243 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002244 "' in output pattern but not input pattern");
2245 return true;
2246 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002247
2248 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002249 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002250
2251 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002252 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002253 // If this node is a register class, and it is the root of the pattern
2254 // then we're mapping something onto an input register. We allow
2255 // changing the type of the input register in this case. This allows
2256 // us to match things like:
2257 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002258 if (Node == Trees[0] && Node->isLeaf()) {
2259 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002260 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2261 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002262 continue;
2263 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002264
Craig Topper306cb122015-11-22 20:46:24 +00002265 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002266 InNodes[0]->getNumTypes() == 1 &&
2267 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002268 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2269 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002270 }
2271 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002272
Chris Lattnercabe0372010-03-15 06:00:16 +00002273 // If there are multiple nodes with the same name, they must all have the
2274 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002275 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002276 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002277 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002278 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002279 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002280
Chris Lattnerf1447252010-03-19 21:37:09 +00002281 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2282 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002283 }
2284 }
2285 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002286 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002287
Chris Lattner8cab0212008-01-05 22:25:12 +00002288 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002289 for (const TreePatternNode *Tree : Trees)
2290 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
Chris Lattner8cab0212008-01-05 22:25:12 +00002291 return !HasUnresolvedTypes;
2292}
2293
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002294void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002295 OS << getRecord()->getName();
2296 if (!Args.empty()) {
2297 OS << "(" << Args[0];
2298 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2299 OS << ", " << Args[i];
2300 OS << ")";
2301 }
2302 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002303
Chris Lattner8cab0212008-01-05 22:25:12 +00002304 if (Trees.size() > 1)
2305 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002306 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002307 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002308 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002309 OS << "\n";
2310 }
2311
2312 if (Trees.size() > 1)
2313 OS << "]\n";
2314}
2315
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002316void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002317
2318//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002319// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002320//
2321
Jim Grosbach65586fe2010-12-21 16:16:00 +00002322CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002323 Records(R), Target(R) {
2324
Dale Johannesenb842d522009-02-05 01:49:45 +00002325 Intrinsics = LoadIntrinsics(Records, false);
2326 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002327 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002328 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002329 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002330 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002331 ParseDefaultOperands();
2332 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002333 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002334 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002335
Chris Lattner8cab0212008-01-05 22:25:12 +00002336 // Generate variants. For example, commutative patterns can match
2337 // multiple ways. Add them to PatternsToMatch as well.
2338 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002339
2340 // Infer instruction flags. For example, we can detect loads,
2341 // stores, and side effects in many cases by examining an
2342 // instruction's pattern.
2343 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002344
2345 // Verify that instruction flags match the patterns.
2346 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002347}
2348
Chris Lattnerab3242f2008-01-06 01:10:31 +00002349Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002350 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002351 if (!N || !N->isSubClassOf("SDNode"))
2352 PrintFatalError("Error getting SDNode '" + Name + "'!");
2353
Chris Lattner8cab0212008-01-05 22:25:12 +00002354 return N;
2355}
2356
2357// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002358void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002359 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2360 while (!Nodes.empty()) {
2361 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2362 Nodes.pop_back();
2363 }
2364
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002365 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002366 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2367 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2368 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2369}
2370
2371/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2372/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002373void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002374 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2375 while (!Xforms.empty()) {
2376 Record *XFormNode = Xforms.back();
2377 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002378 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002379 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002380
2381 Xforms.pop_back();
2382 }
2383}
2384
Chris Lattnerab3242f2008-01-06 01:10:31 +00002385void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002386 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2387 while (!AMs.empty()) {
2388 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2389 AMs.pop_back();
2390 }
2391}
2392
2393
2394/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2395/// file, building up the PatternFragments map. After we've collected them all,
2396/// inline fragments together as necessary, so that there are no references left
2397/// inside a pattern fragment to a pattern fragment.
2398///
Hal Finkel2756dc12014-02-28 00:26:56 +00002399void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002400 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002401
Chris Lattnere7170df2008-01-05 22:43:57 +00002402 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002403 for (Record *Frag : Fragments) {
2404 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002405 continue;
2406
Craig Topper306cb122015-11-22 20:46:24 +00002407 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002408 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002409 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2410 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002411 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002412
Chris Lattnere7170df2008-01-05 22:43:57 +00002413 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002414 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002415 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002416
Chris Lattnere7170df2008-01-05 22:43:57 +00002417 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002418 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002419
Chris Lattner8cab0212008-01-05 22:25:12 +00002420 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002421 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002422 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002423 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002424 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002425 if (!OpsOp ||
2426 (OpsOp->getDef()->getName() != "ops" &&
2427 OpsOp->getDef()->getName() != "outs" &&
2428 OpsOp->getDef()->getName() != "ins"))
2429 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002430
2431 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002432 Args.clear();
2433 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002434 if (!isa<DefInit>(OpsList->getArg(j)) ||
2435 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002436 P->error("Operands list should all be 'node' values.");
2437 if (OpsList->getArgName(j).empty())
2438 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002439 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002440 P->error("'" + OpsList->getArgName(j) +
2441 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002442 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002443 Args.push_back(OpsList->getArgName(j));
2444 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002445
Chris Lattnere7170df2008-01-05 22:43:57 +00002446 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002447 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002448 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002449
Chris Lattnere7170df2008-01-05 22:43:57 +00002450 // If there is a code init for this fragment, keep track of the fact that
2451 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002452 TreePredicateFn PredFn(P);
2453 if (!PredFn.isAlwaysTrue())
2454 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002455
Chris Lattner8cab0212008-01-05 22:25:12 +00002456 // If there is a node transformation corresponding to this, keep track of
2457 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002458 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002459 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2460 P->getOnlyTree()->setTransformFn(Transform);
2461 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002462
Chris Lattner8cab0212008-01-05 22:25:12 +00002463 // Now that we've parsed all of the tree fragments, do a closure on them so
2464 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002465 for (Record *Frag : Fragments) {
2466 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002467 continue;
2468
Craig Topper306cb122015-11-22 20:46:24 +00002469 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002470 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002471
Chris Lattner8cab0212008-01-05 22:25:12 +00002472 // Infer as many types as possible. Don't worry about it if we don't infer
2473 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002474 ThePat.InferAllTypes();
2475 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002476
Chris Lattner8cab0212008-01-05 22:25:12 +00002477 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002478 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002479 }
2480}
2481
Chris Lattnerab3242f2008-01-06 01:10:31 +00002482void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002483 std::vector<Record*> DefaultOps;
2484 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002485
2486 // Find some SDNode.
2487 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002488 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002489
Tom Stellardb7246a72012-09-06 14:15:52 +00002490 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2491 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002492
Tom Stellardb7246a72012-09-06 14:15:52 +00002493 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2494 // SomeSDnode so that we can parse this.
2495 std::vector<std::pair<Init*, std::string> > Ops;
2496 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2497 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2498 DefaultInfo->getArgName(op)));
2499 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002500
Tom Stellardb7246a72012-09-06 14:15:52 +00002501 // Create a TreePattern to parse this.
2502 TreePattern P(DefaultOps[i], DI, false, *this);
2503 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002504
Tom Stellardb7246a72012-09-06 14:15:52 +00002505 // Copy the operands over into a DAGDefaultOperand.
2506 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002507
Tom Stellardb7246a72012-09-06 14:15:52 +00002508 TreePatternNode *T = P.getTree(0);
2509 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2510 TreePatternNode *TPN = T->getChild(op);
2511 while (TPN->ApplyTypeConstraints(P, false))
2512 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002513
Tom Stellardb7246a72012-09-06 14:15:52 +00002514 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002515 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2516 DefaultOps[i]->getName() +
2517 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002518 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002519 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002520 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002521
2522 // Insert it into the DefaultOperands map so we can find it later.
2523 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002524 }
2525}
2526
2527/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2528/// instruction input. Return true if this is a real use.
2529static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002530 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002531 // No name -> not interesting.
2532 if (Pat->getName().empty()) {
2533 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002534 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002535 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2536 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002537 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002538 }
2539 return false;
2540 }
2541
2542 Record *Rec;
2543 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002544 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002545 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2546 Rec = DI->getDef();
2547 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002548 Rec = Pat->getOperator();
2549 }
2550
2551 // SRCVALUE nodes are ignored.
2552 if (Rec->getName() == "srcvalue")
2553 return false;
2554
2555 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2556 if (!Slot) {
2557 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002558 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002559 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002560 Record *SlotRec;
2561 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002562 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002563 } else {
2564 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2565 SlotRec = Slot->getOperator();
2566 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002567
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002568 // Ensure that the inputs agree if we've already seen this input.
2569 if (Rec != SlotRec)
2570 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002571 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002572 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002573 return true;
2574}
2575
2576/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2577/// part of "I", the instruction), computing the set of inputs and outputs of
2578/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002579void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002580FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2581 std::map<std::string, TreePatternNode*> &InstInputs,
2582 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002583 std::vector<Record*> &InstImpResults) {
2584 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002585 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002586 if (!isUse && Pat->getTransformFn())
2587 I->error("Cannot specify a transform function for a non-input value!");
2588 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002589 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002590
Chris Lattnerf2d70992010-02-17 06:53:36 +00002591 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002592 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2593 TreePatternNode *Dest = Pat->getChild(i);
2594 if (!Dest->isLeaf())
2595 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002596
Sean Silvafb509ed2012-10-10 20:24:43 +00002597 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002598 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2599 I->error("implicitly defined value should be a register!");
2600 InstImpResults.push_back(Val->getDef());
2601 }
2602 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002603 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002604
Chris Lattnerf2d70992010-02-17 06:53:36 +00002605 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002606 // If this is not a set, verify that the children nodes are not void typed,
2607 // and recurse.
2608 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002609 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002610 I->error("Cannot have void nodes inside of patterns!");
2611 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002612 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002613 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002614
Chris Lattner8cab0212008-01-05 22:25:12 +00002615 // If this is a non-leaf node with no children, treat it basically as if
2616 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002617 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002618
Chris Lattner8cab0212008-01-05 22:25:12 +00002619 if (!isUse && Pat->getTransformFn())
2620 I->error("Cannot specify a transform function for a non-input value!");
2621 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002622 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002623
Chris Lattner8cab0212008-01-05 22:25:12 +00002624 // Otherwise, this is a set, validate and collect instruction results.
2625 if (Pat->getNumChildren() == 0)
2626 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002627
Chris Lattner8cab0212008-01-05 22:25:12 +00002628 if (Pat->getTransformFn())
2629 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002630
Chris Lattner8cab0212008-01-05 22:25:12 +00002631 // Check the set destinations.
2632 unsigned NumDests = Pat->getNumChildren()-1;
2633 for (unsigned i = 0; i != NumDests; ++i) {
2634 TreePatternNode *Dest = Pat->getChild(i);
2635 if (!Dest->isLeaf())
2636 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002637
Sean Silvafb509ed2012-10-10 20:24:43 +00002638 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002639 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002640 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002641 continue;
2642 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002643
2644 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002645 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002646 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002647 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002648 if (Dest->getName().empty())
2649 I->error("set destination must have a name!");
2650 if (InstResults.count(Dest->getName()))
2651 I->error("cannot set '" + Dest->getName() +"' multiple times");
2652 InstResults[Dest->getName()] = Dest;
2653 } else if (Val->getDef()->isSubClassOf("Register")) {
2654 InstImpResults.push_back(Val->getDef());
2655 } else {
2656 I->error("set destination should be a register!");
2657 }
2658 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002659
Chris Lattner8cab0212008-01-05 22:25:12 +00002660 // Verify and collect info from the computation.
2661 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002662 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002663}
2664
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002665//===----------------------------------------------------------------------===//
2666// Instruction Analysis
2667//===----------------------------------------------------------------------===//
2668
2669class InstAnalyzer {
2670 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002671public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002672 bool hasSideEffects;
2673 bool mayStore;
2674 bool mayLoad;
2675 bool isBitcast;
2676 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002677
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002678 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2679 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2680 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002681
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002682 void Analyze(const TreePattern *Pat) {
2683 // Assume only the first tree is the pattern. The others are clobber nodes.
2684 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002685 }
2686
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002687 void Analyze(const PatternToMatch *Pat) {
2688 AnalyzeNode(Pat->getSrcPattern());
2689 }
2690
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002691private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002692 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002693 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002694 return false;
2695
2696 if (N->getNumChildren() != 2)
2697 return false;
2698
2699 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002700 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002701 return false;
2702
2703 const TreePatternNode *N1 = N->getChild(1);
2704 if (N1->isLeaf())
2705 return false;
2706 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2707 return false;
2708
2709 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2710 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2711 return false;
2712 return OpInfo.getEnumName() == "ISD::BITCAST";
2713 }
2714
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002715public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002716 void AnalyzeNode(const TreePatternNode *N) {
2717 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002718 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002719 Record *LeafRec = DI->getDef();
2720 // Handle ComplexPattern leaves.
2721 if (LeafRec->isSubClassOf("ComplexPattern")) {
2722 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2723 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2724 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002725 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002726 }
2727 }
2728 return;
2729 }
2730
2731 // Analyze children.
2732 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2733 AnalyzeNode(N->getChild(i));
2734
2735 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002736 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002737 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002738 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002739 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002740
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002741 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002742 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2743 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2744 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2745 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002746
2747 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2748 // If this is an intrinsic, analyze it.
2749 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2750 mayLoad = true;// These may load memory.
2751
Dan Gohmanddb2d652010-08-05 23:36:21 +00002752 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002753 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2754
Dan Gohmanddb2d652010-08-05 23:36:21 +00002755 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002756 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002757 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002758 }
2759 }
2760
2761};
2762
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002763static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002764 const InstAnalyzer &PatInfo,
2765 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002766 bool Error = false;
2767
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002768 // Remember where InstInfo got its flags.
2769 if (InstInfo.hasUndefFlags())
2770 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002771
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002772 // Check explicitly set flags for consistency.
2773 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2774 !InstInfo.hasSideEffects_Unset) {
2775 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2776 // the pattern has no side effects. That could be useful for div/rem
2777 // instructions that may trap.
2778 if (!InstInfo.hasSideEffects) {
2779 Error = true;
2780 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2781 Twine(InstInfo.hasSideEffects));
2782 }
2783 }
2784
2785 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2786 Error = true;
2787 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2788 Twine(InstInfo.mayStore));
2789 }
2790
2791 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2792 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00002793 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002794 if (!InstInfo.mayLoad) {
2795 Error = true;
2796 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2797 Twine(InstInfo.mayLoad));
2798 }
2799 }
2800
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002801 // Transfer inferred flags.
2802 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2803 InstInfo.mayStore |= PatInfo.mayStore;
2804 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002805
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002806 // These flags are silently added without any verification.
2807 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002808
2809 // Don't infer isVariadic. This flag means something different on SDNodes and
2810 // instructions. For example, a CALL SDNode is variadic because it has the
2811 // call arguments as operands, but a CALL instruction is not variadic - it
2812 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002813
2814 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002815}
2816
Jim Grosbach514410b2012-07-17 00:47:06 +00002817/// hasNullFragReference - Return true if the DAG has any reference to the
2818/// null_frag operator.
2819static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002820 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002821 if (!OpDef) return false;
2822 Record *Operator = OpDef->getDef();
2823
2824 // If this is the null fragment, return true.
2825 if (Operator->getName() == "null_frag") return true;
2826 // If any of the arguments reference the null fragment, return true.
2827 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002828 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002829 if (Arg && hasNullFragReference(Arg))
2830 return true;
2831 }
2832
2833 return false;
2834}
2835
2836/// hasNullFragReference - Return true if any DAG in the list references
2837/// the null_frag operator.
2838static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00002839 for (Init *I : LI->getValues()) {
2840 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00002841 assert(DI && "non-dag in an instruction Pattern list?!");
2842 if (hasNullFragReference(DI))
2843 return true;
2844 }
2845 return false;
2846}
2847
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002848/// Get all the instructions in a tree.
2849static void
2850getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2851 if (Tree->isLeaf())
2852 return;
2853 if (Tree->getOperator()->isSubClassOf("Instruction"))
2854 Instrs.push_back(Tree->getOperator());
2855 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2856 getInstructionsInTree(Tree->getChild(i), Instrs);
2857}
2858
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002859/// Check the class of a pattern leaf node against the instruction operand it
2860/// represents.
2861static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2862 Record *Leaf) {
2863 if (OI.Rec == Leaf)
2864 return true;
2865
2866 // Allow direct value types to be used in instruction set patterns.
2867 // The type will be checked later.
2868 if (Leaf->isSubClassOf("ValueType"))
2869 return true;
2870
2871 // Patterns can also be ComplexPattern instances.
2872 if (Leaf->isSubClassOf("ComplexPattern"))
2873 return true;
2874
2875 return false;
2876}
2877
Ahmed Bougacha14107512013-10-28 18:07:21 +00002878const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2879 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002880
Craig Topper0d1fb902015-03-10 03:25:04 +00002881 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002882
Craig Topper0d1fb902015-03-10 03:25:04 +00002883 // Parse the instruction.
2884 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2885 // Inline pattern fragments into it.
2886 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002887
Craig Topper0d1fb902015-03-10 03:25:04 +00002888 // Infer as many types as possible. If we cannot infer all of them, we can
2889 // never do anything with this instruction pattern: report it to the user.
2890 if (!I->InferAllTypes())
2891 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002892
Craig Topper0d1fb902015-03-10 03:25:04 +00002893 // InstInputs - Keep track of all of the inputs of the instruction, along
2894 // with the record they are declared as.
2895 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002896
Craig Topper0d1fb902015-03-10 03:25:04 +00002897 // InstResults - Keep track of all the virtual registers that are 'set'
2898 // in the instruction, including what reg class they are.
2899 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002900
Craig Topper0d1fb902015-03-10 03:25:04 +00002901 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002902
Craig Topper0d1fb902015-03-10 03:25:04 +00002903 // Verify that the top-level forms in the instruction are of void type, and
2904 // fill in the InstResults map.
2905 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2906 TreePatternNode *Pat = I->getTree(j);
2907 if (Pat->getNumTypes() != 0)
2908 I->error("Top-level forms in instruction pattern should have"
2909 " void types");
Chris Lattner8cab0212008-01-05 22:25:12 +00002910
Craig Topper0d1fb902015-03-10 03:25:04 +00002911 // Find inputs and outputs, and verify the structure of the uses/defs.
2912 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2913 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002914 }
2915
Craig Topper0d1fb902015-03-10 03:25:04 +00002916 // Now that we have inputs and outputs of the pattern, inspect the operands
2917 // list for the instruction. This determines the order that operands are
2918 // added to the machine instruction the node corresponds to.
2919 unsigned NumResults = InstResults.size();
2920
2921 // Parse the operands list from the (ops) list, validating it.
2922 assert(I->getArgList().empty() && "Args list should still be empty here!");
2923
2924 // Check that all of the results occur first in the list.
2925 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00002926 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00002927 for (unsigned i = 0; i != NumResults; ++i) {
2928 if (i == CGI.Operands.size())
2929 I->error("'" + InstResults.begin()->first +
2930 "' set but does not appear in operand list!");
2931 const std::string &OpName = CGI.Operands[i].Name;
2932
2933 // Check that it exists in InstResults.
2934 TreePatternNode *RNode = InstResults[OpName];
2935 if (!RNode)
2936 I->error("Operand $" + OpName + " does not exist in operand list!");
2937
Craig Topper3a8eb892015-03-20 05:09:06 +00002938 ResNodes.push_back(RNode);
2939
Craig Topper0d1fb902015-03-10 03:25:04 +00002940 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2941 if (!R)
2942 I->error("Operand $" + OpName + " should be a set destination: all "
2943 "outputs must occur before inputs in operand list!");
2944
2945 if (!checkOperandClass(CGI.Operands[i], R))
2946 I->error("Operand $" + OpName + " class mismatch!");
2947
2948 // Remember the return type.
2949 Results.push_back(CGI.Operands[i].Rec);
2950
2951 // Okay, this one checks out.
2952 InstResults.erase(OpName);
2953 }
2954
2955 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2956 // the copy while we're checking the inputs.
2957 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2958
2959 std::vector<TreePatternNode*> ResultNodeOperands;
2960 std::vector<Record*> Operands;
2961 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2962 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2963 const std::string &OpName = Op.Name;
2964 if (OpName.empty())
2965 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2966
2967 if (!InstInputsCheck.count(OpName)) {
2968 // If this is an operand with a DefaultOps set filled in, we can ignore
2969 // this. When we codegen it, we will do so as always executed.
2970 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2971 // Does it have a non-empty DefaultOps field? If so, ignore this
2972 // operand.
2973 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2974 continue;
2975 }
2976 I->error("Operand $" + OpName +
2977 " does not appear in the instruction pattern");
2978 }
2979 TreePatternNode *InVal = InstInputsCheck[OpName];
2980 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2981
2982 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2983 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2984 if (!checkOperandClass(Op, InRec))
2985 I->error("Operand $" + OpName + "'s register class disagrees"
2986 " between the operand and pattern");
2987 }
2988 Operands.push_back(Op.Rec);
2989
2990 // Construct the result for the dest-pattern operand list.
2991 TreePatternNode *OpNode = InVal->clone();
2992
2993 // No predicate is useful on the result.
2994 OpNode->clearPredicateFns();
2995
2996 // Promote the xform function to be an explicit node if set.
2997 if (Record *Xform = OpNode->getTransformFn()) {
2998 OpNode->setTransformFn(nullptr);
2999 std::vector<TreePatternNode*> Children;
3000 Children.push_back(OpNode);
3001 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3002 }
3003
3004 ResultNodeOperands.push_back(OpNode);
3005 }
3006
3007 if (!InstInputsCheck.empty())
3008 I->error("Input operand $" + InstInputsCheck.begin()->first +
3009 " occurs in pattern but not in operands list!");
3010
3011 TreePatternNode *ResultPattern =
3012 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3013 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003014 // Copy fully inferred output node types to instruction result pattern.
3015 for (unsigned i = 0; i != NumResults; ++i) {
3016 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3017 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3018 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003019
3020 // Create and insert the instruction.
3021 // FIXME: InstImpResults should not be part of DAGInstruction.
3022 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3023 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3024
3025 // Use a temporary tree pattern to infer all types and make sure that the
3026 // constructed result is correct. This depends on the instruction already
3027 // being inserted into the DAGInsts map.
3028 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3029 Temp.InferAllTypes(&I->getNamedNodesMap());
3030
3031 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3032 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3033
3034 return TheInsertedInst;
3035}
3036
Ahmed Bougacha14107512013-10-28 18:07:21 +00003037/// ParseInstructions - Parse all of the instructions, inlining and resolving
3038/// any fragments involved. This populates the Instructions list with fully
3039/// resolved instructions.
3040void CodeGenDAGPatterns::ParseInstructions() {
3041 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3042
Craig Topper306cb122015-11-22 20:46:24 +00003043 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003044 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003045
Craig Topper306cb122015-11-22 20:46:24 +00003046 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3047 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003048
3049 // If there is no pattern, only collect minimal information about the
3050 // instruction for its operand list. We have to assume that there is one
3051 // result, as we have no detailed info. A pattern which references the
3052 // null_frag operator is as-if no pattern were specified. Normally this
3053 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3054 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003055 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003056 std::vector<Record*> Results;
3057 std::vector<Record*> Operands;
3058
Craig Topper306cb122015-11-22 20:46:24 +00003059 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003060
3061 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003062 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3063 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003064
Craig Topper3a8eb892015-03-20 05:09:06 +00003065 // The rest are inputs.
3066 for (unsigned j = InstInfo.Operands.NumDefs,
3067 e = InstInfo.Operands.size(); j < e; ++j)
3068 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003069 }
3070
3071 // Create and insert the instruction.
3072 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003073 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003074 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003075 continue; // no pattern.
3076 }
3077
Craig Topper306cb122015-11-22 20:46:24 +00003078 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003079 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3080
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003081 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003082 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003083 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003084
Chris Lattner8cab0212008-01-05 22:25:12 +00003085 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003086 for (auto &Entry : Instructions) {
3087 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003088 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003089 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003090
3091 // FIXME: Assume only the first tree is the pattern. The others are clobber
3092 // nodes.
3093 TreePatternNode *Pattern = I->getTree(0);
3094 TreePatternNode *SrcPattern;
3095 if (Pattern->getOperator()->getName() == "set") {
3096 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3097 } else{
3098 // Not a set (store or something?)
3099 SrcPattern = Pattern;
3100 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003101
Craig Topper306cb122015-11-22 20:46:24 +00003102 Record *Instr = Entry.first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003103 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003104 PatternToMatch(Instr,
3105 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003106 SrcPattern,
3107 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003108 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003109 Instr->getValueAsInt("AddedComplexity"),
3110 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003111 }
3112}
3113
Chris Lattnera7722b62010-02-23 06:55:24 +00003114
3115typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3116
Jim Grosbach65586fe2010-12-21 16:16:00 +00003117static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003118 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003119 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003120 if (!P->getName().empty()) {
3121 NameRecord &Rec = Names[P->getName()];
3122 // If this is the first instance of the name, remember the node.
3123 if (Rec.second++ == 0)
3124 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003125 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003126 PatternTop->error("repetition of value: $" + P->getName() +
3127 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003128 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003129
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003130 if (!P->isLeaf()) {
3131 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003132 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003133 }
3134}
3135
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003136void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003137 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003138 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003139 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003140 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3141 PrintWarning(Pattern->getRecord()->getLoc(),
3142 Twine("Pattern can never match: ") + Reason);
3143 return;
3144 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003145
Chris Lattner1e634e32010-03-01 22:29:19 +00003146 // If the source pattern's root is a complex pattern, that complex pattern
3147 // must specify the nodes it can potentially match.
3148 if (const ComplexPattern *CP =
3149 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3150 if (CP->getRootNodes().empty())
3151 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3152 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003153
3154
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003155 // Find all of the named values in the input and output, ensure they have the
3156 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003157 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003158 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3159 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003160
3161 // Scan all of the named values in the destination pattern, rejecting them if
3162 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003163 for (const auto &Entry : DstNames) {
3164 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003165 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003166 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003167 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003168
Chris Lattnera7722b62010-02-23 06:55:24 +00003169 // Scan all of the named values in the source pattern, rejecting them if the
3170 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003171 for (const auto &Entry : SrcNames)
3172 if (DstNames[Entry.first].first == nullptr &&
3173 SrcNames[Entry.first].second == 1)
3174 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003175
Chris Lattner0c0baa92010-02-23 06:16:51 +00003176 PatternsToMatch.push_back(PTM);
3177}
3178
3179
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003180
3181void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003182 const std::vector<const CodeGenInstruction*> &Instructions =
3183 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003184
3185 // First try to infer flags from the primary instruction pattern, if any.
3186 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003187 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003188 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3189 CodeGenInstruction &InstInfo =
3190 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003191
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003192 // Get the primary instruction pattern.
3193 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3194 if (!Pattern) {
3195 if (InstInfo.hasUndefFlags())
3196 Revisit.push_back(&InstInfo);
3197 continue;
3198 }
3199 InstAnalyzer PatInfo(*this);
3200 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003201 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003202 }
3203
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003204 // Second, look for single-instruction patterns defined outside the
3205 // instruction.
3206 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3207 const PatternToMatch &PTM = *I;
3208
3209 // We can only infer from single-instruction patterns, otherwise we won't
3210 // know which instruction should get the flags.
3211 SmallVector<Record*, 8> PatInstrs;
3212 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3213 if (PatInstrs.size() != 1)
3214 continue;
3215
3216 // Get the single instruction.
3217 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3218
3219 // Only infer properties from the first pattern. We'll verify the others.
3220 if (InstInfo.InferredFrom)
3221 continue;
3222
3223 InstAnalyzer PatInfo(*this);
3224 PatInfo.Analyze(&PTM);
3225 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3226 }
3227
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003228 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003229 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003230
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003231 // Revisit instructions with undefined flags and no pattern.
3232 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003233 for (CodeGenInstruction *InstInfo : Revisit) {
3234 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003235 continue;
3236 // The mayLoad and mayStore flags default to false.
3237 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003238 if (InstInfo->hasSideEffects_Unset)
3239 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003240 }
3241 return;
3242 }
3243
3244 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003245 for (CodeGenInstruction *InstInfo : Revisit) {
3246 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003247 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003248 if (InstInfo->hasSideEffects_Unset)
3249 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003250 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003251 if (InstInfo->mayStore_Unset)
3252 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003253 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003254 if (InstInfo->mayLoad_Unset)
3255 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003256 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003257 }
3258}
3259
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003260
3261/// Verify instruction flags against pattern node properties.
3262void CodeGenDAGPatterns::VerifyInstructionFlags() {
3263 unsigned Errors = 0;
3264 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3265 const PatternToMatch &PTM = *I;
3266 SmallVector<Record*, 8> Instrs;
3267 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3268 if (Instrs.empty())
3269 continue;
3270
3271 // Count the number of instructions with each flag set.
3272 unsigned NumSideEffects = 0;
3273 unsigned NumStores = 0;
3274 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003275 for (const Record *Instr : Instrs) {
3276 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003277 NumSideEffects += InstInfo.hasSideEffects;
3278 NumStores += InstInfo.mayStore;
3279 NumLoads += InstInfo.mayLoad;
3280 }
3281
3282 // Analyze the source pattern.
3283 InstAnalyzer PatInfo(*this);
3284 PatInfo.Analyze(&PTM);
3285
3286 // Collect error messages.
3287 SmallVector<std::string, 4> Msgs;
3288
3289 // Check for missing flags in the output.
3290 // Permit extra flags for now at least.
3291 if (PatInfo.hasSideEffects && !NumSideEffects)
3292 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3293
3294 // Don't verify store flags on instructions with side effects. At least for
3295 // intrinsics, side effects implies mayStore.
3296 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3297 Msgs.push_back("pattern may store, but mayStore isn't set");
3298
3299 // Similarly, mayStore implies mayLoad on intrinsics.
3300 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3301 Msgs.push_back("pattern may load, but mayLoad isn't set");
3302
3303 // Print error messages.
3304 if (Msgs.empty())
3305 continue;
3306 ++Errors;
3307
Craig Topper306cb122015-11-22 20:46:24 +00003308 for (const std::string &Msg : Msgs)
3309 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003310 (Instrs.size() == 1 ?
3311 "instruction" : "output instructions"));
3312 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003313 for (const Record *Instr : Instrs) {
3314 if (Instr != PTM.getSrcRecord())
3315 PrintError(Instr->getLoc(), "defined here");
3316 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003317 if (InstInfo.InferredFrom &&
3318 InstInfo.InferredFrom != InstInfo.TheDef &&
3319 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003320 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003321 }
3322 }
3323 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003324 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003325}
3326
Chris Lattnercabe0372010-03-15 06:00:16 +00003327/// Given a pattern result with an unresolved type, see if we can find one
3328/// instruction with an unresolved result type. Force this result type to an
3329/// arbitrary element if it's possible types to converge results.
3330static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3331 if (N->isLeaf())
3332 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003333
Chris Lattnercabe0372010-03-15 06:00:16 +00003334 // Analyze children.
3335 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3336 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3337 return true;
3338
3339 if (!N->getOperator()->isSubClassOf("Instruction"))
3340 return false;
3341
3342 // If this type is already concrete or completely unknown we can't do
3343 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003344 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3345 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3346 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003347
Chris Lattnerf1447252010-03-19 21:37:09 +00003348 // Otherwise, force its type to the first possibility (an arbitrary choice).
3349 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3350 return true;
3351 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003352
Chris Lattnerf1447252010-03-19 21:37:09 +00003353 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003354}
3355
Chris Lattnerab3242f2008-01-06 01:10:31 +00003356void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003357 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3358
Craig Topper306cb122015-11-22 20:46:24 +00003359 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003360 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003361
3362 // If the pattern references the null_frag, there's nothing to do.
3363 if (hasNullFragReference(Tree))
3364 continue;
3365
Chris Lattner5c2182e2010-03-27 02:53:27 +00003366 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003367
3368 // Inline pattern fragments into it.
3369 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003370
David Greeneaf8ee2c2011-07-29 22:43:06 +00003371 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003372 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003373
Chris Lattner8cab0212008-01-05 22:25:12 +00003374 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003375 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003376
Chris Lattner8cab0212008-01-05 22:25:12 +00003377 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003378 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003379
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003380 if (Result.getNumTrees() != 1)
3381 Result.error("Cannot handle instructions producing instructions "
3382 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003383
Chris Lattner8cab0212008-01-05 22:25:12 +00003384 bool IterateInference;
3385 bool InferredAllPatternTypes, InferredAllResultTypes;
3386 do {
3387 // Infer as many types as possible. If we cannot infer all of them, we
3388 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003389 InferredAllPatternTypes =
3390 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003391
Chris Lattner8cab0212008-01-05 22:25:12 +00003392 // Infer as many types as possible. If we cannot infer all of them, we
3393 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003394 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003395 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003396
Chris Lattnerfdc20712010-03-18 23:15:10 +00003397 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003398
Chris Lattner8cab0212008-01-05 22:25:12 +00003399 // Apply the type of the result to the source pattern. This helps us
3400 // resolve cases where the input type is known to be a pointer type (which
3401 // is considered resolved), but the result knows it needs to be 32- or
3402 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003403 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003404 Pattern->getTree(0)->getNumTypes());
3405 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003406 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3407 i, Result.getTree(0)->getExtType(i), Result);
3408 IterateInference |= Result.getTree(0)->UpdateNodeType(
3409 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003410 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003411
Chris Lattnercabe0372010-03-15 06:00:16 +00003412 // If our iteration has converged and the input pattern's types are fully
3413 // resolved but the result pattern is not fully resolved, we may have a
3414 // situation where we have two instructions in the result pattern and
3415 // the instructions require a common register class, but don't care about
3416 // what actual MVT is used. This is actually a bug in our modelling:
3417 // output patterns should have register classes, not MVTs.
3418 //
3419 // In any case, to handle this, we just go through and disambiguate some
3420 // arbitrary types to the result pattern's nodes.
3421 if (!IterateInference && InferredAllPatternTypes &&
3422 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003423 IterateInference =
3424 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003425 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003426
Chris Lattner8cab0212008-01-05 22:25:12 +00003427 // Verify that we inferred enough types that we can do something with the
3428 // pattern and result. If these fire the user has to add type casts.
3429 if (!InferredAllPatternTypes)
3430 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003431 if (!InferredAllResultTypes) {
3432 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003433 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003434 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003435
Chris Lattner8cab0212008-01-05 22:25:12 +00003436 // Validate that the input pattern is correct.
3437 std::map<std::string, TreePatternNode*> InstInputs;
3438 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003439 std::vector<Record*> InstImpResults;
3440 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3441 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3442 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003443 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003444
3445 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003446 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003447 std::vector<TreePatternNode*> ResultNodeOperands;
3448 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3449 TreePatternNode *OpNode = DstPattern->getChild(ii);
3450 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003451 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003452 std::vector<TreePatternNode*> Children;
3453 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003454 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003455 }
3456 ResultNodeOperands.push_back(OpNode);
3457 }
David Blaikiecf195302014-11-17 22:55:41 +00003458 DstPattern = Result.getOnlyTree();
3459 if (!DstPattern->isLeaf())
3460 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3461 ResultNodeOperands,
3462 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003463
David Blaikiecf195302014-11-17 22:55:41 +00003464 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3465 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3466
3467 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003468 Temp.InferAllTypes();
3469
Jim Grosbach65586fe2010-12-21 16:16:00 +00003470
Chris Lattner0c0baa92010-02-23 06:16:51 +00003471 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003472 PatternToMatch(CurPattern,
3473 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003474 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003475 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003476 CurPattern->getValueAsInt("AddedComplexity"),
3477 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003478 }
3479}
3480
3481/// CombineChildVariants - Given a bunch of permutations of each child of the
3482/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003483static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003484 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3485 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003486 CodeGenDAGPatterns &CDP,
3487 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003488 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003489 for (const auto &Variants : ChildVariants)
3490 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003491 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003492
Chris Lattner8cab0212008-01-05 22:25:12 +00003493 // The end result is an all-pairs construction of the resultant pattern.
3494 std::vector<unsigned> Idxs;
3495 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003496 bool NotDone;
3497 do {
3498#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003499 DEBUG(if (!Idxs.empty()) {
3500 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003501 for (unsigned Idx : Idxs) {
3502 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003503 }
3504 errs() << "]\n";
3505 });
Scott Michel94420742008-03-05 17:49:05 +00003506#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003507 // Create the variant and add it to the output list.
3508 std::vector<TreePatternNode*> NewChildren;
3509 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3510 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003511 auto R = llvm::make_unique<TreePatternNode>(
3512 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003513
Chris Lattner8cab0212008-01-05 22:25:12 +00003514 // Copy over properties.
3515 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003516 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003517 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003518 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3519 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003520
Scott Michel94420742008-03-05 17:49:05 +00003521 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003522 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003523 // Scan to see if this pattern has already been emitted. We can get
3524 // duplication due to things like commuting:
3525 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3526 // which are the same pattern. Ignore the dups.
3527 if (R->canPatternMatch(ErrString, CDP) &&
3528 std::none_of(OutVariants.begin(), OutVariants.end(),
3529 [&](TreePatternNode *Variant) {
3530 return R->isIsomorphicTo(Variant, DepVars);
3531 }))
3532 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003533
Scott Michel94420742008-03-05 17:49:05 +00003534 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003535 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003536 // [0, 0], [0, 1], [1, 0], [1, 1].
3537 int IdxsIdx;
3538 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3539 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3540 Idxs[IdxsIdx] = 0;
3541 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003542 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003543 }
Scott Michel94420742008-03-05 17:49:05 +00003544 NotDone = (IdxsIdx >= 0);
3545 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003546}
3547
3548/// CombineChildVariants - A helper function for binary operators.
3549///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003550static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003551 const std::vector<TreePatternNode*> &LHS,
3552 const std::vector<TreePatternNode*> &RHS,
3553 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003554 CodeGenDAGPatterns &CDP,
3555 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003556 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3557 ChildVariants.push_back(LHS);
3558 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003559 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003560}
Chris Lattner8cab0212008-01-05 22:25:12 +00003561
3562
3563static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3564 std::vector<TreePatternNode *> &Children) {
3565 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3566 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003567
Chris Lattner8cab0212008-01-05 22:25:12 +00003568 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003569 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003570 N->getTransformFn()) {
3571 Children.push_back(N);
3572 return;
3573 }
3574
3575 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3576 Children.push_back(N->getChild(0));
3577 else
3578 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3579
3580 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3581 Children.push_back(N->getChild(1));
3582 else
3583 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3584}
3585
3586/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3587/// the (potentially recursive) pattern by using algebraic laws.
3588///
3589static void GenerateVariantsOf(TreePatternNode *N,
3590 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003591 CodeGenDAGPatterns &CDP,
3592 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003593 // We cannot permute leaves or ComplexPattern uses.
3594 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003595 OutVariants.push_back(N);
3596 return;
3597 }
3598
3599 // Look up interesting info about the node.
3600 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3601
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003602 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003603 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003604 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003605 std::vector<TreePatternNode*> MaximalChildren;
3606 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3607
3608 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3609 // permutations.
3610 if (MaximalChildren.size() == 3) {
3611 // Find the variants of all of our maximal children.
3612 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003613 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3614 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3615 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003616
Chris Lattner8cab0212008-01-05 22:25:12 +00003617 // There are only two ways we can permute the tree:
3618 // (A op B) op C and A op (B op C)
3619 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003620
Chris Lattner8cab0212008-01-05 22:25:12 +00003621 // Generate legal pair permutations of A/B/C.
3622 std::vector<TreePatternNode*> ABVariants;
3623 std::vector<TreePatternNode*> BAVariants;
3624 std::vector<TreePatternNode*> ACVariants;
3625 std::vector<TreePatternNode*> CAVariants;
3626 std::vector<TreePatternNode*> BCVariants;
3627 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003628 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3629 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3630 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3631 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3632 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3633 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003634
3635 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003636 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3637 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3638 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3639 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3640 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3641 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003642
3643 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003644 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3645 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3646 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3647 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3648 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3649 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003650 return;
3651 }
3652 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003653
Chris Lattner8cab0212008-01-05 22:25:12 +00003654 // Compute permutations of all children.
3655 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3656 ChildVariants.resize(N->getNumChildren());
3657 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003658 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003659
3660 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003661 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003662
3663 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003664 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3665 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3666 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3667 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003668 // Don't count children which are actually register references.
3669 unsigned NC = 0;
3670 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3671 TreePatternNode *Child = N->getChild(i);
3672 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003673 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003674 Record *RR = DI->getDef();
3675 if (RR->isSubClassOf("Register"))
3676 continue;
3677 }
3678 NC++;
3679 }
3680 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003681 if (isCommIntrinsic) {
3682 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3683 // operands are the commutative operands, and there might be more operands
3684 // after those.
3685 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003686 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00003687 std::vector<std::vector<TreePatternNode*> > Variants;
3688 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3689 Variants.push_back(ChildVariants[2]);
3690 Variants.push_back(ChildVariants[1]);
3691 for (unsigned i = 3; i != NC; ++i)
3692 Variants.push_back(ChildVariants[i]);
3693 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3694 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003695 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003696 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003697 }
3698}
3699
3700
3701// GenerateVariants - Generate variants. For example, commutative patterns can
3702// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003703void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003704 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003705
Chris Lattner8cab0212008-01-05 22:25:12 +00003706 // Loop over all of the patterns we've collected, checking to see if we can
3707 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003708 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003709 // the .td file having to contain tons of variants of instructions.
3710 //
3711 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3712 // intentionally do not reconsider these. Any variants of added patterns have
3713 // already been added.
3714 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00003715 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003716 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003717 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003718 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003719 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003720 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003721 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00003722 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003723 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003724
3725 assert(!Variants.empty() && "Must create at least original variant!");
3726 Variants.erase(Variants.begin()); // Remove the original pattern.
3727
3728 if (Variants.empty()) // No variants for this pattern.
3729 continue;
3730
Chris Lattner34822f62009-08-23 04:44:11 +00003731 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00003732 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00003733 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003734
3735 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3736 TreePatternNode *Variant = Variants[v];
3737
Chris Lattner34822f62009-08-23 04:44:11 +00003738 DEBUG(errs() << " VAR#" << v << ": ";
3739 Variant->dump();
3740 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003741
Chris Lattner8cab0212008-01-05 22:25:12 +00003742 // Scan to see if an instruction or explicit pattern already matches this.
3743 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003744 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003745 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003746 if (PatternsToMatch[i].getPredicates() !=
3747 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00003748 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003749 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003750 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3751 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003752 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003753 AlreadyExists = true;
3754 break;
3755 }
3756 }
3757 // If we already have it, ignore the variant.
3758 if (AlreadyExists) continue;
3759
3760 // Otherwise, add it to the list of patterns we have.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003761 PatternsToMatch.emplace_back(
3762 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3763 Variant, PatternsToMatch[i].getDstPattern(),
3764 PatternsToMatch[i].getDstRegs(),
3765 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
Chris Lattner8cab0212008-01-05 22:25:12 +00003766 }
3767
Chris Lattner34822f62009-08-23 04:44:11 +00003768 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003769 }
3770}