blob: e48ba384532686bbc49d59588f1fbe7d1cafa694 [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"
Craig Topper3522ab32015-11-28 08:23:02 +000017#include "llvm/ADT/SmallString.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000018#include "llvm/ADT/StringExtras.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000019#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000020#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000021#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000022#include "llvm/TableGen/Error.h"
23#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000024#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000025#include <cstdio>
26#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000027using namespace llvm;
28
Chandler Carruthe96dd892014-04-21 22:55:11 +000029#define DEBUG_TYPE "dag-patterns"
30
Chris Lattner8cab0212008-01-05 22:25:12 +000031//===----------------------------------------------------------------------===//
Chris Lattnercabe0372010-03-15 06:00:16 +000032// EEVT::TypeSet Implementation
33//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +000034
Owen Anderson9f944592009-08-11 20:47:22 +000035static inline bool isInteger(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000036 return MVT(VT).isInteger();
Duncan Sands13237ac2008-06-06 12:08:01 +000037}
Owen Anderson9f944592009-08-11 20:47:22 +000038static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000039 return MVT(VT).isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000040}
Owen Anderson9f944592009-08-11 20:47:22 +000041static inline bool isVector(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000042 return MVT(VT).isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000043}
Chris Lattner6d765eb2010-03-19 17:41:26 +000044static inline bool isScalar(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000045 return !MVT(VT).isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000046}
Duncan Sands13237ac2008-06-06 12:08:01 +000047
Chris Lattnercabe0372010-03-15 06:00:16 +000048EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
49 if (VT == MVT::iAny)
50 EnforceInteger(TP);
51 else if (VT == MVT::fAny)
52 EnforceFloatingPoint(TP);
53 else if (VT == MVT::vAny)
54 EnforceVector(TP);
55 else {
56 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
Ramkumar Ramachandra75a4f352015-01-22 20:14:38 +000057 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
Chris Lattnercabe0372010-03-15 06:00:16 +000058 TypeVec.push_back(VT);
59 }
Chris Lattner8cab0212008-01-05 22:25:12 +000060}
61
Chris Lattnercabe0372010-03-15 06:00:16 +000062
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000063EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
Chris Lattnercabe0372010-03-15 06:00:16 +000064 assert(!VTList.empty() && "empty list?");
65 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +000066
Chris Lattnercabe0372010-03-15 06:00:16 +000067 if (!VTList.empty())
68 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
69 VTList[0] != MVT::fAny);
Jim Grosbach65586fe2010-12-21 16:16:00 +000070
Chris Lattner4a5f7be2010-03-27 20:32:26 +000071 // Verify no duplicates.
Chris Lattnercabe0372010-03-15 06:00:16 +000072 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner4a5f7be2010-03-27 20:32:26 +000073 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner8cab0212008-01-05 22:25:12 +000074}
75
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000076/// FillWithPossibleTypes - Set to all legal types and return true, only valid
77/// on completely unknown type sets.
Chris Lattner6d765eb2010-03-19 17:41:26 +000078bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
79 bool (*Pred)(MVT::SimpleValueType),
80 const char *PredicateName) {
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000081 assert(isCompletelyUnknown());
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000082 ArrayRef<MVT::SimpleValueType> LegalTypes =
Chris Lattner6d765eb2010-03-19 17:41:26 +000083 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +000084
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000085 if (TP.hasError())
86 return false;
87
Craig Topper306cb122015-11-22 20:46:24 +000088 for (MVT::SimpleValueType VT : LegalTypes)
89 if (!Pred || Pred(VT))
90 TypeVec.push_back(VT);
Chris Lattner6d765eb2010-03-19 17:41:26 +000091
92 // If we have nothing that matches the predicate, bail out.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000093 if (TypeVec.empty()) {
Chris Lattner6d765eb2010-03-19 17:41:26 +000094 TP.error("Type inference contradiction found, no " +
Jim Grosbach65586fe2010-12-21 16:16:00 +000095 std::string(PredicateName) + " types found");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000096 return false;
97 }
Chris Lattner6d765eb2010-03-19 17:41:26 +000098 // No need to sort with one element.
99 if (TypeVec.size() == 1) return true;
100
101 // Remove duplicates.
102 array_pod_sort(TypeVec.begin(), TypeVec.end());
103 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000104
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000105 return true;
106}
Chris Lattnercabe0372010-03-15 06:00:16 +0000107
108/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
109/// integer value type.
110bool EEVT::TypeSet::hasIntegerTypes() const {
David Majnemer0a16c222016-08-11 21:15:00 +0000111 return any_of(TypeVec, isInteger);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000112}
Chris Lattnercabe0372010-03-15 06:00:16 +0000113
114/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
115/// a floating point value type.
116bool EEVT::TypeSet::hasFloatingPointTypes() const {
David Majnemer0a16c222016-08-11 21:15:00 +0000117 return any_of(TypeVec, isFloatingPoint);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000118}
Chris Lattnercabe0372010-03-15 06:00:16 +0000119
Craig Topper74169dc2014-01-28 04:49:01 +0000120/// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
121bool EEVT::TypeSet::hasScalarTypes() const {
David Majnemer0a16c222016-08-11 21:15:00 +0000122 return any_of(TypeVec, isScalar);
Craig Topper74169dc2014-01-28 04:49:01 +0000123}
124
Chris Lattnercabe0372010-03-15 06:00:16 +0000125/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
126/// value type.
127bool EEVT::TypeSet::hasVectorTypes() const {
David Majnemer0a16c222016-08-11 21:15:00 +0000128 return any_of(TypeVec, isVector);
Chris Lattner8cab0212008-01-05 22:25:12 +0000129}
Bob Wilson2cd5da82009-08-11 01:14:02 +0000130
Chris Lattnercabe0372010-03-15 06:00:16 +0000131
132std::string EEVT::TypeSet::getName() const {
Chris Lattnerda5b4ad2010-03-19 01:14:27 +0000133 if (TypeVec.empty()) return "<empty>";
Jim Grosbach65586fe2010-12-21 16:16:00 +0000134
Chris Lattnercabe0372010-03-15 06:00:16 +0000135 std::string Result;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000136
Chris Lattnercabe0372010-03-15 06:00:16 +0000137 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
138 std::string VTName = llvm::getEnumName(TypeVec[i]);
139 // Strip off MVT:: prefix if present.
140 if (VTName.substr(0,5) == "MVT::")
141 VTName = VTName.substr(5);
142 if (i) Result += ':';
143 Result += VTName;
144 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000145
Chris Lattnercabe0372010-03-15 06:00:16 +0000146 if (TypeVec.size() == 1)
147 return Result;
148 return "{" + Result + "}";
Bob Wilson2cd5da82009-08-11 01:14:02 +0000149}
Chris Lattnercabe0372010-03-15 06:00:16 +0000150
151/// MergeInTypeInfo - This merges in type information from the specified
152/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000153/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattnercabe0372010-03-15 06:00:16 +0000154bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000155 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattnercabe0372010-03-15 06:00:16 +0000156 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000157
Chris Lattnercabe0372010-03-15 06:00:16 +0000158 if (isCompletelyUnknown()) {
159 *this = InVT;
160 return true;
161 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000162
Craig Topperd2177de2015-11-23 07:19:08 +0000163 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000164
Chris Lattnercabe0372010-03-15 06:00:16 +0000165 // Handle the abstract cases, seeing if we can resolve them better.
166 switch (TypeVec[0]) {
167 default: break;
168 case MVT::iPTR:
169 case MVT::iPTRAny:
170 if (InVT.hasIntegerTypes()) {
171 EEVT::TypeSet InCopy(InVT);
172 InCopy.EnforceInteger(TP);
173 InCopy.EnforceScalar(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000174
Chris Lattnercabe0372010-03-15 06:00:16 +0000175 if (InCopy.isConcrete()) {
176 // If the RHS has one integer type, upgrade iPTR to i32.
177 TypeVec[0] = InVT.TypeVec[0];
178 return true;
179 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000180
Chris Lattnercabe0372010-03-15 06:00:16 +0000181 // If the input has multiple scalar integers, this doesn't add any info.
182 if (!InCopy.isCompletelyUnknown())
183 return false;
184 }
185 break;
186 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000187
Chris Lattnercabe0372010-03-15 06:00:16 +0000188 // If the input constraint is iAny/iPTR and this is an integer type list,
189 // remove non-integer types from the list.
190 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
191 hasIntegerTypes()) {
192 bool MadeChange = EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000193
Chris Lattnercabe0372010-03-15 06:00:16 +0000194 // If we're merging in iPTR/iPTRAny and the node currently has a list of
195 // multiple different integer types, replace them with a single iPTR.
196 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
197 TypeVec.size() != 1) {
Craig Topper4856c812015-11-24 08:20:41 +0000198 TypeVec.assign(1, InVT.TypeVec[0]);
Chris Lattnercabe0372010-03-15 06:00:16 +0000199 MadeChange = true;
200 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000201
Chris Lattnercabe0372010-03-15 06:00:16 +0000202 return MadeChange;
203 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000204
Chris Lattnercabe0372010-03-15 06:00:16 +0000205 // If this is a type list and the RHS is a typelist as well, eliminate entries
206 // from this list that aren't in the other one.
Chris Lattnercabe0372010-03-15 06:00:16 +0000207 TypeSet InputSet(*this);
208
Craig Topperfef745c2015-11-24 08:20:42 +0000209 TypeVec.clear();
210 std::set_intersection(InputSet.TypeVec.begin(), InputSet.TypeVec.end(),
211 InVT.TypeVec.begin(), InVT.TypeVec.end(),
212 std::back_inserter(TypeVec));
Jim Grosbach65586fe2010-12-21 16:16:00 +0000213
Craig Topperfef745c2015-11-24 08:20:42 +0000214 // If the intersection is the same size as the original set then we're done.
215 if (TypeVec.size() == InputSet.TypeVec.size())
216 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000217
Chris Lattnercabe0372010-03-15 06:00:16 +0000218 // If we removed all of our types, we have a type contradiction.
219 if (!TypeVec.empty())
Craig Topperfef745c2015-11-24 08:20:42 +0000220 return true;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000221
Chris Lattnercabe0372010-03-15 06:00:16 +0000222 // FIXME: Really want an SMLoc here!
223 TP.error("Type inference contradiction found, merging '" +
224 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000225 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000226}
227
228/// EnforceInteger - Remove all non-integer types from this set.
229bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000230 if (TP.hasError())
231 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000232 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000233 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000234 return FillWithPossibleTypes(TP, isInteger, "integer");
Craig Topperd2177de2015-11-23 07:19:08 +0000235
Chris Lattnercabe0372010-03-15 06:00:16 +0000236 if (!hasFloatingPointTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000237 return false;
238
239 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000240
Chris Lattnercabe0372010-03-15 06:00:16 +0000241 // Filter out all the fp types.
David Majnemerc7004902016-08-12 04:32:37 +0000242 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isInteger))),
Craig Topperde2d7592015-11-23 07:19:10 +0000243 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.
David Majnemerc7004902016-08-12 04:32:37 +0000267 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isFloatingPoint))),
Craig Topperde2d7592015-11-23 07:19:10 +0000268 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000269
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000270 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000271 TP.error("Type inference contradiction found, '" +
272 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000273 return false;
274 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000275 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000276}
277
278/// EnforceScalar - Remove all vector types from this.
279bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000280 if (TP.hasError())
281 return false;
282
Chris Lattnercabe0372010-03-15 06:00:16 +0000283 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000284 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000285 return FillWithPossibleTypes(TP, isScalar, "scalar");
286
Chris Lattnercabe0372010-03-15 06:00:16 +0000287 if (!hasVectorTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000288 return false;
289
290 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000291
Chris Lattnercabe0372010-03-15 06:00:16 +0000292 // Filter out all the vector types.
David Majnemerc7004902016-08-12 04:32:37 +0000293 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isScalar))),
Craig Topperde2d7592015-11-23 07:19:10 +0000294 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000295
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000296 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000297 TP.error("Type inference contradiction found, '" +
298 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000299 return false;
300 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000301 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000302}
303
304/// EnforceVector - Remove all vector types from this.
305bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000306 if (TP.hasError())
307 return false;
308
Chris Lattner6d765eb2010-03-19 17:41:26 +0000309 // If we know nothing, then get the full set.
310 if (TypeVec.empty())
311 return FillWithPossibleTypes(TP, isVector, "vector");
312
Chris Lattnercabe0372010-03-15 06:00:16 +0000313 TypeSet InputSet(*this);
314 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000315
Chris Lattnercabe0372010-03-15 06:00:16 +0000316 // Filter out all the scalar types.
David Majnemerc7004902016-08-12 04:32:37 +0000317 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isVector))),
Craig Topperde2d7592015-11-23 07:19:10 +0000318 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000319
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000320 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000321 TP.error("Type inference contradiction found, '" +
322 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000323 return false;
324 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000325 return MadeChange;
326}
327
328
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000329
Craig Topper74169dc2014-01-28 04:49:01 +0000330/// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000331/// this should be based on the element type. Update this and other based on
Craig Topper74169dc2014-01-28 04:49:01 +0000332/// this information.
Chris Lattnercabe0372010-03-15 06:00:16 +0000333bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000334 if (TP.hasError())
335 return false;
336
Chris Lattnercabe0372010-03-15 06:00:16 +0000337 // Both operands must be integer or FP, but we don't care which.
338 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000339
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000340 if (isCompletelyUnknown())
341 MadeChange = FillWithPossibleTypes(TP);
342
343 if (Other.isCompletelyUnknown())
344 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000345
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000346 // If one side is known to be integer or known to be FP but the other side has
347 // no information, get at least the type integrality info in there.
348 if (!hasFloatingPointTypes())
349 MadeChange |= Other.EnforceInteger(TP);
350 else if (!hasIntegerTypes())
351 MadeChange |= Other.EnforceFloatingPoint(TP);
352 if (!Other.hasFloatingPointTypes())
353 MadeChange |= EnforceInteger(TP);
354 else if (!Other.hasIntegerTypes())
355 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000356
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000357 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
358 "Should have a type list now");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000359
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000360 // If one contains vectors but the other doesn't pull vectors out.
361 if (!hasVectorTypes())
362 MadeChange |= Other.EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000363 else if (!hasScalarTypes())
364 MadeChange |= Other.EnforceVector(TP);
Craig Topper6dbcb942014-01-25 05:17:38 +0000365 if (!Other.hasVectorTypes())
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000366 MadeChange |= EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000367 else if (!Other.hasScalarTypes())
368 MadeChange |= EnforceVector(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000369
Craig Topper74169dc2014-01-28 04:49:01 +0000370 // This code does not currently handle nodes which have multiple types,
371 // where some types are integer, and some are fp. Assert that this is not
372 // the case.
373 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
374 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
375 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
376
377 if (TP.hasError())
378 return false;
379
Craig Topper7bbd37b2015-03-10 03:25:07 +0000380 // Okay, find the smallest type from current set and remove anything the
381 // same or smaller from the other set. We need to ensure that the scalar
382 // type size is smaller than the scalar size of the smallest type. For
383 // vectors, we also need to make sure that the total size is no larger than
384 // the size of the smallest type.
Craig Topper5712d462015-11-24 08:20:47 +0000385 {
386 TypeSet InputSet(Other);
Craig Topper1282df52015-12-03 05:57:37 +0000387 MVT Smallest = *std::min_element(TypeVec.begin(), TypeVec.end(),
388 [](MVT A, MVT B) {
389 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
390 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
391 A.getSizeInBits() < B.getSizeInBits());
392 });
393
David Majnemerc7004902016-08-12 04:32:37 +0000394 auto I = remove_if(Other.TypeVec, [Smallest](MVT OtherVT) {
395 // Don't compare vector and non-vector types.
396 if (OtherVT.isVector() != Smallest.isVector())
397 return false;
398 // The getSizeInBits() check here is only needed for vectors, but is
399 // a subset of the scalar check for scalars so no need to qualify.
400 return OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
401 OtherVT.getSizeInBits() < Smallest.getSizeInBits();
402 });
Craig Topper5712d462015-11-24 08:20:47 +0000403 MadeChange |= I != Other.TypeVec.end(); // If we're about to remove types.
404 Other.TypeVec.erase(I, Other.TypeVec.end());
Craig Topper74169dc2014-01-28 04:49:01 +0000405
Craig Topper5712d462015-11-24 08:20:47 +0000406 if (Other.TypeVec.empty()) {
407 TP.error("Type inference contradiction found, '" + InputSet.getName() +
408 "' has nothing larger than '" + getName() +"'!");
409 return false;
410 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000411 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000412
Craig Topper7bbd37b2015-03-10 03:25:07 +0000413 // Okay, find the largest type from the other set and remove anything the
414 // same or smaller from the current set. We need to ensure that the scalar
415 // type size is larger than the scalar size of the largest type. For
416 // vectors, we also need to make sure that the total size is no smaller than
417 // the size of the largest type.
Craig Topper5712d462015-11-24 08:20:47 +0000418 {
419 TypeSet InputSet(*this);
Craig Topper1282df52015-12-03 05:57:37 +0000420 MVT Largest = *std::max_element(Other.TypeVec.begin(), Other.TypeVec.end(),
421 [](MVT A, MVT B) {
422 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
423 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
424 A.getSizeInBits() < B.getSizeInBits());
425 });
David Majnemerc7004902016-08-12 04:32:37 +0000426 auto I = remove_if(TypeVec, [Largest](MVT OtherVT) {
427 // Don't compare vector and non-vector types.
428 if (OtherVT.isVector() != Largest.isVector())
429 return false;
430 return OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
431 OtherVT.getSizeInBits() > Largest.getSizeInBits();
432 });
Craig Topper5712d462015-11-24 08:20:47 +0000433 MadeChange |= I != TypeVec.end(); // If we're about to remove types.
434 TypeVec.erase(I, TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000435
Craig Topper5712d462015-11-24 08:20:47 +0000436 if (TypeVec.empty()) {
437 TP.error("Type inference contradiction found, '" + InputSet.getName() +
438 "' has nothing smaller than '" + Other.getName() +"'!");
439 return false;
440 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000441 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000442
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000443 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000444}
445
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000446/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000447/// whose element is specified by VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000448bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
449 TreePattern &TP) {
450 bool MadeChange = false;
451
452 MadeChange |= EnforceVector(TP);
453
454 TypeSet InputSet(*this);
455
456 // Filter out all the types which don't have the right element type.
David Majnemerc7004902016-08-12 04:32:37 +0000457 auto I = remove_if(TypeVec, [VT](MVT VVT) {
458 return VVT.getVectorElementType().SimpleTy != VT;
459 });
Craig Topper5712d462015-11-24 08:20:47 +0000460 MadeChange |= I != TypeVec.end();
461 TypeVec.erase(I, TypeVec.end());
Craig Topper0be34582015-03-05 07:11:34 +0000462
463 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
464 TP.error("Type inference contradiction found, forcing '" +
Craig Topper5712d462015-11-24 08:20:47 +0000465 InputSet.getName() + "' to have a vector element of type " +
466 getEnumName(VT));
Craig Topper0be34582015-03-05 07:11:34 +0000467 return false;
468 }
469
470 return MadeChange;
471}
472
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000473/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Craig Topper0be34582015-03-05 07:11:34 +0000474/// whose element is specified by VTOperand.
Chris Lattner57ebf632010-03-24 00:01:16 +0000475bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000476 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000477 if (TP.hasError())
478 return false;
479
Chris Lattner57ebf632010-03-24 00:01:16 +0000480 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000481 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000482 MadeChange |= EnforceVector(TP);
483 MadeChange |= VTOperand.EnforceScalar(TP);
484
485 // If we know the vector type, it forces the scalar to agree.
486 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000487 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000488 IVT = IVT.getVectorElementType();
Craig Topperdbfcc102015-11-24 08:20:44 +0000489 return MadeChange || VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000490 }
491
492 // If the scalar type is known, filter out vector types whose element types
493 // disagree.
494 if (!VTOperand.isConcrete())
495 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000496
Chris Lattner57ebf632010-03-24 00:01:16 +0000497 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000498
Craig Topper16f1cbd2015-11-24 08:20:45 +0000499 MadeChange |= EnforceVectorEltTypeIs(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000500
Chris Lattnercabe0372010-03-15 06:00:16 +0000501 return MadeChange;
502}
503
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000504/// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
David Greene127fd1d2011-01-24 20:53:18 +0000505/// vector type specified by VTOperand.
506bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
507 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000508 if (TP.hasError())
509 return false;
510
David Greene127fd1d2011-01-24 20:53:18 +0000511 // "This" must be a vector and "VTOperand" must be a vector.
512 bool MadeChange = false;
513 MadeChange |= EnforceVector(TP);
514 MadeChange |= VTOperand.EnforceVector(TP);
515
Craig Topper6e1faaf2014-01-25 17:40:33 +0000516 // If one side is known to be integer or known to be FP but the other side has
517 // no information, get at least the type integrality info in there.
518 if (!hasFloatingPointTypes())
519 MadeChange |= VTOperand.EnforceInteger(TP);
520 else if (!hasIntegerTypes())
521 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
522 if (!VTOperand.hasFloatingPointTypes())
523 MadeChange |= EnforceInteger(TP);
524 else if (!VTOperand.hasIntegerTypes())
525 MadeChange |= EnforceFloatingPoint(TP);
526
527 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
528 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000529
530 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000531 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000532 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000533 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000534 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000535 IVT = IVT.getVectorElementType();
536
Craig Topper95198f42013-09-25 06:37:18 +0000537 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000538 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000539
540 // Only keep types that have less elements than VTOperand.
541 TypeSet InputSet(VTOperand);
542
David Majnemerc7004902016-08-12 04:32:37 +0000543 auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) {
544 return VVT.getVectorNumElements() >= NumElems;
545 });
Craig Topper5712d462015-11-24 08:20:47 +0000546 MadeChange |= I != VTOperand.TypeVec.end();
547 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
548
Craig Topper6e1faaf2014-01-25 17:40:33 +0000549 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
550 TP.error("Type inference contradiction found, forcing '" +
551 InputSet.getName() + "' to have less vector elements than '" +
552 getName() + "'");
553 return false;
554 }
David Greene127fd1d2011-01-24 20:53:18 +0000555 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000556 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000557 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000558 IVT = IVT.getVectorElementType();
559
Craig Topper95198f42013-09-25 06:37:18 +0000560 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000561 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000562
563 // Only keep types that have more elements than 'this'.
564 TypeSet InputSet(*this);
565
David Majnemerc7004902016-08-12 04:32:37 +0000566 auto I = remove_if(TypeVec, [NumElems](MVT VVT) {
567 return VVT.getVectorNumElements() <= NumElems;
568 });
Craig Topper5712d462015-11-24 08:20:47 +0000569 MadeChange |= I != TypeVec.end();
570 TypeVec.erase(I, TypeVec.end());
571
Craig Topper6e1faaf2014-01-25 17:40:33 +0000572 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
573 TP.error("Type inference contradiction found, forcing '" +
574 InputSet.getName() + "' to have more vector elements than '" +
575 VTOperand.getName() + "'");
576 return false;
577 }
David Greene127fd1d2011-01-24 20:53:18 +0000578 }
579
580 return MadeChange;
581}
582
Craig Topper13a3af12017-03-13 17:37:14 +0000583/// EnforceameNumElts - If VTOperand is a scalar, then 'this' is a scalar. If
584/// VTOperand is a vector, then 'this' must have the same number of elements.
585bool EEVT::TypeSet::EnforceSameNumElts(EEVT::TypeSet &VTOperand,
586 TreePattern &TP) {
Craig Topper0be34582015-03-05 07:11:34 +0000587 if (TP.hasError())
588 return false;
589
Craig Topper0be34582015-03-05 07:11:34 +0000590 bool MadeChange = false;
Craig Topper0be34582015-03-05 07:11:34 +0000591
Craig Topper13a3af12017-03-13 17:37:14 +0000592 if (isCompletelyUnknown())
593 MadeChange = FillWithPossibleTypes(TP);
594
595 if (VTOperand.isCompletelyUnknown())
596 MadeChange = VTOperand.FillWithPossibleTypes(TP);
597
598 // If one contains vectors but the other doesn't pull vectors out.
599 if (!hasVectorTypes())
600 MadeChange |= VTOperand.EnforceScalar(TP);
601 else if (!hasScalarTypes())
602 MadeChange |= VTOperand.EnforceVector(TP);
603 if (!VTOperand.hasVectorTypes())
604 MadeChange |= EnforceScalar(TP);
605 else if (!VTOperand.hasScalarTypes())
606 MadeChange |= EnforceVector(TP);
607
608 // If one type is a vector, make sure the other has the same element count.
609 // If this a scalar, then we are already done with the above.
Craig Topper0be34582015-03-05 07:11:34 +0000610 if (isConcrete()) {
611 MVT IVT = getConcrete();
Craig Topper13a3af12017-03-13 17:37:14 +0000612 if (IVT.isVector()) {
613 unsigned NumElems = IVT.getVectorNumElements();
Craig Topper0be34582015-03-05 07:11:34 +0000614
Craig Topper13a3af12017-03-13 17:37:14 +0000615 // Only keep types that have same elements as 'this'.
616 TypeSet InputSet(VTOperand);
Craig Topper0be34582015-03-05 07:11:34 +0000617
Craig Topper13a3af12017-03-13 17:37:14 +0000618 auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) {
619 return VVT.getVectorNumElements() != NumElems;
620 });
621 MadeChange |= I != VTOperand.TypeVec.end();
622 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
Craig Topper5712d462015-11-24 08:20:47 +0000623
Craig Topper13a3af12017-03-13 17:37:14 +0000624 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
625 TP.error("Type inference contradiction found, forcing '" +
626 InputSet.getName() + "' to have same number elements as '" +
627 getName() + "'");
628 return false;
629 }
Craig Topper0be34582015-03-05 07:11:34 +0000630 }
631 } else if (VTOperand.isConcrete()) {
632 MVT IVT = VTOperand.getConcrete();
Craig Topper13a3af12017-03-13 17:37:14 +0000633 if (IVT.isVector()) {
634 unsigned NumElems = IVT.getVectorNumElements();
Craig Topper0be34582015-03-05 07:11:34 +0000635
Craig Topper13a3af12017-03-13 17:37:14 +0000636 // Only keep types that have same elements as VTOperand.
637 TypeSet InputSet(*this);
Craig Topper0be34582015-03-05 07:11:34 +0000638
Craig Topper13a3af12017-03-13 17:37:14 +0000639 auto I = remove_if(TypeVec, [NumElems](MVT VVT) {
640 return VVT.getVectorNumElements() != NumElems;
641 });
642 MadeChange |= I != TypeVec.end();
643 TypeVec.erase(I, TypeVec.end());
Craig Topper5712d462015-11-24 08:20:47 +0000644
Craig Topper13a3af12017-03-13 17:37:14 +0000645 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
646 TP.error("Type inference contradiction found, forcing '" +
647 InputSet.getName() + "' to have same number elements than '" +
648 VTOperand.getName() + "'");
649 return false;
650 }
Craig Topper0be34582015-03-05 07:11:34 +0000651 }
652 }
653
654 return MadeChange;
655}
656
Craig Topper9a44b3f2015-11-26 07:02:18 +0000657/// EnforceSameSize - 'this' is now constrained to be same size as VTOperand.
658bool EEVT::TypeSet::EnforceSameSize(EEVT::TypeSet &VTOperand,
659 TreePattern &TP) {
660 if (TP.hasError())
661 return false;
662
663 bool MadeChange = false;
664
Craig Topperf6564c92017-02-18 22:53:38 +0000665 if (isCompletelyUnknown())
666 MadeChange = FillWithPossibleTypes(TP);
667
668 if (VTOperand.isCompletelyUnknown())
669 MadeChange = VTOperand.FillWithPossibleTypes(TP);
670
Craig Topper9a44b3f2015-11-26 07:02:18 +0000671 // If we know one of the types, it forces the other type agree.
672 if (isConcrete()) {
673 MVT IVT = getConcrete();
674 unsigned Size = IVT.getSizeInBits();
675
676 // Only keep types that have the same size as 'this'.
677 TypeSet InputSet(VTOperand);
678
David Majnemerc7004902016-08-12 04:32:37 +0000679 auto I = remove_if(VTOperand.TypeVec,
680 [&](MVT VT) { return VT.getSizeInBits() != Size; });
Craig Topper9a44b3f2015-11-26 07:02:18 +0000681 MadeChange |= I != VTOperand.TypeVec.end();
682 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
683
684 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
685 TP.error("Type inference contradiction found, forcing '" +
686 InputSet.getName() + "' to have same size as '" +
687 getName() + "'");
688 return false;
689 }
690 } else if (VTOperand.isConcrete()) {
691 MVT IVT = VTOperand.getConcrete();
692 unsigned Size = IVT.getSizeInBits();
693
694 // Only keep types that have the same size as VTOperand.
695 TypeSet InputSet(*this);
696
David Majnemerc7004902016-08-12 04:32:37 +0000697 auto I =
698 remove_if(TypeVec, [&](MVT VT) { return VT.getSizeInBits() != Size; });
Craig Topper9a44b3f2015-11-26 07:02:18 +0000699 MadeChange |= I != TypeVec.end();
700 TypeVec.erase(I, TypeVec.end());
701
702 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
703 TP.error("Type inference contradiction found, forcing '" +
704 InputSet.getName() + "' to have same size as '" +
705 VTOperand.getName() + "'");
706 return false;
707 }
708 }
709
710 return MadeChange;
711}
712
Chris Lattnercabe0372010-03-15 06:00:16 +0000713//===----------------------------------------------------------------------===//
714// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000715
Scott Michel94420742008-03-05 17:49:05 +0000716/// Dependent variable map for CodeGenDAGPattern variant generation
717typedef std::map<std::string, int> DepVarMap;
718
Chris Lattner514e2922011-04-17 21:38:24 +0000719static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000720 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000721 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000722 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000723 } else {
724 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
725 FindDepVarsOf(N->getChild(i), DepMap);
726 }
727}
Chris Lattner514e2922011-04-17 21:38:24 +0000728
729/// Find dependent variables within child patterns
730static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000731 DepVarMap depcounts;
732 FindDepVarsOf(N, depcounts);
Craig Topper306cb122015-11-22 20:46:24 +0000733 for (const std::pair<std::string, int> &Pair : depcounts) {
734 if (Pair.second > 1)
735 DepVars.insert(Pair.first);
Scott Michel94420742008-03-05 17:49:05 +0000736 }
737}
738
Daniel Dunbarba66a812010-10-08 02:07:22 +0000739#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000740/// Dump the dependent variable set:
741static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000742 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000743 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000744 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000745 DEBUG(errs() << "[ ");
Craig Topper306cb122015-11-22 20:46:24 +0000746 for (const std::string &DepVar : DepVars) {
747 DEBUG(errs() << DepVar << " ");
Scott Michel94420742008-03-05 17:49:05 +0000748 }
Chris Lattner34822f62009-08-23 04:44:11 +0000749 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000750 }
751}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000752#endif
753
Chris Lattner514e2922011-04-17 21:38:24 +0000754
755//===----------------------------------------------------------------------===//
756// TreePredicateFn Implementation
757//===----------------------------------------------------------------------===//
758
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000759/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
760TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
761 assert((getPredCode().empty() || getImmCode().empty()) &&
762 ".td file corrupt: can't have a node predicate *and* an imm predicate");
763}
764
Chris Lattner514e2922011-04-17 21:38:24 +0000765std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000766 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000767}
768
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000769std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000770 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000771}
772
Chris Lattner514e2922011-04-17 21:38:24 +0000773
774/// isAlwaysTrue - Return true if this is a noop predicate.
775bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000776 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000777}
778
779/// Return the name to use in the generated code to reference this, this is
780/// "Predicate_foo" if from a pattern fragment "foo".
781std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +0000782 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +0000783}
784
785/// getCodeToRunOnSDNode - Return the code for the function body that
786/// evaluates this predicate. The argument is expected to be in "Node",
787/// not N. This handles casting and conversion to a concrete node type as
788/// appropriate.
789std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000790 // Handle immediate predicates first.
791 std::string ImmCode = getImmCode();
792 if (!ImmCode.empty()) {
793 std::string Result =
794 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000795 return Result + ImmCode;
796 }
797
798 // Handle arbitrary node predicates.
799 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000800 std::string ClassName;
801 if (PatFragRec->getOnlyTree()->isLeaf())
802 ClassName = "SDNode";
803 else {
804 Record *Op = PatFragRec->getOnlyTree()->getOperator();
805 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
806 }
807 std::string Result;
808 if (ClassName == "SDNode")
809 Result = " SDNode *N = Node;\n";
810 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000811 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000812
813 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000814}
815
Chris Lattner8cab0212008-01-05 22:25:12 +0000816//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000817// PatternToMatch implementation
818//
819
Chris Lattner05925fe2010-03-29 01:40:38 +0000820
821/// getPatternSize - Return the 'size' of this pattern. We want to match large
822/// patterns before small ones. This is used to determine the size of a
823/// pattern.
824static unsigned getPatternSize(const TreePatternNode *P,
825 const CodeGenDAGPatterns &CGP) {
826 unsigned Size = 3; // The node itself.
827 // If the root node is a ConstantSDNode, increases its size.
828 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000829 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000830 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000831
Chris Lattner05925fe2010-03-29 01:40:38 +0000832 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000833 if (AM) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000834 Size += AM->getComplexity();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000835
Tim Northoverc807a172014-05-20 11:52:46 +0000836 // We don't want to count any children twice, so return early.
837 return Size;
838 }
839
Chris Lattner05925fe2010-03-29 01:40:38 +0000840 // If this node has some predicate function that must match, it adds to the
841 // complexity of this node.
842 if (!P->getPredicateFns().empty())
843 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000844
Chris Lattner05925fe2010-03-29 01:40:38 +0000845 // Count children in the count if they are also nodes.
846 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
847 TreePatternNode *Child = P->getChild(i);
848 if (!Child->isLeaf() && Child->getNumTypes() &&
849 Child->getType(0) != MVT::Other)
850 Size += getPatternSize(Child, CGP);
851 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000852 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000853 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
854 else if (Child->getComplexPatternInfo(CGP))
855 Size += getPatternSize(Child, CGP);
856 else if (!Child->getPredicateFns().empty())
857 ++Size;
858 }
859 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000860
Chris Lattner05925fe2010-03-29 01:40:38 +0000861 return Size;
862}
863
864/// Compute the complexity metric for the input pattern. This roughly
865/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000866int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000867getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
868 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
869}
870
871
Dan Gohman49e19e92008-08-22 00:20:26 +0000872/// getPredicateCheck - Return a single string containing all of this
873/// pattern's predicates concatenated with "&&" operators.
874///
875std::string PatternToMatch::getPredicateCheck() const {
Craig Topper8985efe2015-11-27 05:44:04 +0000876 SmallVector<Record *, 4> PredicateRecs;
Craig Topperef0578a2015-06-02 04:15:51 +0000877 for (Init *I : Predicates->getValues()) {
878 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000879 Record *Def = Pred->getDef();
880 if (!Def->isSubClassOf("Predicate")) {
881#ifndef NDEBUG
882 Def->dump();
883#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000884 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000885 }
Craig Topper8985efe2015-11-27 05:44:04 +0000886 PredicateRecs.push_back(Def);
Dan Gohman49e19e92008-08-22 00:20:26 +0000887 }
888 }
Craig Topper8985efe2015-11-27 05:44:04 +0000889 // Sort so that different orders get canonicalized to the same string.
890 std::sort(PredicateRecs.begin(), PredicateRecs.end(), LessRecord());
891
Craig Topper3522ab32015-11-28 08:23:02 +0000892 SmallString<128> PredicateCheck;
Craig Topper8985efe2015-11-27 05:44:04 +0000893 for (Record *Pred : PredicateRecs) {
894 if (!PredicateCheck.empty())
895 PredicateCheck += " && ";
Craig Topper2b8419a2017-05-31 19:01:11 +0000896 PredicateCheck += "(";
897 PredicateCheck += Pred->getValueAsString("CondString");
898 PredicateCheck += ")";
Craig Topper8985efe2015-11-27 05:44:04 +0000899 }
Dan Gohman49e19e92008-08-22 00:20:26 +0000900
Craig Topper3522ab32015-11-28 08:23:02 +0000901 return PredicateCheck.str();
Dan Gohman49e19e92008-08-22 00:20:26 +0000902}
903
904//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000905// SDTypeConstraint implementation
906//
907
908SDTypeConstraint::SDTypeConstraint(Record *R) {
909 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000910
Chris Lattner8cab0212008-01-05 22:25:12 +0000911 if (R->isSubClassOf("SDTCisVT")) {
912 ConstraintType = SDTCisVT;
913 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000914 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000915 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000916
Chris Lattner8cab0212008-01-05 22:25:12 +0000917 } else if (R->isSubClassOf("SDTCisPtrTy")) {
918 ConstraintType = SDTCisPtrTy;
919 } else if (R->isSubClassOf("SDTCisInt")) {
920 ConstraintType = SDTCisInt;
921 } else if (R->isSubClassOf("SDTCisFP")) {
922 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000923 } else if (R->isSubClassOf("SDTCisVec")) {
924 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000925 } else if (R->isSubClassOf("SDTCisSameAs")) {
926 ConstraintType = SDTCisSameAs;
927 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
928 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
929 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000930 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000931 R->getValueAsInt("OtherOperandNum");
932 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
933 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000934 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000935 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000936 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
937 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000938 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000939 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
940 ConstraintType = SDTCisSubVecOfVec;
941 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
942 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000943 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
944 ConstraintType = SDTCVecEltisVT;
945 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
946 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
947 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
948 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
949 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
950 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
951 "as SDTCVecEltisVT");
952 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
953 ConstraintType = SDTCisSameNumEltsAs;
954 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
955 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +0000956 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
957 ConstraintType = SDTCisSameSizeAs;
958 x.SDTCisSameSizeAs_Info.OtherOperandNum =
959 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000960 } else {
James Y Knighte452e272015-05-11 22:17:13 +0000961 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +0000962 }
963}
964
965/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000966/// N, and the result number in ResNo.
967static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
968 const SDNodeInfo &NodeInfo,
969 unsigned &ResNo) {
970 unsigned NumResults = NodeInfo.getNumResults();
971 if (OpNo < NumResults) {
972 ResNo = OpNo;
973 return N;
974 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000975
Chris Lattner2db7aba2010-03-19 21:56:21 +0000976 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000977
Chris Lattner2db7aba2010-03-19 21:56:21 +0000978 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +0000979 std::string S;
980 raw_string_ostream OS(S);
981 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000982 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +0000983 N->print(OS);
984 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +0000985 }
986
Chris Lattner2db7aba2010-03-19 21:56:21 +0000987 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000988}
989
990/// ApplyTypeConstraint - Given a node in a pattern, apply this type
991/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000992/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000993bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
994 const SDNodeInfo &NodeInfo,
995 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000996 if (TP.hasError())
997 return false;
998
Chris Lattner2db7aba2010-03-19 21:56:21 +0000999 unsigned ResNo = 0; // The result number being referenced.
1000 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001001
Chris Lattner8cab0212008-01-05 22:25:12 +00001002 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001003 case SDTCisVT:
1004 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001005 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001006 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001007 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001008 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001009 case SDTCisInt:
1010 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +00001011 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001012 case SDTCisFP:
1013 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +00001014 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001015 case SDTCisVec:
1016 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +00001017 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001018 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001019 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001020 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001021 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001022 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1023 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001024 }
1025 case SDTCisVTSmallerThanOp: {
1026 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1027 // have an integer type that is smaller than the VT.
1028 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001029 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001030 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001031 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001032 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001033 return false;
1034 }
Owen Anderson9f944592009-08-11 20:47:22 +00001035 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +00001036 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001037
Chris Lattner38c99662010-03-24 00:06:46 +00001038 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001039
Chris Lattner2db7aba2010-03-19 21:56:21 +00001040 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001041 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001042 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1043 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001044
Chris Lattner38c99662010-03-24 00:06:46 +00001045 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001046 }
1047 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001048 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001049 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001050 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1051 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +00001052 return NodeToApply->getExtType(ResNo).
1053 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001054 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001055 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001056 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001057 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001058 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1059 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001060
Chris Lattner57ebf632010-03-24 00:01:16 +00001061 // Filter vector types out of VecOperand that don't have the right element
1062 // type.
1063 return VecOperand->getExtType(VResNo).
1064 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +00001065 }
David Greene127fd1d2011-01-24 20:53:18 +00001066 case SDTCisSubVecOfVec: {
1067 unsigned VResNo = 0;
1068 TreePatternNode *BigVecOperand =
1069 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1070 VResNo);
1071
1072 // Filter vector types out of BigVecOperand that don't have the
1073 // right subvector type.
1074 return BigVecOperand->getExtType(VResNo).
1075 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1076 }
Craig Topper0be34582015-03-05 07:11:34 +00001077 case SDTCVecEltisVT: {
1078 return NodeToApply->getExtType(ResNo).
1079 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1080 }
1081 case SDTCisSameNumEltsAs: {
1082 unsigned OResNo = 0;
1083 TreePatternNode *OtherNode =
1084 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1085 N, NodeInfo, OResNo);
1086 return OtherNode->getExtType(OResNo).
Craig Topper13a3af12017-03-13 17:37:14 +00001087 EnforceSameNumElts(NodeToApply->getExtType(ResNo), TP);
Craig Topper0be34582015-03-05 07:11:34 +00001088 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001089 case SDTCisSameSizeAs: {
1090 unsigned OResNo = 0;
1091 TreePatternNode *OtherNode =
1092 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1093 N, NodeInfo, OResNo);
1094 return OtherNode->getExtType(OResNo).
1095 EnforceSameSize(NodeToApply->getExtType(ResNo), TP);
1096 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001097 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001098 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001099}
1100
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001101// Update the node type to match an instruction operand or result as specified
1102// in the ins or outs lists on the instruction definition. Return true if the
1103// type was actually changed.
1104bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1105 Record *Operand,
1106 TreePattern &TP) {
1107 // The 'unknown' operand indicates that types should be inferred from the
1108 // context.
1109 if (Operand->isSubClassOf("unknown_class"))
1110 return false;
1111
1112 // The Operand class specifies a type directly.
1113 if (Operand->isSubClassOf("Operand"))
1114 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1115 TP);
1116
1117 // PointerLikeRegClass has a type that is determined at runtime.
1118 if (Operand->isSubClassOf("PointerLikeRegClass"))
1119 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1120
1121 // Both RegisterClass and RegisterOperand operands derive their types from a
1122 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001123 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001124 if (Operand->isSubClassOf("RegisterClass"))
1125 RC = Operand;
1126 else if (Operand->isSubClassOf("RegisterOperand"))
1127 RC = Operand->getValueAsDef("RegClass");
1128
1129 assert(RC && "Unknown operand type");
1130 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1131 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1132}
1133
1134
Chris Lattner8cab0212008-01-05 22:25:12 +00001135//===----------------------------------------------------------------------===//
1136// SDNodeInfo implementation
1137//
1138SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1139 EnumName = R->getValueAsString("Opcode");
1140 SDClassName = R->getValueAsString("SDClass");
1141 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1142 NumResults = TypeProfile->getValueAsInt("NumResults");
1143 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001144
Chris Lattner8cab0212008-01-05 22:25:12 +00001145 // Parse the properties.
1146 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001147 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1148 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001149 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001150 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001151 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001152 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001153 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001154 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001155 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001156 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001157 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001158 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001159 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001160 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001161 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001162 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001163 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001164 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001165 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001166 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001167 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001168 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001169 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001170 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001171 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001172 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001173 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001174 }
1175 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001176
1177
Chris Lattner8cab0212008-01-05 22:25:12 +00001178 // Parse the type constraints.
1179 std::vector<Record*> ConstraintList =
1180 TypeProfile->getValueAsListOfDefs("Constraints");
1181 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1182}
1183
Chris Lattner99e53b32010-02-28 00:22:30 +00001184/// getKnownType - If the type constraints on this node imply a fixed type
1185/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001186/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001187MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001188 unsigned NumResults = getNumResults();
1189 assert(NumResults <= 1 &&
1190 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001191 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001192
Craig Topper306cb122015-11-22 20:46:24 +00001193 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001194 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001195 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001196 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001197
Craig Topper306cb122015-11-22 20:46:24 +00001198 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001199 default: break;
1200 case SDTypeConstraint::SDTCisVT:
Craig Topper306cb122015-11-22 20:46:24 +00001201 return Constraint.x.SDTCisVT_Info.VT;
Chris Lattner99e53b32010-02-28 00:22:30 +00001202 case SDTypeConstraint::SDTCisPtrTy:
1203 return MVT::iPTR;
1204 }
1205 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001206 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001207}
1208
Chris Lattner8cab0212008-01-05 22:25:12 +00001209//===----------------------------------------------------------------------===//
1210// TreePatternNode implementation
1211//
1212
1213TreePatternNode::~TreePatternNode() {
1214#if 0 // FIXME: implement refcounted tree nodes!
1215 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1216 delete getChild(i);
1217#endif
1218}
1219
Chris Lattnerf1447252010-03-19 21:37:09 +00001220static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1221 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001222 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001223 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001224
Chris Lattner2109cb42010-03-22 20:56:36 +00001225 if (Operator->isSubClassOf("Intrinsic"))
1226 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001227
Chris Lattnerf1447252010-03-19 21:37:09 +00001228 if (Operator->isSubClassOf("SDNode"))
1229 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001230
Chris Lattnerf1447252010-03-19 21:37:09 +00001231 if (Operator->isSubClassOf("PatFrag")) {
1232 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1233 // the forward reference case where one pattern fragment references another
1234 // before it is processed.
1235 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1236 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001237
Chris Lattnerf1447252010-03-19 21:37:09 +00001238 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001239 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001240 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001241 if (Tree)
1242 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1243 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001244 assert(Op && "Invalid Fragment");
1245 return GetNumNodeResults(Op, CDP);
1246 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001247
Chris Lattnerf1447252010-03-19 21:37:09 +00001248 if (Operator->isSubClassOf("Instruction")) {
1249 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001250
Craig Topper3a8eb892015-03-20 05:09:06 +00001251 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1252
1253 // Subtract any defaulted outputs.
1254 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1255 Record *OperandNode = InstInfo.Operands[i].Rec;
1256
1257 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1258 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1259 --NumDefsToAdd;
1260 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001261
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001262 // Add on one implicit def if it has a resolvable type.
1263 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1264 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001265 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001266 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001267
Chris Lattnerf1447252010-03-19 21:37:09 +00001268 if (Operator->isSubClassOf("SDNodeXForm"))
1269 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001270
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001271 if (Operator->isSubClassOf("ValueType"))
1272 return 1; // A type-cast of one result.
1273
Tim Northoverc807a172014-05-20 11:52:46 +00001274 if (Operator->isSubClassOf("ComplexPattern"))
1275 return 1;
1276
Matthias Braun8c209aa2017-01-28 02:02:38 +00001277 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001278 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001279}
1280
1281void TreePatternNode::print(raw_ostream &OS) const {
1282 if (isLeaf())
1283 OS << *getLeafValue();
1284 else
1285 OS << '(' << getOperator()->getName();
1286
1287 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1288 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001289
1290 if (!isLeaf()) {
1291 if (getNumChildren() != 0) {
1292 OS << " ";
1293 getChild(0)->print(OS);
1294 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1295 OS << ", ";
1296 getChild(i)->print(OS);
1297 }
1298 }
1299 OS << ")";
1300 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001301
Craig Topper306cb122015-11-22 20:46:24 +00001302 for (const TreePredicateFn &Pred : PredicateFns)
1303 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001304 if (TransformFn)
1305 OS << "<<X:" << TransformFn->getName() << ">>";
1306 if (!getName().empty())
1307 OS << ":$" << getName();
1308
1309}
1310void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001311 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001312}
1313
Scott Michel94420742008-03-05 17:49:05 +00001314/// isIsomorphicTo - Return true if this node is recursively
1315/// isomorphic to the specified node. For this comparison, the node's
1316/// entire state is considered. The assigned name is ignored, since
1317/// nodes with differing names are considered isomorphic. However, if
1318/// the assigned name is present in the dependent variable set, then
1319/// the assigned name is considered significant and the node is
1320/// isomorphic if the names match.
1321bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1322 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001323 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001324 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001325 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001326 getTransformFn() != N->getTransformFn())
1327 return false;
1328
1329 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001330 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1331 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001332 return ((DI->getDef() == NDI->getDef())
1333 && (DepVars.find(getName()) == DepVars.end()
1334 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001335 }
1336 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001337 return getLeafValue() == N->getLeafValue();
1338 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001339
Chris Lattner8cab0212008-01-05 22:25:12 +00001340 if (N->getOperator() != getOperator() ||
1341 N->getNumChildren() != getNumChildren()) return false;
1342 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001343 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001344 return false;
1345 return true;
1346}
1347
1348/// clone - Make a copy of this tree and all of its children.
1349///
1350TreePatternNode *TreePatternNode::clone() const {
1351 TreePatternNode *New;
1352 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001353 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001354 } else {
1355 std::vector<TreePatternNode*> CChildren;
1356 CChildren.reserve(Children.size());
1357 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1358 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001359 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001360 }
1361 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001362 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001363 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001364 New->setTransformFn(getTransformFn());
1365 return New;
1366}
1367
Chris Lattner53c39ba2010-02-14 22:22:58 +00001368/// RemoveAllTypes - Recursively strip all the types of this tree.
1369void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001370 // Reset to unknown type.
1371 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001372 if (isLeaf()) return;
1373 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1374 getChild(i)->RemoveAllTypes();
1375}
1376
1377
Chris Lattner8cab0212008-01-05 22:25:12 +00001378/// SubstituteFormalArguments - Replace the formal arguments in this tree
1379/// with actual values specified by ArgMap.
1380void TreePatternNode::
1381SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1382 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001383
Chris Lattner8cab0212008-01-05 22:25:12 +00001384 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1385 TreePatternNode *Child = getChild(i);
1386 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001387 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001388 // Note that, when substituting into an output pattern, Val might be an
1389 // UnsetInit.
1390 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1391 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001392 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001393 TreePatternNode *NewChild = ArgMap[Child->getName()];
1394 assert(NewChild && "Couldn't find formal argument!");
1395 assert((Child->getPredicateFns().empty() ||
1396 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1397 "Non-empty child predicate clobbered!");
1398 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001399 }
1400 } else {
1401 getChild(i)->SubstituteFormalArguments(ArgMap);
1402 }
1403 }
1404}
1405
1406
1407/// InlinePatternFragments - If this pattern refers to any pattern
1408/// fragments, inline them into place, giving us a pattern without any
1409/// PatFrag references.
1410TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001411 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001412 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001413
1414 if (isLeaf())
1415 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001416 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001417
Chris Lattner8cab0212008-01-05 22:25:12 +00001418 if (!Op->isSubClassOf("PatFrag")) {
1419 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001420 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1421 TreePatternNode *Child = getChild(i);
1422 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1423
1424 assert((Child->getPredicateFns().empty() ||
1425 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1426 "Non-empty child predicate clobbered!");
1427
1428 setChild(i, NewChild);
1429 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001430 return this;
1431 }
1432
1433 // Otherwise, we found a reference to a fragment. First, look up its
1434 // TreePattern record.
1435 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001436
Chris Lattner8cab0212008-01-05 22:25:12 +00001437 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001438 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001439 TP.error("'" + Op->getName() + "' fragment requires " +
1440 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001441 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001442 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001443
1444 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1445
Chris Lattner514e2922011-04-17 21:38:24 +00001446 TreePredicateFn PredFn(Frag);
1447 if (!PredFn.isAlwaysTrue())
1448 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001449
Chris Lattner8cab0212008-01-05 22:25:12 +00001450 // Resolve formal arguments to their actual value.
1451 if (Frag->getNumArgs()) {
1452 // Compute the map of formal to actual arguments.
1453 std::map<std::string, TreePatternNode*> ArgMap;
1454 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1455 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001456
Chris Lattner8cab0212008-01-05 22:25:12 +00001457 FragTree->SubstituteFormalArguments(ArgMap);
1458 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001459
Chris Lattner8cab0212008-01-05 22:25:12 +00001460 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001461 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1462 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001463
1464 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001465 for (const TreePredicateFn &Pred : getPredicateFns())
1466 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001467
Chris Lattner8cab0212008-01-05 22:25:12 +00001468 // Get a new copy of this fragment to stitch into here.
1469 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001470
Chris Lattner2e253b42008-06-30 03:02:03 +00001471 // The fragment we inlined could have recursive inlining that is needed. See
1472 // if there are any pattern fragments in it and inline them as needed.
1473 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001474}
1475
1476/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001477/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001478/// references from the register file information, for example.
1479///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001480/// When Unnamed is set, return the type of a DAG operand with no name, such as
1481/// the F8RC register class argument in:
1482///
1483/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1484///
1485/// When Unnamed is false, return the type of a named DAG operand such as the
1486/// GPR:$src operand above.
1487///
Chris Lattnerf1447252010-03-19 21:37:09 +00001488static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001489 bool NotRegisters,
1490 bool Unnamed,
1491 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001492 // Check to see if this is a register operand.
1493 if (R->isSubClassOf("RegisterOperand")) {
1494 assert(ResNo == 0 && "Regoperand ref only has one result!");
1495 if (NotRegisters)
1496 return EEVT::TypeSet(); // Unknown.
1497 Record *RegClass = R->getValueAsDef("RegClass");
1498 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1499 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1500 }
1501
Chris Lattnercabe0372010-03-15 06:00:16 +00001502 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001503 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001504 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001505 // An unnamed register class represents itself as an i32 immediate, for
1506 // example on a COPY_TO_REGCLASS instruction.
1507 if (Unnamed)
1508 return EEVT::TypeSet(MVT::i32, TP);
1509
1510 // In a named operand, the register class provides the possible set of
1511 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001512 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001513 return EEVT::TypeSet(); // Unknown.
1514 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1515 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001516 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001517
Chris Lattner6070ee22010-03-23 23:50:31 +00001518 if (R->isSubClassOf("PatFrag")) {
1519 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001520 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001521 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001522 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001523
Chris Lattner6070ee22010-03-23 23:50:31 +00001524 if (R->isSubClassOf("Register")) {
1525 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001526 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001527 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001528 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001529 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001530 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001531
1532 if (R->isSubClassOf("SubRegIndex")) {
1533 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001534 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001535 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001536
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001537 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001538 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001539 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1540 //
1541 // (sext_inreg GPR:$src, i16)
1542 // ~~~
1543 if (Unnamed)
1544 return EEVT::TypeSet(MVT::Other, TP);
1545 // With a name, the ValueType simply provides the type of the named
1546 // variable.
1547 //
1548 // (sext_inreg i32:$src, i16)
1549 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001550 if (NotRegisters)
1551 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001552 return EEVT::TypeSet(getValueType(R), TP);
1553 }
1554
1555 if (R->isSubClassOf("CondCode")) {
1556 assert(ResNo == 0 && "This node only has one result!");
1557 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001558 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001559 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001560
Chris Lattner6070ee22010-03-23 23:50:31 +00001561 if (R->isSubClassOf("ComplexPattern")) {
1562 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001563 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001564 return EEVT::TypeSet(); // Unknown.
1565 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1566 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001567 }
1568 if (R->isSubClassOf("PointerLikeRegClass")) {
1569 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001570 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001571 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001572
Chris Lattner6070ee22010-03-23 23:50:31 +00001573 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1574 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001575 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001576 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001577 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001578
Tim Northoverc807a172014-05-20 11:52:46 +00001579 if (R->isSubClassOf("Operand"))
1580 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1581
Chris Lattner8cab0212008-01-05 22:25:12 +00001582 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001583 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001584}
1585
Chris Lattner89c65662008-01-06 05:36:50 +00001586
1587/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1588/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1589const CodeGenIntrinsic *TreePatternNode::
1590getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1591 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1592 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1593 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001594 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001595
Sean Silva88eb8dd2012-10-10 20:24:47 +00001596 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001597 return &CDP.getIntrinsicInfo(IID);
1598}
1599
Chris Lattner53c39ba2010-02-14 22:22:58 +00001600/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1601/// return the ComplexPattern information, otherwise return null.
1602const ComplexPattern *
1603TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001604 Record *Rec;
1605 if (isLeaf()) {
1606 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1607 if (!DI)
1608 return nullptr;
1609 Rec = DI->getDef();
1610 } else
1611 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001612
Tim Northoverc807a172014-05-20 11:52:46 +00001613 if (!Rec->isSubClassOf("ComplexPattern"))
1614 return nullptr;
1615 return &CGP.getComplexPattern(Rec);
1616}
1617
1618unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1619 // A ComplexPattern specifically declares how many results it fills in.
1620 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1621 return CP->getNumOperands();
1622
1623 // If MIOperandInfo is specified, that gives the count.
1624 if (isLeaf()) {
1625 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1626 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1627 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1628 if (MIOps->getNumArgs())
1629 return MIOps->getNumArgs();
1630 }
1631 }
1632
1633 // Otherwise there is just one result.
1634 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001635}
1636
1637/// NodeHasProperty - Return true if this node has the specified property.
1638bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001639 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001640 if (isLeaf()) {
1641 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1642 return CP->hasProperty(Property);
1643 return false;
1644 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001645
Chris Lattner53c39ba2010-02-14 22:22:58 +00001646 Record *Operator = getOperator();
1647 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001648
Chris Lattner53c39ba2010-02-14 22:22:58 +00001649 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1650}
1651
1652
1653
1654
1655/// TreeHasProperty - Return true if any node in this tree has the specified
1656/// property.
1657bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001658 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001659 if (NodeHasProperty(Property, CGP))
1660 return true;
1661 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1662 if (getChild(i)->TreeHasProperty(Property, CGP))
1663 return true;
1664 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001665}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001666
Evan Cheng49bad4c2008-06-16 20:29:38 +00001667/// isCommutativeIntrinsic - Return true if the node corresponds to a
1668/// commutative intrinsic.
1669bool
1670TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1671 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1672 return Int->isCommutative;
1673 return false;
1674}
1675
Matt Arsenaulteb492162014-11-02 23:46:51 +00001676static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1677 if (!N->isLeaf())
1678 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001679
Matt Arsenaulteb492162014-11-02 23:46:51 +00001680 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1681 if (DI && DI->getDef()->isSubClassOf(Class))
1682 return true;
1683
1684 return false;
1685}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001686
1687static void emitTooManyOperandsError(TreePattern &TP,
1688 StringRef InstName,
1689 unsigned Expected,
1690 unsigned Actual) {
1691 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1692 " operands but expected only " + Twine(Expected) + "!");
1693}
1694
1695static void emitTooFewOperandsError(TreePattern &TP,
1696 StringRef InstName,
1697 unsigned Actual) {
1698 TP.error("Instruction '" + InstName +
1699 "' expects more than the provided " + Twine(Actual) + " operands!");
1700}
1701
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001702/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001703/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001704/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001705bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001706 if (TP.hasError())
1707 return false;
1708
Chris Lattnerab3242f2008-01-06 01:10:31 +00001709 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001710 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001711 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001712 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001713 bool MadeChange = false;
1714 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1715 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001716 NotRegisters,
1717 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001718 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001719 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001720
Sean Silvafb509ed2012-10-10 20:24:43 +00001721 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001722 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001723
Chris Lattnerf1447252010-03-19 21:37:09 +00001724 // Int inits are always integers. :)
1725 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001726
Chris Lattnerf1447252010-03-19 21:37:09 +00001727 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001728 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001729
Chris Lattnerf1447252010-03-19 21:37:09 +00001730 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001731 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1732 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001733
Craig Topper95198f42013-09-25 06:37:18 +00001734 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001735 // Make sure that the value is representable for this type.
1736 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001737
Richard Smith228e6d42012-08-24 23:29:28 +00001738 // Check that the value doesn't use more bits than we have. It must either
1739 // be a sign- or zero-extended equivalent of the original.
1740 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1741 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001742 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001743
Richard Smith228e6d42012-08-24 23:29:28 +00001744 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001745 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001746 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001747 }
1748 return false;
1749 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001750
Chris Lattner8cab0212008-01-05 22:25:12 +00001751 // special handling for set, which isn't really an SDNode.
1752 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001753 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1754 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001755 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001756
Chris Lattnerf1447252010-03-19 21:37:09 +00001757 TreePatternNode *SetVal = getChild(NC-1);
1758 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1759
Elena Demikhovsky09954792015-03-01 08:23:41 +00001760 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001761 TreePatternNode *Child = getChild(i);
1762 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001763
Chris Lattner8cab0212008-01-05 22:25:12 +00001764 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001765 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1766 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001767 }
1768 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001769 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001770
Chris Lattner5c2182e2010-03-27 02:53:27 +00001771 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001772 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1773
Chris Lattner8cab0212008-01-05 22:25:12 +00001774 bool MadeChange = false;
1775 for (unsigned i = 0; i < getNumChildren(); ++i)
1776 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001777 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001778 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001779
Chris Lattneree820ac2010-02-23 05:51:07 +00001780 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001781 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001782
Chris Lattner8cab0212008-01-05 22:25:12 +00001783 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001784 unsigned NumRetVTs = Int->IS.RetVTs.size();
1785 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001786
Bill Wendling91821472008-11-13 09:08:33 +00001787 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001788 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001789
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001790 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001791 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001792 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001793 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001794 return false;
1795 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001796
1797 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001798 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001799
Chris Lattnerf1447252010-03-19 21:37:09 +00001800 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1801 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001802
Chris Lattnerf1447252010-03-19 21:37:09 +00001803 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1804 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1805 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001806 }
1807 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001808 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001809
Chris Lattneree820ac2010-02-23 05:51:07 +00001810 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001811 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001812
Chris Lattner135091b2010-03-28 08:48:47 +00001813 // Check that the number of operands is sane. Negative operands -> varargs.
1814 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001815 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001816 TP.error(getOperator()->getName() + " node requires exactly " +
1817 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001818 return false;
1819 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001820
Chris Lattner8cab0212008-01-05 22:25:12 +00001821 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1822 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1823 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001824 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001825 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001826
Chris Lattneree820ac2010-02-23 05:51:07 +00001827 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001828 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001829 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001830 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001831
Chris Lattnerd44966f2010-03-27 19:15:02 +00001832 bool MadeChange = false;
1833
1834 // Apply the result types to the node, these come from the things in the
1835 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001836 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1837 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001838 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1839 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001840
Chris Lattnerd44966f2010-03-27 19:15:02 +00001841 // If the instruction has implicit defs, we apply the first one as a result.
1842 // FIXME: This sucks, it should apply all implicit defs.
1843 if (!InstInfo.ImplicitDefs.empty()) {
1844 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001845
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001846 // FIXME: Generalize to multiple possible types and multiple possible
1847 // ImplicitDefs.
1848 MVT::SimpleValueType VT =
1849 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001850
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001851 if (VT != MVT::Other)
1852 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001853 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001854
Chris Lattnercabe0372010-03-15 06:00:16 +00001855 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1856 // be the same.
1857 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001858 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1859 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1860 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001861 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1862 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1863 // variadic.
1864
1865 unsigned NChild = getNumChildren();
1866 if (NChild < 3) {
1867 TP.error("REG_SEQUENCE requires at least 3 operands!");
1868 return false;
1869 }
1870
1871 if (NChild % 2 == 0) {
1872 TP.error("REG_SEQUENCE requires an odd number of operands!");
1873 return false;
1874 }
1875
1876 if (!isOperandClass(getChild(0), "RegisterClass")) {
1877 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1878 return false;
1879 }
1880
1881 for (unsigned I = 1; I < NChild; I += 2) {
1882 TreePatternNode *SubIdxChild = getChild(I + 1);
1883 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1884 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1885 itostr(I + 1) + "!");
1886 return false;
1887 }
1888 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001889 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001890
1891 unsigned ChildNo = 0;
1892 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1893 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001894
Chris Lattner8cab0212008-01-05 22:25:12 +00001895 // If the instruction expects a predicate or optional def operand, we
1896 // codegen this by setting the operand to it's default value if it has a
1897 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001898 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001899 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1900 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001901
Chris Lattner8cab0212008-01-05 22:25:12 +00001902 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001903 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001904 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001905 return false;
1906 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001907
Chris Lattner8cab0212008-01-05 22:25:12 +00001908 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001909 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001910
1911 // If the operand has sub-operands, they may be provided by distinct
1912 // child patterns, so attempt to match each sub-operand separately.
1913 if (OperandNode->isSubClassOf("Operand")) {
1914 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1915 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1916 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001917 // a single ComplexPattern-related Operand.
1918
1919 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001920 // Match first sub-operand against the child we already have.
1921 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1922 MadeChange |=
1923 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1924
1925 // And the remaining sub-operands against subsequent children.
1926 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1927 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001928 emitTooFewOperandsError(TP, getOperator()->getName(),
1929 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001930 return false;
1931 }
1932 Child = getChild(ChildNo++);
1933
1934 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1935 MadeChange |=
1936 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1937 }
1938 continue;
1939 }
1940 }
1941 }
1942
1943 // If we didn't match by pieces above, attempt to match the whole
1944 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001945 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001946 }
Christopher Lamba7312392008-03-11 09:33:47 +00001947
Matt Arsenaulteb492162014-11-02 23:46:51 +00001948 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001949 emitTooManyOperandsError(TP, getOperator()->getName(),
1950 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001951 return false;
1952 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001953
Ulrich Weigande618abd2013-03-19 19:51:09 +00001954 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1955 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001956 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001957 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001958
Tim Northoverc807a172014-05-20 11:52:46 +00001959 if (getOperator()->isSubClassOf("ComplexPattern")) {
1960 bool MadeChange = false;
1961
1962 for (unsigned i = 0; i < getNumChildren(); ++i)
1963 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1964
1965 return MadeChange;
1966 }
1967
Chris Lattneree820ac2010-02-23 05:51:07 +00001968 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001969
Chris Lattneree820ac2010-02-23 05:51:07 +00001970 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001971 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001972 TP.error("Node transform '" + getOperator()->getName() +
1973 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001974 return false;
1975 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001976
Chris Lattnercabe0372010-03-15 06:00:16 +00001977 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1978
Jim Grosbach65586fe2010-12-21 16:16:00 +00001979
Chris Lattneree820ac2010-02-23 05:51:07 +00001980 // If either the output or input of the xform does not have exact
1981 // type info. We assume they must be the same. Otherwise, it is perfectly
1982 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001983#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001984 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001985 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1986 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001987 return MadeChange;
1988 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001989#endif
1990 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001991}
1992
1993/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1994/// RHS of a commutative operation, not the on LHS.
1995static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1996 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1997 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001998 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001999 return true;
2000 return false;
2001}
2002
2003
2004/// canPatternMatch - If it is impossible for this pattern to match on this
2005/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002006/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002007/// that can never possibly work), and to prevent the pattern permuter from
2008/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002009bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002010 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002011 if (isLeaf()) return true;
2012
2013 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2014 if (!getChild(i)->canPatternMatch(Reason, CDP))
2015 return false;
2016
2017 // If this is an intrinsic, handle cases that would make it not match. For
2018 // example, if an operand is required to be an immediate.
2019 if (getOperator()->isSubClassOf("Intrinsic")) {
2020 // TODO:
2021 return true;
2022 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002023
Tim Northoverc807a172014-05-20 11:52:46 +00002024 if (getOperator()->isSubClassOf("ComplexPattern"))
2025 return true;
2026
Chris Lattner8cab0212008-01-05 22:25:12 +00002027 // If this node is a commutative operator, check that the LHS isn't an
2028 // immediate.
2029 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002030 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2031 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002032 // Scan all of the operands of the node and make sure that only the last one
2033 // is a constant node, unless the RHS also is.
2034 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002035 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002036 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002037 if (OnlyOnRHSOfCommutative(getChild(i))) {
2038 Reason="Immediate value must be on the RHS of commutative operators!";
2039 return false;
2040 }
2041 }
2042 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002043
Chris Lattner8cab0212008-01-05 22:25:12 +00002044 return true;
2045}
2046
2047//===----------------------------------------------------------------------===//
2048// TreePattern implementation
2049//
2050
David Greeneaf8ee2c2011-07-29 22:43:06 +00002051TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002052 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2053 isInputPattern(isInput), HasError(false) {
Craig Topperef0578a2015-06-02 04:15:51 +00002054 for (Init *I : RawPat->getValues())
2055 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002056}
2057
David Greeneaf8ee2c2011-07-29 22:43:06 +00002058TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002059 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2060 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002061 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002062}
2063
David Blaikiecf195302014-11-17 22:55:41 +00002064TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002065 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2066 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00002067 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002068}
2069
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002070void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002071 if (HasError)
2072 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002073 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002074 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2075 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002076}
2077
Chris Lattnercabe0372010-03-15 06:00:16 +00002078void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002079 for (TreePatternNode *Tree : Trees)
2080 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002081}
2082
2083void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2084 if (!N->getName().empty())
2085 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002086
Chris Lattnercabe0372010-03-15 06:00:16 +00002087 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2088 ComputeNamedNodes(N->getChild(i));
2089}
2090
David Blaikiecf195302014-11-17 22:55:41 +00002091
2092TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002093 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002094 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002095
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002096 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002097 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002098 /// (foo GPR, imm) -> (foo GPR, (imm))
2099 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002100 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002101 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002102 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002103 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002104
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002105 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002106 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002107 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002108 if (OpName.empty())
2109 error("'node' argument requires a name to match with operand list");
2110 Args.push_back(OpName);
2111 }
2112
2113 Res->setName(OpName);
2114 return Res;
2115 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002116
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002117 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002118 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002119 if (OpName.empty())
2120 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002121 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002122 Args.push_back(OpName);
2123 Res->setName(OpName);
2124 return Res;
2125 }
2126
Sean Silvafb509ed2012-10-10 20:24:43 +00002127 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002128 if (!OpName.empty())
2129 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002130 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002131 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002132
Sean Silvafb509ed2012-10-10 20:24:43 +00002133 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002134 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002135 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002136 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002137 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002138 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002139 }
2140
Sean Silvafb509ed2012-10-10 20:24:43 +00002141 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002142 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002143 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002144 error("Pattern has unexpected init kind!");
2145 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002146 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002147 if (!OpDef) error("Pattern has unexpected operator type!");
2148 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002149
Chris Lattner8cab0212008-01-05 22:25:12 +00002150 if (Operator->isSubClassOf("ValueType")) {
2151 // If the operator is a ValueType, then this must be "type cast" of a leaf
2152 // node.
2153 if (Dag->getNumArgs() != 1)
2154 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002155
Matthias Braunbb053162016-12-05 06:00:46 +00002156 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2157 Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002158
Chris Lattner8cab0212008-01-05 22:25:12 +00002159 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002160 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2161 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002162
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002163 if (!OpName.empty())
2164 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002165 return New;
2166 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002167
Chris Lattner8cab0212008-01-05 22:25:12 +00002168 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002169 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002170 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002171 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002172 !Operator->isSubClassOf("SDNodeXForm") &&
2173 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002174 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002175 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002176 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002177 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002178
Chris Lattner8cab0212008-01-05 22:25:12 +00002179 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002180 if (isInputPattern) {
2181 if (Operator->isSubClassOf("Instruction") ||
2182 Operator->isSubClassOf("SDNodeXForm"))
2183 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2184 } else {
2185 if (Operator->isSubClassOf("Intrinsic"))
2186 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002187
Chris Lattner2e9eae12010-03-28 06:57:56 +00002188 if (Operator->isSubClassOf("SDNode") &&
2189 Operator->getName() != "imm" &&
2190 Operator->getName() != "fpimm" &&
2191 Operator->getName() != "tglobaltlsaddr" &&
2192 Operator->getName() != "tconstpool" &&
2193 Operator->getName() != "tjumptable" &&
2194 Operator->getName() != "tframeindex" &&
2195 Operator->getName() != "texternalsym" &&
2196 Operator->getName() != "tblockaddress" &&
2197 Operator->getName() != "tglobaladdr" &&
2198 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002199 Operator->getName() != "vt" &&
2200 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002201 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2202 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002203
Chris Lattner8cab0212008-01-05 22:25:12 +00002204 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002205
2206 // Parse all the operands.
2207 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002208 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002209
Chris Lattner8cab0212008-01-05 22:25:12 +00002210 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002211 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002212 // convert the intrinsic name to a number.
2213 if (Operator->isSubClassOf("Intrinsic")) {
2214 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2215 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2216
2217 // If this intrinsic returns void, it must have side-effects and thus a
2218 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002219 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002220 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002221 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002222 // Has side-effects, requires chain.
2223 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002224 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002225 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002226
David Greenee32ebf22011-07-29 19:07:07 +00002227 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002228 Children.insert(Children.begin(), IIDNode);
2229 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002230
Tim Northoverc807a172014-05-20 11:52:46 +00002231 if (Operator->isSubClassOf("ComplexPattern")) {
2232 for (unsigned i = 0; i < Children.size(); ++i) {
2233 TreePatternNode *Child = Children[i];
2234
2235 if (Child->getName().empty())
2236 error("All arguments to a ComplexPattern must be named");
2237
2238 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2239 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2240 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2241 auto OperandId = std::make_pair(Operator, i);
2242 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2243 if (PrevOp != ComplexPatternOperands.end()) {
2244 if (PrevOp->getValue() != OperandId)
2245 error("All ComplexPattern operands must appear consistently: "
2246 "in the same order in just one ComplexPattern instance.");
2247 } else
2248 ComplexPatternOperands[Child->getName()] = OperandId;
2249 }
2250 }
2251
Chris Lattnerf1447252010-03-19 21:37:09 +00002252 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002253 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002254 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002255
Matthias Braun7cf3b112016-12-05 06:00:41 +00002256 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002257 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002258 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002259 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002260 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002261}
2262
Chris Lattnera787c9e2010-03-28 08:38:32 +00002263/// SimplifyTree - See if we can simplify this tree to eliminate something that
2264/// will never match in favor of something obvious that will. This is here
2265/// strictly as a convenience to target authors because it allows them to write
2266/// more type generic things and have useless type casts fold away.
2267///
2268/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002269static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002270 if (N->isLeaf())
2271 return false;
2272
2273 // If we have a bitconvert with a resolved type and if the source and
2274 // destination types are the same, then the bitconvert is useless, remove it.
2275 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002276 N->getExtType(0).isConcrete() &&
2277 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2278 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002279 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002280 SimplifyTree(N);
2281 return true;
2282 }
2283
2284 // Walk all children.
2285 bool MadeChange = false;
2286 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002287 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002288 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002289 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002290 }
2291 return MadeChange;
2292}
2293
2294
2295
Chris Lattner8cab0212008-01-05 22:25:12 +00002296/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002297/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002298/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002299bool TreePattern::
2300InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2301 if (NamedNodes.empty())
2302 ComputeNamedNodes();
2303
Chris Lattner8cab0212008-01-05 22:25:12 +00002304 bool MadeChange = true;
2305 while (MadeChange) {
2306 MadeChange = false;
Craig Topper306cb122015-11-22 20:46:24 +00002307 for (TreePatternNode *Tree : Trees) {
2308 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2309 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002310 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002311
2312 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002313 for (auto &Entry : NamedNodes) {
2314 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002315
Chris Lattnercabe0372010-03-15 06:00:16 +00002316 // If we have input named node types, propagate their types to the named
2317 // values here.
2318 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002319 if (!InNamedTypes->count(Entry.getKey())) {
2320 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002321 "' in output pattern but not input pattern");
2322 return true;
2323 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002324
2325 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002326 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002327
2328 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002329 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002330 // If this node is a register class, and it is the root of the pattern
2331 // then we're mapping something onto an input register. We allow
2332 // changing the type of the input register in this case. This allows
2333 // us to match things like:
2334 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002335 if (Node == Trees[0] && Node->isLeaf()) {
2336 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002337 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2338 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002339 continue;
2340 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002341
Craig Topper306cb122015-11-22 20:46:24 +00002342 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002343 InNodes[0]->getNumTypes() == 1 &&
2344 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002345 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2346 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002347 }
2348 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002349
Chris Lattnercabe0372010-03-15 06:00:16 +00002350 // If there are multiple nodes with the same name, they must all have the
2351 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002352 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002353 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002354 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002355 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002356 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002357
Chris Lattnerf1447252010-03-19 21:37:09 +00002358 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2359 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002360 }
2361 }
2362 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002363 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002364
Chris Lattner8cab0212008-01-05 22:25:12 +00002365 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002366 for (const TreePatternNode *Tree : Trees)
2367 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
Chris Lattner8cab0212008-01-05 22:25:12 +00002368 return !HasUnresolvedTypes;
2369}
2370
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002371void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002372 OS << getRecord()->getName();
2373 if (!Args.empty()) {
2374 OS << "(" << Args[0];
2375 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2376 OS << ", " << Args[i];
2377 OS << ")";
2378 }
2379 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002380
Chris Lattner8cab0212008-01-05 22:25:12 +00002381 if (Trees.size() > 1)
2382 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002383 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002384 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002385 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002386 OS << "\n";
2387 }
2388
2389 if (Trees.size() > 1)
2390 OS << "]\n";
2391}
2392
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002393void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002394
2395//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002396// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002397//
2398
Jim Grosbach65586fe2010-12-21 16:16:00 +00002399CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002400 Records(R), Target(R) {
2401
Justin Bogner92a8c612016-07-15 16:31:37 +00002402 Intrinsics = CodeGenIntrinsicTable(Records, false);
2403 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002404 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002405 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002406 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002407 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002408 ParseDefaultOperands();
2409 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002410 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002411 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002412
Chris Lattner8cab0212008-01-05 22:25:12 +00002413 // Generate variants. For example, commutative patterns can match
2414 // multiple ways. Add them to PatternsToMatch as well.
2415 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002416
2417 // Infer instruction flags. For example, we can detect loads,
2418 // stores, and side effects in many cases by examining an
2419 // instruction's pattern.
2420 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002421
2422 // Verify that instruction flags match the patterns.
2423 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002424}
2425
Chris Lattnerab3242f2008-01-06 01:10:31 +00002426Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002427 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002428 if (!N || !N->isSubClassOf("SDNode"))
2429 PrintFatalError("Error getting SDNode '" + Name + "'!");
2430
Chris Lattner8cab0212008-01-05 22:25:12 +00002431 return N;
2432}
2433
2434// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002435void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002436 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2437 while (!Nodes.empty()) {
2438 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2439 Nodes.pop_back();
2440 }
2441
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002442 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002443 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2444 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2445 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2446}
2447
2448/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2449/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002450void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002451 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2452 while (!Xforms.empty()) {
2453 Record *XFormNode = Xforms.back();
2454 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002455 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002456 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002457
2458 Xforms.pop_back();
2459 }
2460}
2461
Chris Lattnerab3242f2008-01-06 01:10:31 +00002462void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002463 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2464 while (!AMs.empty()) {
2465 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2466 AMs.pop_back();
2467 }
2468}
2469
2470
2471/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2472/// file, building up the PatternFragments map. After we've collected them all,
2473/// inline fragments together as necessary, so that there are no references left
2474/// inside a pattern fragment to a pattern fragment.
2475///
Hal Finkel2756dc12014-02-28 00:26:56 +00002476void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002477 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002478
Chris Lattnere7170df2008-01-05 22:43:57 +00002479 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002480 for (Record *Frag : Fragments) {
2481 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002482 continue;
2483
Craig Topper306cb122015-11-22 20:46:24 +00002484 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002485 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002486 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2487 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002488 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002489
Chris Lattnere7170df2008-01-05 22:43:57 +00002490 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002491 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002492 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002493
Chris Lattnere7170df2008-01-05 22:43:57 +00002494 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002495 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002496
Chris Lattner8cab0212008-01-05 22:25:12 +00002497 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002498 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002499 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002500 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002501 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002502 if (!OpsOp ||
2503 (OpsOp->getDef()->getName() != "ops" &&
2504 OpsOp->getDef()->getName() != "outs" &&
2505 OpsOp->getDef()->getName() != "ins"))
2506 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002507
2508 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002509 Args.clear();
2510 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002511 if (!isa<DefInit>(OpsList->getArg(j)) ||
2512 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002513 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00002514 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00002515 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00002516 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2517 if (!OperandsSet.count(ArgNameStr))
2518 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00002519 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00002520 OperandsSet.erase(ArgNameStr);
2521 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00002522 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002523
Chris Lattnere7170df2008-01-05 22:43:57 +00002524 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002525 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002526 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002527
Chris Lattnere7170df2008-01-05 22:43:57 +00002528 // If there is a code init for this fragment, keep track of the fact that
2529 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002530 TreePredicateFn PredFn(P);
2531 if (!PredFn.isAlwaysTrue())
2532 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002533
Chris Lattner8cab0212008-01-05 22:25:12 +00002534 // If there is a node transformation corresponding to this, keep track of
2535 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002536 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002537 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2538 P->getOnlyTree()->setTransformFn(Transform);
2539 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002540
Chris Lattner8cab0212008-01-05 22:25:12 +00002541 // Now that we've parsed all of the tree fragments, do a closure on them so
2542 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002543 for (Record *Frag : Fragments) {
2544 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002545 continue;
2546
Craig Topper306cb122015-11-22 20:46:24 +00002547 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002548 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002549
Chris Lattner8cab0212008-01-05 22:25:12 +00002550 // Infer as many types as possible. Don't worry about it if we don't infer
2551 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002552 ThePat.InferAllTypes();
2553 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002554
Chris Lattner8cab0212008-01-05 22:25:12 +00002555 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002556 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002557 }
2558}
2559
Chris Lattnerab3242f2008-01-06 01:10:31 +00002560void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002561 std::vector<Record*> DefaultOps;
2562 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002563
2564 // Find some SDNode.
2565 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002566 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002567
Tom Stellardb7246a72012-09-06 14:15:52 +00002568 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2569 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002570
Tom Stellardb7246a72012-09-06 14:15:52 +00002571 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2572 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00002573 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00002574 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2575 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2576 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00002577 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002578
Tom Stellardb7246a72012-09-06 14:15:52 +00002579 // Create a TreePattern to parse this.
2580 TreePattern P(DefaultOps[i], DI, false, *this);
2581 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002582
Tom Stellardb7246a72012-09-06 14:15:52 +00002583 // Copy the operands over into a DAGDefaultOperand.
2584 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002585
Tom Stellardb7246a72012-09-06 14:15:52 +00002586 TreePatternNode *T = P.getTree(0);
2587 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2588 TreePatternNode *TPN = T->getChild(op);
2589 while (TPN->ApplyTypeConstraints(P, false))
2590 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002591
Tom Stellardb7246a72012-09-06 14:15:52 +00002592 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002593 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2594 DefaultOps[i]->getName() +
2595 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002596 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002597 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002598 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002599
2600 // Insert it into the DefaultOperands map so we can find it later.
2601 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002602 }
2603}
2604
2605/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2606/// instruction input. Return true if this is a real use.
2607static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002608 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002609 // No name -> not interesting.
2610 if (Pat->getName().empty()) {
2611 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002612 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002613 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2614 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002615 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002616 }
2617 return false;
2618 }
2619
2620 Record *Rec;
2621 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002622 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002623 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2624 Rec = DI->getDef();
2625 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002626 Rec = Pat->getOperator();
2627 }
2628
2629 // SRCVALUE nodes are ignored.
2630 if (Rec->getName() == "srcvalue")
2631 return false;
2632
2633 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2634 if (!Slot) {
2635 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002636 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002637 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002638 Record *SlotRec;
2639 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002640 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002641 } else {
2642 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2643 SlotRec = Slot->getOperator();
2644 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002645
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002646 // Ensure that the inputs agree if we've already seen this input.
2647 if (Rec != SlotRec)
2648 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002649 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002650 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002651 return true;
2652}
2653
2654/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2655/// part of "I", the instruction), computing the set of inputs and outputs of
2656/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002657void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002658FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2659 std::map<std::string, TreePatternNode*> &InstInputs,
2660 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002661 std::vector<Record*> &InstImpResults) {
2662 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002663 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002664 if (!isUse && Pat->getTransformFn())
2665 I->error("Cannot specify a transform function for a non-input value!");
2666 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002667 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002668
Chris Lattnerf2d70992010-02-17 06:53:36 +00002669 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002670 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2671 TreePatternNode *Dest = Pat->getChild(i);
2672 if (!Dest->isLeaf())
2673 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002674
Sean Silvafb509ed2012-10-10 20:24:43 +00002675 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002676 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2677 I->error("implicitly defined value should be a register!");
2678 InstImpResults.push_back(Val->getDef());
2679 }
2680 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002681 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002682
Chris Lattnerf2d70992010-02-17 06:53:36 +00002683 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002684 // If this is not a set, verify that the children nodes are not void typed,
2685 // and recurse.
2686 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002687 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002688 I->error("Cannot have void nodes inside of patterns!");
2689 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002690 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002691 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002692
Chris Lattner8cab0212008-01-05 22:25:12 +00002693 // If this is a non-leaf node with no children, treat it basically as if
2694 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002695 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002696
Chris Lattner8cab0212008-01-05 22:25:12 +00002697 if (!isUse && Pat->getTransformFn())
2698 I->error("Cannot specify a transform function for a non-input value!");
2699 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002700 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002701
Chris Lattner8cab0212008-01-05 22:25:12 +00002702 // Otherwise, this is a set, validate and collect instruction results.
2703 if (Pat->getNumChildren() == 0)
2704 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002705
Chris Lattner8cab0212008-01-05 22:25:12 +00002706 if (Pat->getTransformFn())
2707 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002708
Chris Lattner8cab0212008-01-05 22:25:12 +00002709 // Check the set destinations.
2710 unsigned NumDests = Pat->getNumChildren()-1;
2711 for (unsigned i = 0; i != NumDests; ++i) {
2712 TreePatternNode *Dest = Pat->getChild(i);
2713 if (!Dest->isLeaf())
2714 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002715
Sean Silvafb509ed2012-10-10 20:24:43 +00002716 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002717 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002718 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002719 continue;
2720 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002721
2722 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002723 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002724 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002725 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002726 if (Dest->getName().empty())
2727 I->error("set destination must have a name!");
2728 if (InstResults.count(Dest->getName()))
2729 I->error("cannot set '" + Dest->getName() +"' multiple times");
2730 InstResults[Dest->getName()] = Dest;
2731 } else if (Val->getDef()->isSubClassOf("Register")) {
2732 InstImpResults.push_back(Val->getDef());
2733 } else {
2734 I->error("set destination should be a register!");
2735 }
2736 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002737
Chris Lattner8cab0212008-01-05 22:25:12 +00002738 // Verify and collect info from the computation.
2739 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002740 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002741}
2742
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002743//===----------------------------------------------------------------------===//
2744// Instruction Analysis
2745//===----------------------------------------------------------------------===//
2746
2747class InstAnalyzer {
2748 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002749public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002750 bool hasSideEffects;
2751 bool mayStore;
2752 bool mayLoad;
2753 bool isBitcast;
2754 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002755
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002756 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2757 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2758 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002759
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002760 void Analyze(const TreePattern *Pat) {
2761 // Assume only the first tree is the pattern. The others are clobber nodes.
2762 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002763 }
2764
Craig Topper2a053a92017-06-20 16:34:37 +00002765 void Analyze(const PatternToMatch &Pat) {
2766 AnalyzeNode(Pat.getSrcPattern());
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002767 }
2768
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002769private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002770 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002771 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002772 return false;
2773
2774 if (N->getNumChildren() != 2)
2775 return false;
2776
2777 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002778 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002779 return false;
2780
2781 const TreePatternNode *N1 = N->getChild(1);
2782 if (N1->isLeaf())
2783 return false;
2784 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2785 return false;
2786
2787 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2788 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2789 return false;
2790 return OpInfo.getEnumName() == "ISD::BITCAST";
2791 }
2792
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002793public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002794 void AnalyzeNode(const TreePatternNode *N) {
2795 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002796 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002797 Record *LeafRec = DI->getDef();
2798 // Handle ComplexPattern leaves.
2799 if (LeafRec->isSubClassOf("ComplexPattern")) {
2800 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2801 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2802 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002803 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002804 }
2805 }
2806 return;
2807 }
2808
2809 // Analyze children.
2810 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2811 AnalyzeNode(N->getChild(i));
2812
2813 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002814 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002815 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002816 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002817 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002818
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002819 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002820 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2821 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2822 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2823 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002824
2825 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2826 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002827 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002828 mayLoad = true;// These may load memory.
2829
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002830 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002831 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2832
Matt Arsenault868af922017-04-28 21:01:46 +00002833 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
2834 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002835 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002836 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002837 }
2838 }
2839
2840};
2841
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002842static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002843 const InstAnalyzer &PatInfo,
2844 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002845 bool Error = false;
2846
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002847 // Remember where InstInfo got its flags.
2848 if (InstInfo.hasUndefFlags())
2849 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002850
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002851 // Check explicitly set flags for consistency.
2852 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2853 !InstInfo.hasSideEffects_Unset) {
2854 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2855 // the pattern has no side effects. That could be useful for div/rem
2856 // instructions that may trap.
2857 if (!InstInfo.hasSideEffects) {
2858 Error = true;
2859 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2860 Twine(InstInfo.hasSideEffects));
2861 }
2862 }
2863
2864 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2865 Error = true;
2866 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2867 Twine(InstInfo.mayStore));
2868 }
2869
2870 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2871 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00002872 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002873 if (!InstInfo.mayLoad) {
2874 Error = true;
2875 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2876 Twine(InstInfo.mayLoad));
2877 }
2878 }
2879
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002880 // Transfer inferred flags.
2881 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2882 InstInfo.mayStore |= PatInfo.mayStore;
2883 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002884
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002885 // These flags are silently added without any verification.
2886 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002887
2888 // Don't infer isVariadic. This flag means something different on SDNodes and
2889 // instructions. For example, a CALL SDNode is variadic because it has the
2890 // call arguments as operands, but a CALL instruction is not variadic - it
2891 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002892
2893 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002894}
2895
Jim Grosbach514410b2012-07-17 00:47:06 +00002896/// hasNullFragReference - Return true if the DAG has any reference to the
2897/// null_frag operator.
2898static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002899 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002900 if (!OpDef) return false;
2901 Record *Operator = OpDef->getDef();
2902
2903 // If this is the null fragment, return true.
2904 if (Operator->getName() == "null_frag") return true;
2905 // If any of the arguments reference the null fragment, return true.
2906 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002907 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002908 if (Arg && hasNullFragReference(Arg))
2909 return true;
2910 }
2911
2912 return false;
2913}
2914
2915/// hasNullFragReference - Return true if any DAG in the list references
2916/// the null_frag operator.
2917static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00002918 for (Init *I : LI->getValues()) {
2919 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00002920 assert(DI && "non-dag in an instruction Pattern list?!");
2921 if (hasNullFragReference(DI))
2922 return true;
2923 }
2924 return false;
2925}
2926
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002927/// Get all the instructions in a tree.
2928static void
2929getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2930 if (Tree->isLeaf())
2931 return;
2932 if (Tree->getOperator()->isSubClassOf("Instruction"))
2933 Instrs.push_back(Tree->getOperator());
2934 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2935 getInstructionsInTree(Tree->getChild(i), Instrs);
2936}
2937
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002938/// Check the class of a pattern leaf node against the instruction operand it
2939/// represents.
2940static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2941 Record *Leaf) {
2942 if (OI.Rec == Leaf)
2943 return true;
2944
2945 // Allow direct value types to be used in instruction set patterns.
2946 // The type will be checked later.
2947 if (Leaf->isSubClassOf("ValueType"))
2948 return true;
2949
2950 // Patterns can also be ComplexPattern instances.
2951 if (Leaf->isSubClassOf("ComplexPattern"))
2952 return true;
2953
2954 return false;
2955}
2956
Ahmed Bougacha14107512013-10-28 18:07:21 +00002957const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2958 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002959
Craig Topper0d1fb902015-03-10 03:25:04 +00002960 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002961
Craig Topper0d1fb902015-03-10 03:25:04 +00002962 // Parse the instruction.
2963 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2964 // Inline pattern fragments into it.
2965 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002966
Craig Topper0d1fb902015-03-10 03:25:04 +00002967 // Infer as many types as possible. If we cannot infer all of them, we can
2968 // never do anything with this instruction pattern: report it to the user.
2969 if (!I->InferAllTypes())
2970 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002971
Craig Topper0d1fb902015-03-10 03:25:04 +00002972 // InstInputs - Keep track of all of the inputs of the instruction, along
2973 // with the record they are declared as.
2974 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002975
Craig Topper0d1fb902015-03-10 03:25:04 +00002976 // InstResults - Keep track of all the virtual registers that are 'set'
2977 // in the instruction, including what reg class they are.
2978 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002979
Craig Topper0d1fb902015-03-10 03:25:04 +00002980 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002981
Craig Topper0d1fb902015-03-10 03:25:04 +00002982 // Verify that the top-level forms in the instruction are of void type, and
2983 // fill in the InstResults map.
2984 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2985 TreePatternNode *Pat = I->getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00002986 if (Pat->getNumTypes() != 0) {
2987 std::string Types;
2988 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
2989 if (k > 0)
2990 Types += ", ";
2991 Types += Pat->getExtType(k).getName();
2992 }
Craig Topper0d1fb902015-03-10 03:25:04 +00002993 I->error("Top-level forms in instruction pattern should have"
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00002994 " void types, has types " + Types);
2995 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002996
Craig Topper0d1fb902015-03-10 03:25:04 +00002997 // Find inputs and outputs, and verify the structure of the uses/defs.
2998 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2999 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003000 }
3001
Craig Topper0d1fb902015-03-10 03:25:04 +00003002 // Now that we have inputs and outputs of the pattern, inspect the operands
3003 // list for the instruction. This determines the order that operands are
3004 // added to the machine instruction the node corresponds to.
3005 unsigned NumResults = InstResults.size();
3006
3007 // Parse the operands list from the (ops) list, validating it.
3008 assert(I->getArgList().empty() && "Args list should still be empty here!");
3009
3010 // Check that all of the results occur first in the list.
3011 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00003012 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003013 for (unsigned i = 0; i != NumResults; ++i) {
3014 if (i == CGI.Operands.size())
3015 I->error("'" + InstResults.begin()->first +
3016 "' set but does not appear in operand list!");
3017 const std::string &OpName = CGI.Operands[i].Name;
3018
3019 // Check that it exists in InstResults.
3020 TreePatternNode *RNode = InstResults[OpName];
3021 if (!RNode)
3022 I->error("Operand $" + OpName + " does not exist in operand list!");
3023
Craig Topper3a8eb892015-03-20 05:09:06 +00003024 ResNodes.push_back(RNode);
3025
Craig Topper0d1fb902015-03-10 03:25:04 +00003026 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3027 if (!R)
3028 I->error("Operand $" + OpName + " should be a set destination: all "
3029 "outputs must occur before inputs in operand list!");
3030
3031 if (!checkOperandClass(CGI.Operands[i], R))
3032 I->error("Operand $" + OpName + " class mismatch!");
3033
3034 // Remember the return type.
3035 Results.push_back(CGI.Operands[i].Rec);
3036
3037 // Okay, this one checks out.
3038 InstResults.erase(OpName);
3039 }
3040
3041 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3042 // the copy while we're checking the inputs.
3043 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3044
3045 std::vector<TreePatternNode*> ResultNodeOperands;
3046 std::vector<Record*> Operands;
3047 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3048 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3049 const std::string &OpName = Op.Name;
3050 if (OpName.empty())
3051 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3052
3053 if (!InstInputsCheck.count(OpName)) {
3054 // If this is an operand with a DefaultOps set filled in, we can ignore
3055 // this. When we codegen it, we will do so as always executed.
3056 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3057 // Does it have a non-empty DefaultOps field? If so, ignore this
3058 // operand.
3059 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3060 continue;
3061 }
3062 I->error("Operand $" + OpName +
3063 " does not appear in the instruction pattern");
3064 }
3065 TreePatternNode *InVal = InstInputsCheck[OpName];
3066 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3067
3068 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3069 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3070 if (!checkOperandClass(Op, InRec))
3071 I->error("Operand $" + OpName + "'s register class disagrees"
3072 " between the operand and pattern");
3073 }
3074 Operands.push_back(Op.Rec);
3075
3076 // Construct the result for the dest-pattern operand list.
3077 TreePatternNode *OpNode = InVal->clone();
3078
3079 // No predicate is useful on the result.
3080 OpNode->clearPredicateFns();
3081
3082 // Promote the xform function to be an explicit node if set.
3083 if (Record *Xform = OpNode->getTransformFn()) {
3084 OpNode->setTransformFn(nullptr);
3085 std::vector<TreePatternNode*> Children;
3086 Children.push_back(OpNode);
3087 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3088 }
3089
3090 ResultNodeOperands.push_back(OpNode);
3091 }
3092
3093 if (!InstInputsCheck.empty())
3094 I->error("Input operand $" + InstInputsCheck.begin()->first +
3095 " occurs in pattern but not in operands list!");
3096
3097 TreePatternNode *ResultPattern =
3098 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3099 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003100 // Copy fully inferred output node types to instruction result pattern.
3101 for (unsigned i = 0; i != NumResults; ++i) {
3102 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3103 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3104 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003105
3106 // Create and insert the instruction.
3107 // FIXME: InstImpResults should not be part of DAGInstruction.
3108 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3109 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3110
3111 // Use a temporary tree pattern to infer all types and make sure that the
3112 // constructed result is correct. This depends on the instruction already
3113 // being inserted into the DAGInsts map.
3114 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3115 Temp.InferAllTypes(&I->getNamedNodesMap());
3116
3117 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3118 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3119
3120 return TheInsertedInst;
3121}
3122
Ahmed Bougacha14107512013-10-28 18:07:21 +00003123/// ParseInstructions - Parse all of the instructions, inlining and resolving
3124/// any fragments involved. This populates the Instructions list with fully
3125/// resolved instructions.
3126void CodeGenDAGPatterns::ParseInstructions() {
3127 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3128
Craig Topper306cb122015-11-22 20:46:24 +00003129 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003130 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003131
Craig Topper306cb122015-11-22 20:46:24 +00003132 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3133 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003134
3135 // If there is no pattern, only collect minimal information about the
3136 // instruction for its operand list. We have to assume that there is one
3137 // result, as we have no detailed info. A pattern which references the
3138 // null_frag operator is as-if no pattern were specified. Normally this
3139 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3140 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003141 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003142 std::vector<Record*> Results;
3143 std::vector<Record*> Operands;
3144
Craig Topper306cb122015-11-22 20:46:24 +00003145 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003146
3147 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003148 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3149 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003150
Craig Topper3a8eb892015-03-20 05:09:06 +00003151 // The rest are inputs.
3152 for (unsigned j = InstInfo.Operands.NumDefs,
3153 e = InstInfo.Operands.size(); j < e; ++j)
3154 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003155 }
3156
3157 // Create and insert the instruction.
3158 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003159 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003160 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003161 continue; // no pattern.
3162 }
3163
Craig Topper306cb122015-11-22 20:46:24 +00003164 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003165 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3166
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003167 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003168 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003169 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003170
Chris Lattner8cab0212008-01-05 22:25:12 +00003171 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003172 for (auto &Entry : Instructions) {
3173 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003174 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003175 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003176
3177 // FIXME: Assume only the first tree is the pattern. The others are clobber
3178 // nodes.
3179 TreePatternNode *Pattern = I->getTree(0);
3180 TreePatternNode *SrcPattern;
3181 if (Pattern->getOperator()->getName() == "set") {
3182 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3183 } else{
3184 // Not a set (store or something?)
3185 SrcPattern = Pattern;
3186 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003187
Craig Topper306cb122015-11-22 20:46:24 +00003188 Record *Instr = Entry.first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003189 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003190 PatternToMatch(Instr,
3191 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003192 SrcPattern,
3193 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003194 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003195 Instr->getValueAsInt("AddedComplexity"),
3196 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003197 }
3198}
3199
Chris Lattnera7722b62010-02-23 06:55:24 +00003200
3201typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3202
Jim Grosbach65586fe2010-12-21 16:16:00 +00003203static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003204 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003205 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003206 if (!P->getName().empty()) {
3207 NameRecord &Rec = Names[P->getName()];
3208 // If this is the first instance of the name, remember the node.
3209 if (Rec.second++ == 0)
3210 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003211 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003212 PatternTop->error("repetition of value: $" + P->getName() +
3213 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003214 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003215
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003216 if (!P->isLeaf()) {
3217 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003218 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003219 }
3220}
3221
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003222void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003223 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003224 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003225 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003226 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3227 PrintWarning(Pattern->getRecord()->getLoc(),
3228 Twine("Pattern can never match: ") + Reason);
3229 return;
3230 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003231
Chris Lattner1e634e32010-03-01 22:29:19 +00003232 // If the source pattern's root is a complex pattern, that complex pattern
3233 // must specify the nodes it can potentially match.
3234 if (const ComplexPattern *CP =
3235 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3236 if (CP->getRootNodes().empty())
3237 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3238 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003239
3240
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003241 // Find all of the named values in the input and output, ensure they have the
3242 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003243 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003244 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3245 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003246
3247 // Scan all of the named values in the destination pattern, rejecting them if
3248 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003249 for (const auto &Entry : DstNames) {
3250 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003251 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003252 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003253 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003254
Chris Lattnera7722b62010-02-23 06:55:24 +00003255 // Scan all of the named values in the source pattern, rejecting them if the
3256 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003257 for (const auto &Entry : SrcNames)
3258 if (DstNames[Entry.first].first == nullptr &&
3259 SrcNames[Entry.first].second == 1)
3260 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003261
Craig Topper18e6b572017-06-25 17:33:49 +00003262 PatternsToMatch.push_back(std::move(PTM));
Chris Lattner0c0baa92010-02-23 06:16:51 +00003263}
3264
3265
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003266
3267void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003268 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003269 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003270
3271 // First try to infer flags from the primary instruction pattern, if any.
3272 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003273 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003274 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3275 CodeGenInstruction &InstInfo =
3276 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003277
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003278 // Get the primary instruction pattern.
3279 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3280 if (!Pattern) {
3281 if (InstInfo.hasUndefFlags())
3282 Revisit.push_back(&InstInfo);
3283 continue;
3284 }
3285 InstAnalyzer PatInfo(*this);
3286 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003287 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003288 }
3289
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003290 // Second, look for single-instruction patterns defined outside the
3291 // instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003292 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003293 // We can only infer from single-instruction patterns, otherwise we won't
3294 // know which instruction should get the flags.
3295 SmallVector<Record*, 8> PatInstrs;
3296 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3297 if (PatInstrs.size() != 1)
3298 continue;
3299
3300 // Get the single instruction.
3301 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3302
3303 // Only infer properties from the first pattern. We'll verify the others.
3304 if (InstInfo.InferredFrom)
3305 continue;
3306
3307 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003308 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003309 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3310 }
3311
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003312 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003313 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003314
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003315 // Revisit instructions with undefined flags and no pattern.
3316 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003317 for (CodeGenInstruction *InstInfo : Revisit) {
3318 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003319 continue;
3320 // The mayLoad and mayStore flags default to false.
3321 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003322 if (InstInfo->hasSideEffects_Unset)
3323 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003324 }
3325 return;
3326 }
3327
3328 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003329 for (CodeGenInstruction *InstInfo : Revisit) {
3330 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003331 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003332 if (InstInfo->hasSideEffects_Unset)
3333 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003334 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003335 if (InstInfo->mayStore_Unset)
3336 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003337 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003338 if (InstInfo->mayLoad_Unset)
3339 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003340 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003341 }
3342}
3343
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003344
3345/// Verify instruction flags against pattern node properties.
3346void CodeGenDAGPatterns::VerifyInstructionFlags() {
3347 unsigned Errors = 0;
3348 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3349 const PatternToMatch &PTM = *I;
3350 SmallVector<Record*, 8> Instrs;
3351 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3352 if (Instrs.empty())
3353 continue;
3354
3355 // Count the number of instructions with each flag set.
3356 unsigned NumSideEffects = 0;
3357 unsigned NumStores = 0;
3358 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003359 for (const Record *Instr : Instrs) {
3360 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003361 NumSideEffects += InstInfo.hasSideEffects;
3362 NumStores += InstInfo.mayStore;
3363 NumLoads += InstInfo.mayLoad;
3364 }
3365
3366 // Analyze the source pattern.
3367 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003368 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003369
3370 // Collect error messages.
3371 SmallVector<std::string, 4> Msgs;
3372
3373 // Check for missing flags in the output.
3374 // Permit extra flags for now at least.
3375 if (PatInfo.hasSideEffects && !NumSideEffects)
3376 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3377
3378 // Don't verify store flags on instructions with side effects. At least for
3379 // intrinsics, side effects implies mayStore.
3380 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3381 Msgs.push_back("pattern may store, but mayStore isn't set");
3382
3383 // Similarly, mayStore implies mayLoad on intrinsics.
3384 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3385 Msgs.push_back("pattern may load, but mayLoad isn't set");
3386
3387 // Print error messages.
3388 if (Msgs.empty())
3389 continue;
3390 ++Errors;
3391
Craig Topper306cb122015-11-22 20:46:24 +00003392 for (const std::string &Msg : Msgs)
3393 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003394 (Instrs.size() == 1 ?
3395 "instruction" : "output instructions"));
3396 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003397 for (const Record *Instr : Instrs) {
3398 if (Instr != PTM.getSrcRecord())
3399 PrintError(Instr->getLoc(), "defined here");
3400 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003401 if (InstInfo.InferredFrom &&
3402 InstInfo.InferredFrom != InstInfo.TheDef &&
3403 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003404 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003405 }
3406 }
3407 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003408 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003409}
3410
Chris Lattnercabe0372010-03-15 06:00:16 +00003411/// Given a pattern result with an unresolved type, see if we can find one
3412/// instruction with an unresolved result type. Force this result type to an
3413/// arbitrary element if it's possible types to converge results.
3414static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3415 if (N->isLeaf())
3416 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003417
Chris Lattnercabe0372010-03-15 06:00:16 +00003418 // Analyze children.
3419 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3420 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3421 return true;
3422
3423 if (!N->getOperator()->isSubClassOf("Instruction"))
3424 return false;
3425
3426 // If this type is already concrete or completely unknown we can't do
3427 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003428 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3429 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3430 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003431
Chris Lattnerf1447252010-03-19 21:37:09 +00003432 // Otherwise, force its type to the first possibility (an arbitrary choice).
3433 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3434 return true;
3435 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003436
Chris Lattnerf1447252010-03-19 21:37:09 +00003437 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003438}
3439
Chris Lattnerab3242f2008-01-06 01:10:31 +00003440void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003441 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3442
Craig Topper306cb122015-11-22 20:46:24 +00003443 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003444 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003445
3446 // If the pattern references the null_frag, there's nothing to do.
3447 if (hasNullFragReference(Tree))
3448 continue;
3449
Chris Lattner5c2182e2010-03-27 02:53:27 +00003450 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003451
3452 // Inline pattern fragments into it.
3453 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003454
David Greeneaf8ee2c2011-07-29 22:43:06 +00003455 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003456 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003457
Chris Lattner8cab0212008-01-05 22:25:12 +00003458 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003459 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003460
Chris Lattner8cab0212008-01-05 22:25:12 +00003461 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003462 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003463
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003464 if (Result.getNumTrees() != 1)
3465 Result.error("Cannot handle instructions producing instructions "
3466 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003467
Chris Lattner8cab0212008-01-05 22:25:12 +00003468 bool IterateInference;
3469 bool InferredAllPatternTypes, InferredAllResultTypes;
3470 do {
3471 // Infer as many types as possible. If we cannot infer all of them, we
3472 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003473 InferredAllPatternTypes =
3474 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003475
Chris Lattner8cab0212008-01-05 22:25:12 +00003476 // Infer as many types as possible. If we cannot infer all of them, we
3477 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003478 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003479 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003480
Chris Lattnerfdc20712010-03-18 23:15:10 +00003481 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003482
Chris Lattner8cab0212008-01-05 22:25:12 +00003483 // Apply the type of the result to the source pattern. This helps us
3484 // resolve cases where the input type is known to be a pointer type (which
3485 // is considered resolved), but the result knows it needs to be 32- or
3486 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003487 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003488 Pattern->getTree(0)->getNumTypes());
3489 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003490 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3491 i, Result.getTree(0)->getExtType(i), Result);
3492 IterateInference |= Result.getTree(0)->UpdateNodeType(
3493 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003494 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003495
Chris Lattnercabe0372010-03-15 06:00:16 +00003496 // If our iteration has converged and the input pattern's types are fully
3497 // resolved but the result pattern is not fully resolved, we may have a
3498 // situation where we have two instructions in the result pattern and
3499 // the instructions require a common register class, but don't care about
3500 // what actual MVT is used. This is actually a bug in our modelling:
3501 // output patterns should have register classes, not MVTs.
3502 //
3503 // In any case, to handle this, we just go through and disambiguate some
3504 // arbitrary types to the result pattern's nodes.
3505 if (!IterateInference && InferredAllPatternTypes &&
3506 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003507 IterateInference =
3508 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003509 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003510
Chris Lattner8cab0212008-01-05 22:25:12 +00003511 // Verify that we inferred enough types that we can do something with the
3512 // pattern and result. If these fire the user has to add type casts.
3513 if (!InferredAllPatternTypes)
3514 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003515 if (!InferredAllResultTypes) {
3516 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003517 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003518 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003519
Chris Lattner8cab0212008-01-05 22:25:12 +00003520 // Validate that the input pattern is correct.
3521 std::map<std::string, TreePatternNode*> InstInputs;
3522 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003523 std::vector<Record*> InstImpResults;
3524 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3525 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3526 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003527 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003528
3529 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003530 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003531 std::vector<TreePatternNode*> ResultNodeOperands;
3532 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3533 TreePatternNode *OpNode = DstPattern->getChild(ii);
3534 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003535 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003536 std::vector<TreePatternNode*> Children;
3537 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003538 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003539 }
3540 ResultNodeOperands.push_back(OpNode);
3541 }
David Blaikiecf195302014-11-17 22:55:41 +00003542 DstPattern = Result.getOnlyTree();
3543 if (!DstPattern->isLeaf())
3544 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3545 ResultNodeOperands,
3546 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003547
David Blaikiecf195302014-11-17 22:55:41 +00003548 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3549 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3550
3551 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003552 Temp.InferAllTypes();
3553
Craig Topper18e6b572017-06-25 17:33:49 +00003554 AddPatternToMatch(
3555 Pattern,
3556 PatternToMatch(
3557 CurPattern, CurPattern->getValueAsListInit("Predicates"),
3558 Pattern->getTree(0), Temp.getOnlyTree(), std::move(InstImpResults),
3559 CurPattern->getValueAsInt("AddedComplexity"), CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003560 }
3561}
3562
3563/// CombineChildVariants - Given a bunch of permutations of each child of the
3564/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003565static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003566 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3567 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003568 CodeGenDAGPatterns &CDP,
3569 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003570 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003571 for (const auto &Variants : ChildVariants)
3572 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003573 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003574
Chris Lattner8cab0212008-01-05 22:25:12 +00003575 // The end result is an all-pairs construction of the resultant pattern.
3576 std::vector<unsigned> Idxs;
3577 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003578 bool NotDone;
3579 do {
3580#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003581 DEBUG(if (!Idxs.empty()) {
3582 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003583 for (unsigned Idx : Idxs) {
3584 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003585 }
3586 errs() << "]\n";
3587 });
Scott Michel94420742008-03-05 17:49:05 +00003588#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003589 // Create the variant and add it to the output list.
3590 std::vector<TreePatternNode*> NewChildren;
3591 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3592 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003593 auto R = llvm::make_unique<TreePatternNode>(
3594 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003595
Chris Lattner8cab0212008-01-05 22:25:12 +00003596 // Copy over properties.
3597 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003598 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003599 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003600 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3601 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003602
Scott Michel94420742008-03-05 17:49:05 +00003603 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003604 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003605 // Scan to see if this pattern has already been emitted. We can get
3606 // duplication due to things like commuting:
3607 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3608 // which are the same pattern. Ignore the dups.
3609 if (R->canPatternMatch(ErrString, CDP) &&
David Majnemer0a16c222016-08-11 21:15:00 +00003610 none_of(OutVariants, [&](TreePatternNode *Variant) {
3611 return R->isIsomorphicTo(Variant, DepVars);
3612 }))
David Blaikiefda69dd2015-11-22 20:11:21 +00003613 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003614
Scott Michel94420742008-03-05 17:49:05 +00003615 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003616 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003617 // [0, 0], [0, 1], [1, 0], [1, 1].
3618 int IdxsIdx;
3619 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3620 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3621 Idxs[IdxsIdx] = 0;
3622 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003623 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003624 }
Scott Michel94420742008-03-05 17:49:05 +00003625 NotDone = (IdxsIdx >= 0);
3626 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003627}
3628
3629/// CombineChildVariants - A helper function for binary operators.
3630///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003631static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003632 const std::vector<TreePatternNode*> &LHS,
3633 const std::vector<TreePatternNode*> &RHS,
3634 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003635 CodeGenDAGPatterns &CDP,
3636 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003637 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3638 ChildVariants.push_back(LHS);
3639 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003640 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003641}
Chris Lattner8cab0212008-01-05 22:25:12 +00003642
3643
3644static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3645 std::vector<TreePatternNode *> &Children) {
3646 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3647 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003648
Chris Lattner8cab0212008-01-05 22:25:12 +00003649 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003650 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003651 N->getTransformFn()) {
3652 Children.push_back(N);
3653 return;
3654 }
3655
3656 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3657 Children.push_back(N->getChild(0));
3658 else
3659 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3660
3661 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3662 Children.push_back(N->getChild(1));
3663 else
3664 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3665}
3666
3667/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3668/// the (potentially recursive) pattern by using algebraic laws.
3669///
3670static void GenerateVariantsOf(TreePatternNode *N,
3671 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003672 CodeGenDAGPatterns &CDP,
3673 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003674 // We cannot permute leaves or ComplexPattern uses.
3675 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003676 OutVariants.push_back(N);
3677 return;
3678 }
3679
3680 // Look up interesting info about the node.
3681 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3682
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003683 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003684 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003685 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003686 std::vector<TreePatternNode*> MaximalChildren;
3687 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3688
3689 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3690 // permutations.
3691 if (MaximalChildren.size() == 3) {
3692 // Find the variants of all of our maximal children.
3693 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003694 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3695 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3696 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003697
Chris Lattner8cab0212008-01-05 22:25:12 +00003698 // There are only two ways we can permute the tree:
3699 // (A op B) op C and A op (B op C)
3700 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003701
Chris Lattner8cab0212008-01-05 22:25:12 +00003702 // Generate legal pair permutations of A/B/C.
3703 std::vector<TreePatternNode*> ABVariants;
3704 std::vector<TreePatternNode*> BAVariants;
3705 std::vector<TreePatternNode*> ACVariants;
3706 std::vector<TreePatternNode*> CAVariants;
3707 std::vector<TreePatternNode*> BCVariants;
3708 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003709 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3710 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3711 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3712 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3713 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3714 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003715
3716 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003717 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3718 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3719 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3720 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3721 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3722 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003723
3724 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003725 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3726 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3727 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3728 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3729 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3730 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003731 return;
3732 }
3733 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003734
Chris Lattner8cab0212008-01-05 22:25:12 +00003735 // Compute permutations of all children.
3736 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3737 ChildVariants.resize(N->getNumChildren());
3738 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003739 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003740
3741 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003742 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003743
3744 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003745 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3746 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3747 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3748 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003749 // Don't count children which are actually register references.
3750 unsigned NC = 0;
3751 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3752 TreePatternNode *Child = N->getChild(i);
3753 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003754 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003755 Record *RR = DI->getDef();
3756 if (RR->isSubClassOf("Register"))
3757 continue;
3758 }
3759 NC++;
3760 }
3761 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003762 if (isCommIntrinsic) {
3763 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3764 // operands are the commutative operands, and there might be more operands
3765 // after those.
3766 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003767 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00003768 std::vector<std::vector<TreePatternNode*> > Variants;
3769 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3770 Variants.push_back(ChildVariants[2]);
3771 Variants.push_back(ChildVariants[1]);
3772 for (unsigned i = 3; i != NC; ++i)
3773 Variants.push_back(ChildVariants[i]);
3774 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3775 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003776 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003777 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003778 }
3779}
3780
3781
3782// GenerateVariants - Generate variants. For example, commutative patterns can
3783// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003784void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003785 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003786
Chris Lattner8cab0212008-01-05 22:25:12 +00003787 // Loop over all of the patterns we've collected, checking to see if we can
3788 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003789 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003790 // the .td file having to contain tons of variants of instructions.
3791 //
3792 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3793 // intentionally do not reconsider these. Any variants of added patterns have
3794 // already been added.
3795 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00003796 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003797 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003798 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003799 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003800 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003801 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003802 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00003803 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003804 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003805
3806 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00003807 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003808 continue;
3809
Chris Lattner34822f62009-08-23 04:44:11 +00003810 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00003811 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00003812 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003813
3814 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3815 TreePatternNode *Variant = Variants[v];
3816
Chris Lattner34822f62009-08-23 04:44:11 +00003817 DEBUG(errs() << " VAR#" << v << ": ";
3818 Variant->dump();
3819 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003820
Chris Lattner8cab0212008-01-05 22:25:12 +00003821 // Scan to see if an instruction or explicit pattern already matches this.
3822 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003823 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003824 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003825 if (PatternsToMatch[i].getPredicates() !=
3826 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00003827 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003828 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003829 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3830 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003831 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003832 AlreadyExists = true;
3833 break;
3834 }
3835 }
3836 // If we already have it, ignore the variant.
3837 if (AlreadyExists) continue;
3838
3839 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00003840 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00003841 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3842 Variant, PatternsToMatch[i].getDstPattern(),
3843 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00003844 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003845 }
3846
Chris Lattner34822f62009-08-23 04:44:11 +00003847 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003848 }
3849}