blob: 4396297c6d7e53714a2601c94df8dff2e8b99877 [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner6cefb772008-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 Lattnerfe718932008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner93c7e412008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattner2cacec52010-03-15 06:00:16 +000016#include "llvm/ADT/STLExtras.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000017#include "llvm/ADT/StringExtras.h"
Jim Grosbach9b29ea42012-04-18 17:46:41 +000018#include "llvm/ADT/Twine.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include "llvm/Support/Debug.h"
David Blaikiefdebc382012-01-17 04:43:56 +000020#include "llvm/Support/ErrorHandling.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000021#include "llvm/TableGen/Error.h"
22#include "llvm/TableGen/Record.h"
Chuck Rose III9a79de32008-01-15 21:43:17 +000023#include <algorithm>
Benjamin Kramer901b8582012-03-23 11:35:30 +000024#include <cstdio>
25#include <set>
Chris Lattner6cefb772008-01-05 22:25:12 +000026using namespace llvm;
27
28//===----------------------------------------------------------------------===//
Chris Lattner2cacec52010-03-15 06:00:16 +000029// EEVT::TypeSet Implementation
30//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +000031
Owen Anderson825b72b2009-08-11 20:47:22 +000032static inline bool isInteger(MVT::SimpleValueType VT) {
Craig Topper49909412013-09-25 06:37:18 +000033 return MVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000034}
Owen Anderson825b72b2009-08-11 20:47:22 +000035static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Craig Topper49909412013-09-25 06:37:18 +000036 return MVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000037}
Owen Anderson825b72b2009-08-11 20:47:22 +000038static inline bool isVector(MVT::SimpleValueType VT) {
Craig Topper49909412013-09-25 06:37:18 +000039 return MVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000040}
Chris Lattner774ce292010-03-19 17:41:26 +000041static inline bool isScalar(MVT::SimpleValueType VT) {
Craig Topper49909412013-09-25 06:37:18 +000042 return !MVT(VT).isVector();
Chris Lattner774ce292010-03-19 17:41:26 +000043}
Duncan Sands83ec4b62008-06-06 12:08:01 +000044
Chris Lattner2cacec52010-03-15 06:00:16 +000045EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
46 if (VT == MVT::iAny)
47 EnforceInteger(TP);
48 else if (VT == MVT::fAny)
49 EnforceFloatingPoint(TP);
50 else if (VT == MVT::vAny)
51 EnforceVector(TP);
52 else {
53 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
54 VT == MVT::iPTRAny) && "Not a concrete type!");
55 TypeVec.push_back(VT);
56 }
Chris Lattner6cefb772008-01-05 22:25:12 +000057}
58
Chris Lattner2cacec52010-03-15 06:00:16 +000059
Jakob Stoklund Olesen26369a92013-03-17 17:26:09 +000060EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
Chris Lattner2cacec52010-03-15 06:00:16 +000061 assert(!VTList.empty() && "empty list?");
62 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000063
Chris Lattner2cacec52010-03-15 06:00:16 +000064 if (!VTList.empty())
65 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
66 VTList[0] != MVT::fAny);
Jim Grosbachfbadcd02010-12-21 16:16:00 +000067
Chris Lattner0d7952e2010-03-27 20:32:26 +000068 // Verify no duplicates.
Chris Lattner2cacec52010-03-15 06:00:16 +000069 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner0d7952e2010-03-27 20:32:26 +000070 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner6cefb772008-01-05 22:25:12 +000071}
72
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000073/// FillWithPossibleTypes - Set to all legal types and return true, only valid
74/// on completely unknown type sets.
Chris Lattner774ce292010-03-19 17:41:26 +000075bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
76 bool (*Pred)(MVT::SimpleValueType),
77 const char *PredicateName) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000078 assert(isCompletelyUnknown());
Jakob Stoklund Olesen26369a92013-03-17 17:26:09 +000079 ArrayRef<MVT::SimpleValueType> LegalTypes =
Chris Lattner774ce292010-03-19 17:41:26 +000080 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +000081
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +000082 if (TP.hasError())
83 return false;
84
Chris Lattner774ce292010-03-19 17:41:26 +000085 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
86 if (Pred == 0 || Pred(LegalTypes[i]))
87 TypeVec.push_back(LegalTypes[i]);
88
89 // If we have nothing that matches the predicate, bail out.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +000090 if (TypeVec.empty()) {
Chris Lattner774ce292010-03-19 17:41:26 +000091 TP.error("Type inference contradiction found, no " +
Jim Grosbachfbadcd02010-12-21 16:16:00 +000092 std::string(PredicateName) + " types found");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +000093 return false;
94 }
Chris Lattner774ce292010-03-19 17:41:26 +000095 // No need to sort with one element.
96 if (TypeVec.size() == 1) return true;
97
98 // Remove duplicates.
99 array_pod_sort(TypeVec.begin(), TypeVec.end());
100 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000101
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000102 return true;
103}
Chris Lattner2cacec52010-03-15 06:00:16 +0000104
105/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
106/// integer value type.
107bool EEVT::TypeSet::hasIntegerTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isInteger(TypeVec[i]))
110 return true;
111 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000112}
Chris Lattner2cacec52010-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 {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isFloatingPoint(TypeVec[i]))
119 return true;
120 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000121}
Chris Lattner2cacec52010-03-15 06:00:16 +0000122
123/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
124/// value type.
125bool EEVT::TypeSet::hasVectorTypes() const {
126 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
127 if (isVector(TypeVec[i]))
128 return true;
129 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +0000130}
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000131
Chris Lattner2cacec52010-03-15 06:00:16 +0000132
133std::string EEVT::TypeSet::getName() const {
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000134 if (TypeVec.empty()) return "<empty>";
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000135
Chris Lattner2cacec52010-03-15 06:00:16 +0000136 std::string Result;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000137
Chris Lattner2cacec52010-03-15 06:00:16 +0000138 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
139 std::string VTName = llvm::getEnumName(TypeVec[i]);
140 // Strip off MVT:: prefix if present.
141 if (VTName.substr(0,5) == "MVT::")
142 VTName = VTName.substr(5);
143 if (i) Result += ':';
144 Result += VTName;
145 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000146
Chris Lattner2cacec52010-03-15 06:00:16 +0000147 if (TypeVec.size() == 1)
148 return Result;
149 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000150}
Chris Lattner2cacec52010-03-15 06:00:16 +0000151
152/// MergeInTypeInfo - This merges in type information from the specified
153/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000154/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattner2cacec52010-03-15 06:00:16 +0000155bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000156 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattner2cacec52010-03-15 06:00:16 +0000157 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000158
Chris Lattner2cacec52010-03-15 06:00:16 +0000159 if (isCompletelyUnknown()) {
160 *this = InVT;
161 return true;
162 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000163
Chris Lattner2cacec52010-03-15 06:00:16 +0000164 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000165
Chris Lattner2cacec52010-03-15 06:00:16 +0000166 // Handle the abstract cases, seeing if we can resolve them better.
167 switch (TypeVec[0]) {
168 default: break;
169 case MVT::iPTR:
170 case MVT::iPTRAny:
171 if (InVT.hasIntegerTypes()) {
172 EEVT::TypeSet InCopy(InVT);
173 InCopy.EnforceInteger(TP);
174 InCopy.EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000175
Chris Lattner2cacec52010-03-15 06:00:16 +0000176 if (InCopy.isConcrete()) {
177 // If the RHS has one integer type, upgrade iPTR to i32.
178 TypeVec[0] = InVT.TypeVec[0];
179 return true;
180 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000181
Chris Lattner2cacec52010-03-15 06:00:16 +0000182 // If the input has multiple scalar integers, this doesn't add any info.
183 if (!InCopy.isCompletelyUnknown())
184 return false;
185 }
186 break;
187 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000188
Chris Lattner2cacec52010-03-15 06:00:16 +0000189 // If the input constraint is iAny/iPTR and this is an integer type list,
190 // remove non-integer types from the list.
191 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
192 hasIntegerTypes()) {
193 bool MadeChange = EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000194
Chris Lattner2cacec52010-03-15 06:00:16 +0000195 // If we're merging in iPTR/iPTRAny and the node currently has a list of
196 // multiple different integer types, replace them with a single iPTR.
197 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
198 TypeVec.size() != 1) {
199 TypeVec.resize(1);
200 TypeVec[0] = InVT.TypeVec[0];
201 MadeChange = true;
202 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000203
Chris Lattner2cacec52010-03-15 06:00:16 +0000204 return MadeChange;
205 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000206
Chris Lattner2cacec52010-03-15 06:00:16 +0000207 // If this is a type list and the RHS is a typelist as well, eliminate entries
208 // from this list that aren't in the other one.
209 bool MadeChange = false;
210 TypeSet InputSet(*this);
211
212 for (unsigned i = 0; i != TypeVec.size(); ++i) {
213 bool InInVT = false;
214 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
215 if (TypeVec[i] == InVT.TypeVec[j]) {
216 InInVT = true;
217 break;
218 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000219
Chris Lattner2cacec52010-03-15 06:00:16 +0000220 if (InInVT) continue;
221 TypeVec.erase(TypeVec.begin()+i--);
222 MadeChange = true;
223 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000224
Chris Lattner2cacec52010-03-15 06:00:16 +0000225 // If we removed all of our types, we have a type contradiction.
226 if (!TypeVec.empty())
227 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000228
Chris Lattner2cacec52010-03-15 06:00:16 +0000229 // FIXME: Really want an SMLoc here!
230 TP.error("Type inference contradiction found, merging '" +
231 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000232 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +0000233}
234
235/// EnforceInteger - Remove all non-integer types from this set.
236bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000237 if (TP.hasError())
238 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +0000239 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000240 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000241 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattner2cacec52010-03-15 06:00:16 +0000242 if (!hasFloatingPointTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000243 return false;
244
245 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000246
Chris Lattner2cacec52010-03-15 06:00:16 +0000247 // Filter out all the fp types.
248 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000249 if (!isInteger(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000250 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000251
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000252 if (TypeVec.empty()) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000253 TP.error("Type inference contradiction found, '" +
254 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000255 return false;
256 }
Chris Lattner774ce292010-03-19 17:41:26 +0000257 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000258}
259
260/// EnforceFloatingPoint - Remove all integer types from this set.
261bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000262 if (TP.hasError())
263 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +0000264 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000265 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000266 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
267
Chris Lattner2cacec52010-03-15 06:00:16 +0000268 if (!hasIntegerTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000269 return false;
270
271 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000272
Chris Lattner2cacec52010-03-15 06:00:16 +0000273 // Filter out all the fp types.
274 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000275 if (!isFloatingPoint(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000276 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000277
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000278 if (TypeVec.empty()) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000279 TP.error("Type inference contradiction found, '" +
280 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000281 return false;
282 }
Chris Lattner774ce292010-03-19 17:41:26 +0000283 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000284}
285
286/// EnforceScalar - Remove all vector types from this.
287bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000288 if (TP.hasError())
289 return false;
290
Chris Lattner2cacec52010-03-15 06:00:16 +0000291 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000292 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000293 return FillWithPossibleTypes(TP, isScalar, "scalar");
294
Chris Lattner2cacec52010-03-15 06:00:16 +0000295 if (!hasVectorTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000296 return false;
297
298 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000299
Chris Lattner2cacec52010-03-15 06:00:16 +0000300 // Filter out all the vector types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000302 if (!isScalar(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000303 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000304
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000305 if (TypeVec.empty()) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000306 TP.error("Type inference contradiction found, '" +
307 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000308 return false;
309 }
Chris Lattner774ce292010-03-19 17:41:26 +0000310 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000311}
312
313/// EnforceVector - Remove all vector types from this.
314bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000315 if (TP.hasError())
316 return false;
317
Chris Lattner774ce292010-03-19 17:41:26 +0000318 // If we know nothing, then get the full set.
319 if (TypeVec.empty())
320 return FillWithPossibleTypes(TP, isVector, "vector");
321
Chris Lattner2cacec52010-03-15 06:00:16 +0000322 TypeSet InputSet(*this);
323 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000324
Chris Lattner2cacec52010-03-15 06:00:16 +0000325 // Filter out all the scalar types.
326 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000327 if (!isVector(TypeVec[i])) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000328 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner774ce292010-03-19 17:41:26 +0000329 MadeChange = true;
330 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000331
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000332 if (TypeVec.empty()) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000333 TP.error("Type inference contradiction found, '" +
334 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000335 return false;
336 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000337 return MadeChange;
338}
339
340
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000341
Chris Lattner2cacec52010-03-15 06:00:16 +0000342/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
343/// this an other based on this information.
344bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000345 if (TP.hasError())
346 return false;
347
Chris Lattner2cacec52010-03-15 06:00:16 +0000348 // Both operands must be integer or FP, but we don't care which.
349 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000350
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000351 if (isCompletelyUnknown())
352 MadeChange = FillWithPossibleTypes(TP);
353
354 if (Other.isCompletelyUnknown())
355 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000356
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000357 // If one side is known to be integer or known to be FP but the other side has
358 // no information, get at least the type integrality info in there.
359 if (!hasFloatingPointTypes())
360 MadeChange |= Other.EnforceInteger(TP);
361 else if (!hasIntegerTypes())
362 MadeChange |= Other.EnforceFloatingPoint(TP);
363 if (!Other.hasFloatingPointTypes())
364 MadeChange |= EnforceInteger(TP);
365 else if (!Other.hasIntegerTypes())
366 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000367
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000368 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
369 "Should have a type list now");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000370
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000371 // If one contains vectors but the other doesn't pull vectors out.
372 if (!hasVectorTypes())
373 MadeChange |= Other.EnforceScalar(TP);
374 if (!hasVectorTypes())
375 MadeChange |= EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000376
David Greene9d7f0112011-02-01 19:12:32 +0000377 if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
378 // If we are down to concrete types, this code does not currently
379 // handle nodes which have multiple types, where some types are
380 // integer, and some are fp. Assert that this is not the case.
381 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
382 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
383 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
384
385 // Otherwise, if these are both vector types, either this vector
386 // must have a larger bitsize than the other, or this element type
387 // must be larger than the other.
Craig Topper49909412013-09-25 06:37:18 +0000388 MVT Type(TypeVec[0]);
389 MVT OtherType(Other.TypeVec[0]);
David Greene9d7f0112011-02-01 19:12:32 +0000390
391 if (hasVectorTypes() && Other.hasVectorTypes()) {
392 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
393 if (Type.getVectorElementType().getSizeInBits()
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000394 >= OtherType.getVectorElementType().getSizeInBits()) {
David Greene9d7f0112011-02-01 19:12:32 +0000395 TP.error("Type inference contradiction found, '" +
396 getName() + "' element type not smaller than '" +
397 Other.getName() +"'!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000398 return false;
399 }
Craig Topperfb2d8e12013-09-24 06:21:04 +0000400 } else
David Greene9d7f0112011-02-01 19:12:32 +0000401 // For scalar types, the bitsize of this type must be larger
402 // than that of the other.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000403 if (Type.getSizeInBits() >= OtherType.getSizeInBits()) {
David Greene9d7f0112011-02-01 19:12:32 +0000404 TP.error("Type inference contradiction found, '" +
405 getName() + "' is not smaller than '" +
406 Other.getName() +"'!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000407 return false;
408 }
David Greene9d7f0112011-02-01 19:12:32 +0000409 }
410
411
412 // Handle int and fp as disjoint sets. This won't work for patterns
413 // that have mixed fp/int types but those are likely rare and would
414 // not have been accepted by this code previously.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000415
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000416 // Okay, find the smallest type from the current set and remove it from the
417 // largest set.
David Greenec83e2032011-02-04 17:01:53 +0000418 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000419 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
420 if (isInteger(TypeVec[i])) {
421 SmallestInt = TypeVec[i];
422 break;
423 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000424 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000425 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
426 SmallestInt = TypeVec[i];
427
David Greenec83e2032011-02-04 17:01:53 +0000428 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000429 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
430 if (isFloatingPoint(TypeVec[i])) {
431 SmallestFP = TypeVec[i];
432 break;
433 }
434 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
435 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
436 SmallestFP = TypeVec[i];
437
438 int OtherIntSize = 0;
439 int OtherFPSize = 0;
Craig Topper6227d5c2013-07-04 01:31:24 +0000440 for (SmallVectorImpl<MVT::SimpleValueType>::iterator TVI =
David Greene9d7f0112011-02-01 19:12:32 +0000441 Other.TypeVec.begin();
442 TVI != Other.TypeVec.end();
443 /* NULL */) {
444 if (isInteger(*TVI)) {
445 ++OtherIntSize;
446 if (*TVI == SmallestInt) {
447 TVI = Other.TypeVec.erase(TVI);
448 --OtherIntSize;
449 MadeChange = true;
450 continue;
451 }
Craig Topperfb2d8e12013-09-24 06:21:04 +0000452 } else if (isFloatingPoint(*TVI)) {
David Greene9d7f0112011-02-01 19:12:32 +0000453 ++OtherFPSize;
454 if (*TVI == SmallestFP) {
455 TVI = Other.TypeVec.erase(TVI);
456 --OtherFPSize;
457 MadeChange = true;
458 continue;
459 }
460 }
461 ++TVI;
462 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000463
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000464 // If this is the only type in the large set, the constraint can never be
465 // satisfied.
Craig Topperfb2d8e12013-09-24 06:21:04 +0000466 if ((Other.hasIntegerTypes() && OtherIntSize == 0) ||
467 (Other.hasFloatingPointTypes() && OtherFPSize == 0)) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000468 TP.error("Type inference contradiction found, '" +
469 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000470 return false;
471 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000472
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000473 // Okay, find the largest type in the Other set and remove it from the
474 // current set.
David Greenec83e2032011-02-04 17:01:53 +0000475 MVT::SimpleValueType LargestInt = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000476 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
477 if (isInteger(Other.TypeVec[i])) {
478 LargestInt = Other.TypeVec[i];
479 break;
480 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000481 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000482 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
483 LargestInt = Other.TypeVec[i];
484
David Greenec83e2032011-02-04 17:01:53 +0000485 MVT::SimpleValueType LargestFP = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000486 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
487 if (isFloatingPoint(Other.TypeVec[i])) {
488 LargestFP = Other.TypeVec[i];
489 break;
490 }
491 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
492 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
493 LargestFP = Other.TypeVec[i];
494
495 int IntSize = 0;
496 int FPSize = 0;
Craig Topper6227d5c2013-07-04 01:31:24 +0000497 for (SmallVectorImpl<MVT::SimpleValueType>::iterator TVI =
David Greene9d7f0112011-02-01 19:12:32 +0000498 TypeVec.begin();
499 TVI != TypeVec.end();
500 /* NULL */) {
501 if (isInteger(*TVI)) {
502 ++IntSize;
503 if (*TVI == LargestInt) {
504 TVI = TypeVec.erase(TVI);
505 --IntSize;
506 MadeChange = true;
507 continue;
508 }
Craig Topperfb2d8e12013-09-24 06:21:04 +0000509 } else if (isFloatingPoint(*TVI)) {
David Greene9d7f0112011-02-01 19:12:32 +0000510 ++FPSize;
511 if (*TVI == LargestFP) {
512 TVI = TypeVec.erase(TVI);
513 --FPSize;
514 MadeChange = true;
515 continue;
516 }
517 }
518 ++TVI;
519 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000520
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000521 // If this is the only type in the small set, the constraint can never be
522 // satisfied.
Craig Topperfb2d8e12013-09-24 06:21:04 +0000523 if ((hasIntegerTypes() && IntSize == 0) ||
524 (hasFloatingPointTypes() && FPSize == 0)) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000525 TP.error("Type inference contradiction found, '" +
526 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000527 return false;
528 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000529
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000530 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000531}
532
533/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner66fb9d22010-03-24 00:01:16 +0000534/// whose element is specified by VTOperand.
535bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattner2cacec52010-03-15 06:00:16 +0000536 TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000537 if (TP.hasError())
538 return false;
539
Chris Lattner66fb9d22010-03-24 00:01:16 +0000540 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattner2cacec52010-03-15 06:00:16 +0000541 bool MadeChange = false;
Chris Lattner66fb9d22010-03-24 00:01:16 +0000542 MadeChange |= EnforceVector(TP);
543 MadeChange |= VTOperand.EnforceScalar(TP);
544
545 // If we know the vector type, it forces the scalar to agree.
546 if (isConcrete()) {
Craig Topper49909412013-09-25 06:37:18 +0000547 MVT IVT = getConcrete();
Chris Lattner66fb9d22010-03-24 00:01:16 +0000548 IVT = IVT.getVectorElementType();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000549 return MadeChange |
Craig Topper49909412013-09-25 06:37:18 +0000550 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner66fb9d22010-03-24 00:01:16 +0000551 }
552
553 // If the scalar type is known, filter out vector types whose element types
554 // disagree.
555 if (!VTOperand.isConcrete())
556 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000557
Chris Lattner66fb9d22010-03-24 00:01:16 +0000558 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000559
Chris Lattner66fb9d22010-03-24 00:01:16 +0000560 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000561
Chris Lattner66fb9d22010-03-24 00:01:16 +0000562 // Filter out all the types which don't have the right element type.
563 for (unsigned i = 0; i != TypeVec.size(); ++i) {
564 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
Craig Topper49909412013-09-25 06:37:18 +0000565 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000566 TypeVec.erase(TypeVec.begin()+i--);
567 MadeChange = true;
568 }
Chris Lattner66fb9d22010-03-24 00:01:16 +0000569 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000570
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000571 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattner2cacec52010-03-15 06:00:16 +0000572 TP.error("Type inference contradiction found, forcing '" +
573 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000574 return false;
575 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000576 return MadeChange;
577}
578
David Greene60322692011-01-24 20:53:18 +0000579/// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
580/// vector type specified by VTOperand.
581bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
582 TreePattern &TP) {
583 // "This" must be a vector and "VTOperand" must be a vector.
584 bool MadeChange = false;
585 MadeChange |= EnforceVector(TP);
586 MadeChange |= VTOperand.EnforceVector(TP);
587
588 // "This" must be larger than "VTOperand."
589 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
590
591 // If we know the vector type, it forces the scalar types to agree.
592 if (isConcrete()) {
Craig Topper49909412013-09-25 06:37:18 +0000593 MVT IVT = getConcrete();
David Greene60322692011-01-24 20:53:18 +0000594 IVT = IVT.getVectorElementType();
595
Craig Topper49909412013-09-25 06:37:18 +0000596 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene60322692011-01-24 20:53:18 +0000597 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
598 } else if (VTOperand.isConcrete()) {
Craig Topper49909412013-09-25 06:37:18 +0000599 MVT IVT = VTOperand.getConcrete();
David Greene60322692011-01-24 20:53:18 +0000600 IVT = IVT.getVectorElementType();
601
Craig Topper49909412013-09-25 06:37:18 +0000602 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene60322692011-01-24 20:53:18 +0000603 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
604 }
605
606 return MadeChange;
607}
608
Chris Lattner2cacec52010-03-15 06:00:16 +0000609//===----------------------------------------------------------------------===//
610// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000611
Scott Michel327d0652008-03-05 17:49:05 +0000612/// Dependent variable map for CodeGenDAGPattern variant generation
613typedef std::map<std::string, int> DepVarMap;
614
615/// Const iterator shorthand for DepVarMap
616typedef DepVarMap::const_iterator DepVarMap_citer;
617
Chris Lattner54379062011-04-17 21:38:24 +0000618static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel327d0652008-03-05 17:49:05 +0000619 if (N->isLeaf()) {
Sean Silva3f7b7f82012-10-10 20:24:47 +0000620 if (isa<DefInit>(N->getLeafValue()))
Scott Michel327d0652008-03-05 17:49:05 +0000621 DepMap[N->getName()]++;
Scott Michel327d0652008-03-05 17:49:05 +0000622 } else {
623 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
624 FindDepVarsOf(N->getChild(i), DepMap);
625 }
626}
Chris Lattner54379062011-04-17 21:38:24 +0000627
628/// Find dependent variables within child patterns
629static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000630 DepVarMap depcounts;
631 FindDepVarsOf(N, depcounts);
632 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner54379062011-04-17 21:38:24 +0000633 if (i->second > 1) // std::pair<std::string, int>
Scott Michel327d0652008-03-05 17:49:05 +0000634 DepVars.insert(i->first);
Scott Michel327d0652008-03-05 17:49:05 +0000635 }
636}
637
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000638#ifndef NDEBUG
Chris Lattner54379062011-04-17 21:38:24 +0000639/// Dump the dependent variable set:
640static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000641 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000642 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000643 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000644 DEBUG(errs() << "[ ");
Jim Grosbachbb168242010-10-08 18:13:57 +0000645 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
646 e = DepVars.end(); i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000647 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000648 }
Chris Lattner569f1212009-08-23 04:44:11 +0000649 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000650 }
651}
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000652#endif
653
Chris Lattner54379062011-04-17 21:38:24 +0000654
655//===----------------------------------------------------------------------===//
656// TreePredicateFn Implementation
657//===----------------------------------------------------------------------===//
658
Chris Lattner7ed13912011-04-17 22:05:17 +0000659/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
660TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
661 assert((getPredCode().empty() || getImmCode().empty()) &&
662 ".td file corrupt: can't have a node predicate *and* an imm predicate");
663}
664
Chris Lattner54379062011-04-17 21:38:24 +0000665std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +0000666 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner54379062011-04-17 21:38:24 +0000667}
668
Chris Lattner7ed13912011-04-17 22:05:17 +0000669std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +0000670 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner7ed13912011-04-17 22:05:17 +0000671}
672
Chris Lattner54379062011-04-17 21:38:24 +0000673
674/// isAlwaysTrue - Return true if this is a noop predicate.
675bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000676 return getPredCode().empty() && getImmCode().empty();
Chris Lattner54379062011-04-17 21:38:24 +0000677}
678
679/// Return the name to use in the generated code to reference this, this is
680/// "Predicate_foo" if from a pattern fragment "foo".
681std::string TreePredicateFn::getFnName() const {
682 return "Predicate_" + PatFragRec->getRecord()->getName();
683}
684
685/// getCodeToRunOnSDNode - Return the code for the function body that
686/// evaluates this predicate. The argument is expected to be in "Node",
687/// not N. This handles casting and conversion to a concrete node type as
688/// appropriate.
689std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000690 // Handle immediate predicates first.
691 std::string ImmCode = getImmCode();
692 if (!ImmCode.empty()) {
693 std::string Result =
694 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner7ed13912011-04-17 22:05:17 +0000695 return Result + ImmCode;
696 }
697
698 // Handle arbitrary node predicates.
699 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner54379062011-04-17 21:38:24 +0000700 std::string ClassName;
701 if (PatFragRec->getOnlyTree()->isLeaf())
702 ClassName = "SDNode";
703 else {
704 Record *Op = PatFragRec->getOnlyTree()->getOperator();
705 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
706 }
707 std::string Result;
708 if (ClassName == "SDNode")
709 Result = " SDNode *N = Node;\n";
710 else
711 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
712
713 return Result + getPredCode();
Scott Michel327d0652008-03-05 17:49:05 +0000714}
715
Chris Lattner6cefb772008-01-05 22:25:12 +0000716//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000717// PatternToMatch implementation
718//
719
Chris Lattner48e86db2010-03-29 01:40:38 +0000720
721/// getPatternSize - Return the 'size' of this pattern. We want to match large
722/// patterns before small ones. This is used to determine the size of a
723/// pattern.
724static unsigned getPatternSize(const TreePatternNode *P,
725 const CodeGenDAGPatterns &CGP) {
726 unsigned Size = 3; // The node itself.
727 // If the root node is a ConstantSDNode, increases its size.
728 // e.g. (set R32:$dst, 0).
Sean Silva3f7b7f82012-10-10 20:24:47 +0000729 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000730 Size += 2;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000731
Chris Lattner48e86db2010-03-29 01:40:38 +0000732 // FIXME: This is a hack to statically increase the priority of patterns
733 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
734 // Later we can allow complexity / cost for each pattern to be (optionally)
735 // specified. To get best possible pattern match we'll need to dynamically
736 // calculate the complexity of all patterns a dag can potentially map to.
737 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
738 if (AM)
739 Size += AM->getNumOperands() * 3;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000740
Chris Lattner48e86db2010-03-29 01:40:38 +0000741 // If this node has some predicate function that must match, it adds to the
742 // complexity of this node.
743 if (!P->getPredicateFns().empty())
744 ++Size;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000745
Chris Lattner48e86db2010-03-29 01:40:38 +0000746 // Count children in the count if they are also nodes.
747 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
748 TreePatternNode *Child = P->getChild(i);
749 if (!Child->isLeaf() && Child->getNumTypes() &&
750 Child->getType(0) != MVT::Other)
751 Size += getPatternSize(Child, CGP);
752 else if (Child->isLeaf()) {
Sean Silva3f7b7f82012-10-10 20:24:47 +0000753 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000754 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
755 else if (Child->getComplexPatternInfo(CGP))
756 Size += getPatternSize(Child, CGP);
757 else if (!Child->getPredicateFns().empty())
758 ++Size;
759 }
760 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000761
Chris Lattner48e86db2010-03-29 01:40:38 +0000762 return Size;
763}
764
765/// Compute the complexity metric for the input pattern. This roughly
766/// corresponds to the number of nodes that are covered.
767unsigned PatternToMatch::
768getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
769 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
770}
771
772
Dan Gohman22bb3112008-08-22 00:20:26 +0000773/// getPredicateCheck - Return a single string containing all of this
774/// pattern's predicates concatenated with "&&" operators.
775///
776std::string PatternToMatch::getPredicateCheck() const {
777 std::string PredicateCheck;
778 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
Sean Silva6cfc8062012-10-10 20:24:43 +0000779 if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
Dan Gohman22bb3112008-08-22 00:20:26 +0000780 Record *Def = Pred->getDef();
781 if (!Def->isSubClassOf("Predicate")) {
782#ifndef NDEBUG
783 Def->dump();
784#endif
Craig Topper655b8de2012-02-05 07:21:30 +0000785 llvm_unreachable("Unknown predicate type!");
Dan Gohman22bb3112008-08-22 00:20:26 +0000786 }
787 if (!PredicateCheck.empty())
788 PredicateCheck += " && ";
789 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
790 }
791 }
792
793 return PredicateCheck;
794}
795
796//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000797// SDTypeConstraint implementation
798//
799
800SDTypeConstraint::SDTypeConstraint(Record *R) {
801 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000802
Chris Lattner6cefb772008-01-05 22:25:12 +0000803 if (R->isSubClassOf("SDTCisVT")) {
804 ConstraintType = SDTCisVT;
805 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerc8122612010-03-28 06:04:39 +0000806 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000807 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000808
Chris Lattner6cefb772008-01-05 22:25:12 +0000809 } else if (R->isSubClassOf("SDTCisPtrTy")) {
810 ConstraintType = SDTCisPtrTy;
811 } else if (R->isSubClassOf("SDTCisInt")) {
812 ConstraintType = SDTCisInt;
813 } else if (R->isSubClassOf("SDTCisFP")) {
814 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000815 } else if (R->isSubClassOf("SDTCisVec")) {
816 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000817 } else if (R->isSubClassOf("SDTCisSameAs")) {
818 ConstraintType = SDTCisSameAs;
819 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
820 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
821 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000822 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000823 R->getValueAsInt("OtherOperandNum");
824 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
825 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000826 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000827 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000828 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
829 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000830 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene60322692011-01-24 20:53:18 +0000831 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
832 ConstraintType = SDTCisSubVecOfVec;
833 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
834 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000835 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000836 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000837 exit(1);
838 }
839}
840
841/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000842/// N, and the result number in ResNo.
843static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
844 const SDNodeInfo &NodeInfo,
845 unsigned &ResNo) {
846 unsigned NumResults = NodeInfo.getNumResults();
847 if (OpNo < NumResults) {
848 ResNo = OpNo;
849 return N;
850 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000851
Chris Lattner2e68a022010-03-19 21:56:21 +0000852 OpNo -= NumResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000853
Chris Lattner2e68a022010-03-19 21:56:21 +0000854 if (OpNo >= N->getNumChildren()) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000855 errs() << "Invalid operand number in type constraint "
Chris Lattner2e68a022010-03-19 21:56:21 +0000856 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000857 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000858 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000859 exit(1);
860 }
861
Chris Lattner2e68a022010-03-19 21:56:21 +0000862 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000863}
864
865/// ApplyTypeConstraint - Given a node in a pattern, apply this type
866/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000867/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner6cefb772008-01-05 22:25:12 +0000868bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
869 const SDNodeInfo &NodeInfo,
870 TreePattern &TP) const {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000871 if (TP.hasError())
872 return false;
873
Chris Lattner2e68a022010-03-19 21:56:21 +0000874 unsigned ResNo = 0; // The result number being referenced.
875 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000876
Chris Lattner6cefb772008-01-05 22:25:12 +0000877 switch (ConstraintType) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000878 case SDTCisVT:
879 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000880 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000881 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000882 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000883 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000884 case SDTCisInt:
885 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000886 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000887 case SDTCisFP:
888 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000889 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000890 case SDTCisVec:
891 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000892 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000893 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000894 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000895 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000896 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000897 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
898 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000899 }
900 case SDTCisVTSmallerThanOp: {
901 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
902 // have an integer type that is smaller than the VT.
903 if (!NodeToApply->isLeaf() ||
Sean Silva3f7b7f82012-10-10 20:24:47 +0000904 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greene05bce0b2011-07-29 22:43:06 +0000905 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000906 ->isSubClassOf("ValueType")) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000907 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000908 return false;
909 }
Owen Anderson825b72b2009-08-11 20:47:22 +0000910 MVT::SimpleValueType VT =
David Greene05bce0b2011-07-29 22:43:06 +0000911 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000912
Chris Lattnercc878302010-03-24 00:06:46 +0000913 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000914
Chris Lattner2e68a022010-03-19 21:56:21 +0000915 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000916 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000917 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
918 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000919
Chris Lattnercc878302010-03-24 00:06:46 +0000920 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000921 }
922 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000923 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000924 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000925 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
926 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000927 return NodeToApply->getExtType(ResNo).
928 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000929 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000930 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000931 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000932 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000933 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
934 VResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000935
Chris Lattner66fb9d22010-03-24 00:01:16 +0000936 // Filter vector types out of VecOperand that don't have the right element
937 // type.
938 return VecOperand->getExtType(VResNo).
939 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000940 }
David Greene60322692011-01-24 20:53:18 +0000941 case SDTCisSubVecOfVec: {
942 unsigned VResNo = 0;
943 TreePatternNode *BigVecOperand =
944 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
945 VResNo);
946
947 // Filter vector types out of BigVecOperand that don't have the
948 // right subvector type.
949 return BigVecOperand->getExtType(VResNo).
950 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
951 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000952 }
David Blaikie58bd1512012-01-17 07:00:13 +0000953 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner6cefb772008-01-05 22:25:12 +0000954}
955
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +0000956// Update the node type to match an instruction operand or result as specified
957// in the ins or outs lists on the instruction definition. Return true if the
958// type was actually changed.
959bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
960 Record *Operand,
961 TreePattern &TP) {
962 // The 'unknown' operand indicates that types should be inferred from the
963 // context.
964 if (Operand->isSubClassOf("unknown_class"))
965 return false;
966
967 // The Operand class specifies a type directly.
968 if (Operand->isSubClassOf("Operand"))
969 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
970 TP);
971
972 // PointerLikeRegClass has a type that is determined at runtime.
973 if (Operand->isSubClassOf("PointerLikeRegClass"))
974 return UpdateNodeType(ResNo, MVT::iPTR, TP);
975
976 // Both RegisterClass and RegisterOperand operands derive their types from a
977 // register class def.
978 Record *RC = 0;
979 if (Operand->isSubClassOf("RegisterClass"))
980 RC = Operand;
981 else if (Operand->isSubClassOf("RegisterOperand"))
982 RC = Operand->getValueAsDef("RegClass");
983
984 assert(RC && "Unknown operand type");
985 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
986 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
987}
988
989
Chris Lattner6cefb772008-01-05 22:25:12 +0000990//===----------------------------------------------------------------------===//
991// SDNodeInfo implementation
992//
993SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
994 EnumName = R->getValueAsString("Opcode");
995 SDClassName = R->getValueAsString("SDClass");
996 Record *TypeProfile = R->getValueAsDef("TypeProfile");
997 NumResults = TypeProfile->getValueAsInt("NumResults");
998 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000999
Chris Lattner6cefb772008-01-05 22:25:12 +00001000 // Parse the properties.
1001 Properties = 0;
1002 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1003 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1004 if (PropList[i]->getName() == "SDNPCommutative") {
1005 Properties |= 1 << SDNPCommutative;
1006 } else if (PropList[i]->getName() == "SDNPAssociative") {
1007 Properties |= 1 << SDNPAssociative;
1008 } else if (PropList[i]->getName() == "SDNPHasChain") {
1009 Properties |= 1 << SDNPHasChain;
Chris Lattner036609b2010-12-23 18:28:41 +00001010 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1011 Properties |= 1 << SDNPOutGlue;
1012 } else if (PropList[i]->getName() == "SDNPInGlue") {
1013 Properties |= 1 << SDNPInGlue;
1014 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1015 Properties |= 1 << SDNPOptInGlue;
Chris Lattnerc8478d82008-01-06 06:44:58 +00001016 } else if (PropList[i]->getName() == "SDNPMayStore") {
1017 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +00001018 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1019 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +00001020 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1021 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +00001022 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1023 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +00001024 } else if (PropList[i]->getName() == "SDNPVariadic") {
1025 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +00001026 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001027 errs() << "Unknown SD Node property '" << PropList[i]->getName()
1028 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001029 exit(1);
1030 }
1031 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001032
1033
Chris Lattner6cefb772008-01-05 22:25:12 +00001034 // Parse the type constraints.
1035 std::vector<Record*> ConstraintList =
1036 TypeProfile->getValueAsListOfDefs("Constraints");
1037 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1038}
1039
Chris Lattner22579812010-02-28 00:22:30 +00001040/// getKnownType - If the type constraints on this node imply a fixed type
1041/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +00001042/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +00001043MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +00001044 unsigned NumResults = getNumResults();
1045 assert(NumResults <= 1 &&
1046 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +00001047 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001048
Chris Lattner22579812010-02-28 00:22:30 +00001049 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1050 // Make sure that this applies to the correct node result.
1051 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1052 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001053
Chris Lattner22579812010-02-28 00:22:30 +00001054 switch (TypeConstraints[i].ConstraintType) {
1055 default: break;
1056 case SDTypeConstraint::SDTCisVT:
1057 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1058 case SDTypeConstraint::SDTCisPtrTy:
1059 return MVT::iPTR;
1060 }
1061 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +00001062 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +00001063}
1064
Chris Lattner6cefb772008-01-05 22:25:12 +00001065//===----------------------------------------------------------------------===//
1066// TreePatternNode implementation
1067//
1068
1069TreePatternNode::~TreePatternNode() {
1070#if 0 // FIXME: implement refcounted tree nodes!
1071 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1072 delete getChild(i);
1073#endif
1074}
1075
Chris Lattnerd7349192010-03-19 21:37:09 +00001076static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1077 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +00001078 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +00001079 return 0; // All return nothing.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001080
Chris Lattner93dc92e2010-03-22 20:56:36 +00001081 if (Operator->isSubClassOf("Intrinsic"))
1082 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001083
Chris Lattnerd7349192010-03-19 21:37:09 +00001084 if (Operator->isSubClassOf("SDNode"))
1085 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001086
Chris Lattnerd7349192010-03-19 21:37:09 +00001087 if (Operator->isSubClassOf("PatFrag")) {
1088 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1089 // the forward reference case where one pattern fragment references another
1090 // before it is processed.
1091 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1092 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001093
Chris Lattnerd7349192010-03-19 21:37:09 +00001094 // Get the result tree.
David Greene05bce0b2011-07-29 22:43:06 +00001095 DagInit *Tree = Operator->getValueAsDag("Fragment");
Chris Lattnerd7349192010-03-19 21:37:09 +00001096 Record *Op = 0;
Sean Silva3f7b7f82012-10-10 20:24:47 +00001097 if (Tree)
1098 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1099 Op = DI->getDef();
Chris Lattnerd7349192010-03-19 21:37:09 +00001100 assert(Op && "Invalid Fragment");
1101 return GetNumNodeResults(Op, CDP);
1102 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001103
Chris Lattnerd7349192010-03-19 21:37:09 +00001104 if (Operator->isSubClassOf("Instruction")) {
1105 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001106
1107 // FIXME: Should allow access to all the results here.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001108 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001109
Chris Lattner9414ae52010-03-27 20:09:24 +00001110 // Add on one implicit def if it has a resolvable type.
1111 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1112 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001113 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +00001114 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001115
Chris Lattnerd7349192010-03-19 21:37:09 +00001116 if (Operator->isSubClassOf("SDNodeXForm"))
1117 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001118
Chris Lattnerd7349192010-03-19 21:37:09 +00001119 Operator->dump();
1120 errs() << "Unhandled node in GetNumNodeResults\n";
1121 exit(1);
1122}
1123
1124void TreePatternNode::print(raw_ostream &OS) const {
1125 if (isLeaf())
1126 OS << *getLeafValue();
1127 else
1128 OS << '(' << getOperator()->getName();
1129
1130 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1131 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +00001132
1133 if (!isLeaf()) {
1134 if (getNumChildren() != 0) {
1135 OS << " ";
1136 getChild(0)->print(OS);
1137 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1138 OS << ", ";
1139 getChild(i)->print(OS);
1140 }
1141 }
1142 OS << ")";
1143 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001144
Dan Gohman0540e172008-10-15 06:17:21 +00001145 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner54379062011-04-17 21:38:24 +00001146 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +00001147 if (TransformFn)
1148 OS << "<<X:" << TransformFn->getName() << ">>";
1149 if (!getName().empty())
1150 OS << ":$" << getName();
1151
1152}
1153void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001154 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +00001155}
1156
Scott Michel327d0652008-03-05 17:49:05 +00001157/// isIsomorphicTo - Return true if this node is recursively
1158/// isomorphic to the specified node. For this comparison, the node's
1159/// entire state is considered. The assigned name is ignored, since
1160/// nodes with differing names are considered isomorphic. However, if
1161/// the assigned name is present in the dependent variable set, then
1162/// the assigned name is considered significant and the node is
1163/// isomorphic if the names match.
1164bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1165 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001166 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +00001167 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +00001168 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00001169 getTransformFn() != N->getTransformFn())
1170 return false;
1171
1172 if (isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00001173 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1174 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +00001175 return ((DI->getDef() == NDI->getDef())
1176 && (DepVars.find(getName()) == DepVars.end()
1177 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +00001178 }
1179 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001180 return getLeafValue() == N->getLeafValue();
1181 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001182
Chris Lattner6cefb772008-01-05 22:25:12 +00001183 if (N->getOperator() != getOperator() ||
1184 N->getNumChildren() != getNumChildren()) return false;
1185 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00001186 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +00001187 return false;
1188 return true;
1189}
1190
1191/// clone - Make a copy of this tree and all of its children.
1192///
1193TreePatternNode *TreePatternNode::clone() const {
1194 TreePatternNode *New;
1195 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001196 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001197 } else {
1198 std::vector<TreePatternNode*> CChildren;
1199 CChildren.reserve(Children.size());
1200 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1201 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +00001202 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001203 }
1204 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001205 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +00001206 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00001207 New->setTransformFn(getTransformFn());
1208 return New;
1209}
1210
Chris Lattner47661322010-02-14 22:22:58 +00001211/// RemoveAllTypes - Recursively strip all the types of this tree.
1212void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +00001213 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1214 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +00001215 if (isLeaf()) return;
1216 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1217 getChild(i)->RemoveAllTypes();
1218}
1219
1220
Chris Lattner6cefb772008-01-05 22:25:12 +00001221/// SubstituteFormalArguments - Replace the formal arguments in this tree
1222/// with actual values specified by ArgMap.
1223void TreePatternNode::
1224SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1225 if (isLeaf()) return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001226
Chris Lattner6cefb772008-01-05 22:25:12 +00001227 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1228 TreePatternNode *Child = getChild(i);
1229 if (Child->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001230 Init *Val = Child->getLeafValue();
Sean Silva3f7b7f82012-10-10 20:24:47 +00001231 if (isa<DefInit>(Val) &&
1232 cast<DefInit>(Val)->getDef()->getName() == "node") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001233 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +00001234 TreePatternNode *NewChild = ArgMap[Child->getName()];
1235 assert(NewChild && "Couldn't find formal argument!");
1236 assert((Child->getPredicateFns().empty() ||
1237 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1238 "Non-empty child predicate clobbered!");
1239 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +00001240 }
1241 } else {
1242 getChild(i)->SubstituteFormalArguments(ArgMap);
1243 }
1244 }
1245}
1246
1247
1248/// InlinePatternFragments - If this pattern refers to any pattern
1249/// fragments, inline them into place, giving us a pattern without any
1250/// PatFrag references.
1251TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001252 if (TP.hasError())
Kaelyn Uhrain50a61022012-10-25 21:25:08 +00001253 return 0;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001254
1255 if (isLeaf())
1256 return this; // nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001257 Record *Op = getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001258
Chris Lattner6cefb772008-01-05 22:25:12 +00001259 if (!Op->isSubClassOf("PatFrag")) {
1260 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00001261 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1262 TreePatternNode *Child = getChild(i);
1263 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1264
1265 assert((Child->getPredicateFns().empty() ||
1266 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1267 "Non-empty child predicate clobbered!");
1268
1269 setChild(i, NewChild);
1270 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001271 return this;
1272 }
1273
1274 // Otherwise, we found a reference to a fragment. First, look up its
1275 // TreePattern record.
1276 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001277
Chris Lattner6cefb772008-01-05 22:25:12 +00001278 // Verify that we are passing the right number of operands.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001279 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001280 TP.error("'" + Op->getName() + "' fragment requires " +
1281 utostr(Frag->getNumArgs()) + " operands!");
Kaelyn Uhrain50a61022012-10-25 21:25:08 +00001282 return 0;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001283 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001284
1285 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1286
Chris Lattner54379062011-04-17 21:38:24 +00001287 TreePredicateFn PredFn(Frag);
1288 if (!PredFn.isAlwaysTrue())
1289 FragTree->addPredicateFn(PredFn);
Dan Gohman0540e172008-10-15 06:17:21 +00001290
Chris Lattner6cefb772008-01-05 22:25:12 +00001291 // Resolve formal arguments to their actual value.
1292 if (Frag->getNumArgs()) {
1293 // Compute the map of formal to actual arguments.
1294 std::map<std::string, TreePatternNode*> ArgMap;
1295 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1296 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001297
Chris Lattner6cefb772008-01-05 22:25:12 +00001298 FragTree->SubstituteFormalArguments(ArgMap);
1299 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001300
Chris Lattner6cefb772008-01-05 22:25:12 +00001301 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001302 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1303 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +00001304
1305 // Transfer in the old predicates.
1306 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1307 FragTree->addPredicateFn(getPredicateFns()[i]);
1308
Chris Lattner6cefb772008-01-05 22:25:12 +00001309 // Get a new copy of this fragment to stitch into here.
1310 //delete this; // FIXME: implement refcounting!
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001311
Chris Lattner2ca698d2008-06-30 03:02:03 +00001312 // The fragment we inlined could have recursive inlining that is needed. See
1313 // if there are any pattern fragments in it and inline them as needed.
1314 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001315}
1316
1317/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +00001318/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +00001319/// references from the register file information, for example.
1320///
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00001321/// When Unnamed is set, return the type of a DAG operand with no name, such as
1322/// the F8RC register class argument in:
1323///
1324/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1325///
1326/// When Unnamed is false, return the type of a named DAG operand such as the
1327/// GPR:$src operand above.
1328///
Chris Lattnerd7349192010-03-19 21:37:09 +00001329static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00001330 bool NotRegisters,
1331 bool Unnamed,
1332 TreePattern &TP) {
Owen Andersonbea6f612011-06-27 21:06:21 +00001333 // Check to see if this is a register operand.
1334 if (R->isSubClassOf("RegisterOperand")) {
1335 assert(ResNo == 0 && "Regoperand ref only has one result!");
1336 if (NotRegisters)
1337 return EEVT::TypeSet(); // Unknown.
1338 Record *RegClass = R->getValueAsDef("RegClass");
1339 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1340 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1341 }
1342
Chris Lattner2cacec52010-03-15 06:00:16 +00001343 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00001344 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001345 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00001346 // An unnamed register class represents itself as an i32 immediate, for
1347 // example on a COPY_TO_REGCLASS instruction.
1348 if (Unnamed)
1349 return EEVT::TypeSet(MVT::i32, TP);
1350
1351 // In a named operand, the register class provides the possible set of
1352 // types.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001353 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001354 return EEVT::TypeSet(); // Unknown.
1355 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1356 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001357 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001358
Chris Lattner640a3f52010-03-23 23:50:31 +00001359 if (R->isSubClassOf("PatFrag")) {
1360 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001361 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001362 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001363 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001364
Chris Lattner640a3f52010-03-23 23:50:31 +00001365 if (R->isSubClassOf("Register")) {
1366 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001367 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001368 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001369 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001370 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001371 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00001372
1373 if (R->isSubClassOf("SubRegIndex")) {
1374 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1375 return EEVT::TypeSet();
1376 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001377
Jakob Stoklund Olesenf0a804d2013-03-23 20:35:01 +00001378 if (R->isSubClassOf("ValueType")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001379 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesenf0a804d2013-03-23 20:35:01 +00001380 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1381 //
1382 // (sext_inreg GPR:$src, i16)
1383 // ~~~
1384 if (Unnamed)
1385 return EEVT::TypeSet(MVT::Other, TP);
1386 // With a name, the ValueType simply provides the type of the named
1387 // variable.
1388 //
1389 // (sext_inreg i32:$src, i16)
1390 // ~~~~~~~~
Jakob Stoklund Olesen19209962013-03-24 00:56:16 +00001391 if (NotRegisters)
1392 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesenf0a804d2013-03-23 20:35:01 +00001393 return EEVT::TypeSet(getValueType(R), TP);
1394 }
1395
1396 if (R->isSubClassOf("CondCode")) {
1397 assert(ResNo == 0 && "This node only has one result!");
1398 // Using a CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001399 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001400 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001401
Chris Lattner640a3f52010-03-23 23:50:31 +00001402 if (R->isSubClassOf("ComplexPattern")) {
1403 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001404 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001405 return EEVT::TypeSet(); // Unknown.
1406 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1407 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001408 }
1409 if (R->isSubClassOf("PointerLikeRegClass")) {
1410 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001411 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001412 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001413
Chris Lattner640a3f52010-03-23 23:50:31 +00001414 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1415 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001416 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001417 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001418 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001419
Chris Lattner6cefb772008-01-05 22:25:12 +00001420 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001421 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001422}
1423
Chris Lattnere67bde52008-01-06 05:36:50 +00001424
1425/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1426/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1427const CodeGenIntrinsic *TreePatternNode::
1428getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1429 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1430 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1431 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1432 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001433
Sean Silva3f7b7f82012-10-10 20:24:47 +00001434 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattnere67bde52008-01-06 05:36:50 +00001435 return &CDP.getIntrinsicInfo(IID);
1436}
1437
Chris Lattner47661322010-02-14 22:22:58 +00001438/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1439/// return the ComplexPattern information, otherwise return null.
1440const ComplexPattern *
1441TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1442 if (!isLeaf()) return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001443
Sean Silva6cfc8062012-10-10 20:24:43 +00001444 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
Chris Lattner47661322010-02-14 22:22:58 +00001445 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1446 return &CGP.getComplexPattern(DI->getDef());
1447 return 0;
1448}
1449
1450/// NodeHasProperty - Return true if this node has the specified property.
1451bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001452 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001453 if (isLeaf()) {
1454 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1455 return CP->hasProperty(Property);
1456 return false;
1457 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001458
Chris Lattner47661322010-02-14 22:22:58 +00001459 Record *Operator = getOperator();
1460 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001461
Chris Lattner47661322010-02-14 22:22:58 +00001462 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1463}
1464
1465
1466
1467
1468/// TreeHasProperty - Return true if any node in this tree has the specified
1469/// property.
1470bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001471 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001472 if (NodeHasProperty(Property, CGP))
1473 return true;
1474 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1475 if (getChild(i)->TreeHasProperty(Property, CGP))
1476 return true;
1477 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001478}
Chris Lattner47661322010-02-14 22:22:58 +00001479
Evan Cheng6bd95672008-06-16 20:29:38 +00001480/// isCommutativeIntrinsic - Return true if the node corresponds to a
1481/// commutative intrinsic.
1482bool
1483TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1484 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1485 return Int->isCommutative;
1486 return false;
1487}
1488
Chris Lattnere67bde52008-01-06 05:36:50 +00001489
Bob Wilson6c01ca92009-01-05 17:23:09 +00001490/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001491/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001492/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner6cefb772008-01-05 22:25:12 +00001493bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001494 if (TP.hasError())
1495 return false;
1496
Chris Lattnerfe718932008-01-06 01:10:31 +00001497 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001498 if (isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00001499 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001500 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001501 bool MadeChange = false;
1502 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1503 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00001504 NotRegisters,
1505 !hasName(), TP), TP);
Chris Lattnerd7349192010-03-19 21:37:09 +00001506 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001507 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001508
Sean Silva6cfc8062012-10-10 20:24:43 +00001509 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001510 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001511
Chris Lattnerd7349192010-03-19 21:37:09 +00001512 // Int inits are always integers. :)
1513 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001514
Chris Lattnerd7349192010-03-19 21:37:09 +00001515 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001516 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001517
Chris Lattnerd7349192010-03-19 21:37:09 +00001518 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001519 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1520 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001521
Craig Topper49909412013-09-25 06:37:18 +00001522 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattner2cacec52010-03-15 06:00:16 +00001523 // Make sure that the value is representable for this type.
1524 if (Size >= 32) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001525
Richard Smith1144af32012-08-24 23:29:28 +00001526 // Check that the value doesn't use more bits than we have. It must either
1527 // be a sign- or zero-extended equivalent of the original.
1528 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1529 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattner2cacec52010-03-15 06:00:16 +00001530 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001531
Richard Smith1144af32012-08-24 23:29:28 +00001532 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerd7349192010-03-19 21:37:09 +00001533 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001534 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +00001535 }
1536 return false;
1537 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001538
Chris Lattner6cefb772008-01-05 22:25:12 +00001539 // special handling for set, which isn't really an SDNode.
1540 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001541 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1542 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001543 unsigned NC = getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001544
Chris Lattnerd7349192010-03-19 21:37:09 +00001545 TreePatternNode *SetVal = getChild(NC-1);
1546 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1547
Chris Lattner6cefb772008-01-05 22:25:12 +00001548 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001549 TreePatternNode *Child = getChild(i);
1550 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001551
Chris Lattner6cefb772008-01-05 22:25:12 +00001552 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001553 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1554 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001555 }
1556 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001557 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001558
Chris Lattner310adf12010-03-27 02:53:27 +00001559 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001560 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1561
Chris Lattner6cefb772008-01-05 22:25:12 +00001562 bool MadeChange = false;
1563 for (unsigned i = 0; i < getNumChildren(); ++i)
1564 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001565 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001566 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001567
Chris Lattner6eb30122010-02-23 05:51:07 +00001568 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001569 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001570
Chris Lattner6cefb772008-01-05 22:25:12 +00001571 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001572 unsigned NumRetVTs = Int->IS.RetVTs.size();
1573 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001574
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001575 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001576 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001577
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001578 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattnere67bde52008-01-06 05:36:50 +00001579 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001580 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001581 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001582 return false;
1583 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001584
1585 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001586 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001587
Chris Lattnerd7349192010-03-19 21:37:09 +00001588 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1589 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001590
Chris Lattnerd7349192010-03-19 21:37:09 +00001591 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1592 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1593 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001594 }
1595 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001596 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001597
Chris Lattner6eb30122010-02-23 05:51:07 +00001598 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001599 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001600
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001601 // Check that the number of operands is sane. Negative operands -> varargs.
1602 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001603 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001604 TP.error(getOperator()->getName() + " node requires exactly " +
1605 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001606 return false;
1607 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001608
Chris Lattner6cefb772008-01-05 22:25:12 +00001609 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1610 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1611 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001612 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001613 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001614
Chris Lattner6eb30122010-02-23 05:51:07 +00001615 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001616 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001617 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001618 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001619
Chris Lattner0be6fe72010-03-27 19:15:02 +00001620 bool MadeChange = false;
1621
1622 // Apply the result types to the node, these come from the things in the
1623 // (outs) list of the instruction.
1624 // FIXME: Cap at one result so far.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001625 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +00001626 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1627 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001628
Chris Lattner0be6fe72010-03-27 19:15:02 +00001629 // If the instruction has implicit defs, we apply the first one as a result.
1630 // FIXME: This sucks, it should apply all implicit defs.
1631 if (!InstInfo.ImplicitDefs.empty()) {
1632 unsigned ResNo = NumResultsToAdd;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001633
Chris Lattner9414ae52010-03-27 20:09:24 +00001634 // FIXME: Generalize to multiple possible types and multiple possible
1635 // ImplicitDefs.
1636 MVT::SimpleValueType VT =
1637 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001638
Chris Lattner9414ae52010-03-27 20:09:24 +00001639 if (VT != MVT::Other)
1640 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001641 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001642
Chris Lattner2cacec52010-03-15 06:00:16 +00001643 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1644 // be the same.
1645 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001646 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1647 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1648 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001649 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001650
1651 unsigned ChildNo = 0;
1652 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1653 Record *OperandNode = Inst.getOperand(i);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001654
Chris Lattner6cefb772008-01-05 22:25:12 +00001655 // If the instruction expects a predicate or optional def operand, we
1656 // codegen this by setting the operand to it's default value if it has a
1657 // non-empty DefaultOps field.
Tom Stellard6d3d7652012-09-06 14:15:52 +00001658 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001659 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1660 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001661
Chris Lattner6cefb772008-01-05 22:25:12 +00001662 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001663 if (ChildNo >= getNumChildren()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001664 TP.error("Instruction '" + getOperator()->getName() +
1665 "' expects more operands than were provided.");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001666 return false;
1667 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001668
Chris Lattner6cefb772008-01-05 22:25:12 +00001669 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001670 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigandec8d1a52013-03-19 19:51:09 +00001671
1672 // If the operand has sub-operands, they may be provided by distinct
1673 // child patterns, so attempt to match each sub-operand separately.
1674 if (OperandNode->isSubClassOf("Operand")) {
1675 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1676 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1677 // But don't do that if the whole operand is being provided by
1678 // a single ComplexPattern.
1679 const ComplexPattern *AM = Child->getComplexPatternInfo(CDP);
1680 if (!AM || AM->getNumOperands() < NumArgs) {
1681 // Match first sub-operand against the child we already have.
1682 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1683 MadeChange |=
1684 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1685
1686 // And the remaining sub-operands against subsequent children.
1687 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1688 if (ChildNo >= getNumChildren()) {
1689 TP.error("Instruction '" + getOperator()->getName() +
1690 "' expects more operands than were provided.");
1691 return false;
1692 }
1693 Child = getChild(ChildNo++);
1694
1695 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1696 MadeChange |=
1697 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1698 }
1699 continue;
1700 }
1701 }
1702 }
1703
1704 // If we didn't match by pieces above, attempt to match the whole
1705 // operand now.
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +00001706 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001707 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001708
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001709 if (ChildNo != getNumChildren()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001710 TP.error("Instruction '" + getOperator()->getName() +
1711 "' was provided too many operands!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001712 return false;
1713 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001714
Ulrich Weigandec8d1a52013-03-19 19:51:09 +00001715 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1716 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001717 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001718 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001719
Chris Lattner6eb30122010-02-23 05:51:07 +00001720 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001721
Chris Lattner6eb30122010-02-23 05:51:07 +00001722 // Node transforms always take one operand.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001723 if (getNumChildren() != 1) {
Chris Lattner6eb30122010-02-23 05:51:07 +00001724 TP.error("Node transform '" + getOperator()->getName() +
1725 "' requires one operand!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001726 return false;
1727 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001728
Chris Lattner2cacec52010-03-15 06:00:16 +00001729 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1730
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001731
Chris Lattner6eb30122010-02-23 05:51:07 +00001732 // If either the output or input of the xform does not have exact
1733 // type info. We assume they must be the same. Otherwise, it is perfectly
1734 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001735#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001736 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001737 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1738 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001739 return MadeChange;
1740 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001741#endif
1742 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001743}
1744
1745/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1746/// RHS of a commutative operation, not the on LHS.
1747static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1748 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1749 return true;
Sean Silva3f7b7f82012-10-10 20:24:47 +00001750 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner6cefb772008-01-05 22:25:12 +00001751 return true;
1752 return false;
1753}
1754
1755
1756/// canPatternMatch - If it is impossible for this pattern to match on this
1757/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001758/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001759/// that can never possibly work), and to prevent the pattern permuter from
1760/// generating stuff that is useless.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001761bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001762 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001763 if (isLeaf()) return true;
1764
1765 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1766 if (!getChild(i)->canPatternMatch(Reason, CDP))
1767 return false;
1768
1769 // If this is an intrinsic, handle cases that would make it not match. For
1770 // example, if an operand is required to be an immediate.
1771 if (getOperator()->isSubClassOf("Intrinsic")) {
1772 // TODO:
1773 return true;
1774 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001775
Chris Lattner6cefb772008-01-05 22:25:12 +00001776 // If this node is a commutative operator, check that the LHS isn't an
1777 // immediate.
1778 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001779 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1780 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001781 // Scan all of the operands of the node and make sure that only the last one
1782 // is a constant node, unless the RHS also is.
1783 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001784 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1785 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001786 if (OnlyOnRHSOfCommutative(getChild(i))) {
1787 Reason="Immediate value must be on the RHS of commutative operators!";
1788 return false;
1789 }
1790 }
1791 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001792
Chris Lattner6cefb772008-01-05 22:25:12 +00001793 return true;
1794}
1795
1796//===----------------------------------------------------------------------===//
1797// TreePattern implementation
1798//
1799
David Greene05bce0b2011-07-29 22:43:06 +00001800TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001801 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1802 isInputPattern(isInput), HasError(false) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001803 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattnerc2173052010-03-28 06:50:34 +00001804 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001805}
1806
David Greene05bce0b2011-07-29 22:43:06 +00001807TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001808 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1809 isInputPattern(isInput), HasError(false) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001810 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001811}
1812
1813TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001814 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1815 isInputPattern(isInput), HasError(false) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001816 Trees.push_back(Pat);
1817}
1818
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001819void TreePattern::error(const std::string &Msg) {
1820 if (HasError)
1821 return;
Chris Lattner6cefb772008-01-05 22:25:12 +00001822 dump();
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001823 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1824 HasError = true;
Chris Lattner6cefb772008-01-05 22:25:12 +00001825}
1826
Chris Lattner2cacec52010-03-15 06:00:16 +00001827void TreePattern::ComputeNamedNodes() {
1828 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1829 ComputeNamedNodes(Trees[i]);
1830}
1831
1832void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1833 if (!N->getName().empty())
1834 NamedNodes[N->getName()].push_back(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001835
Chris Lattner2cacec52010-03-15 06:00:16 +00001836 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1837 ComputeNamedNodes(N->getChild(i));
1838}
1839
Chris Lattnerd7349192010-03-19 21:37:09 +00001840
David Greene05bce0b2011-07-29 22:43:06 +00001841TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silva6cfc8062012-10-10 20:24:43 +00001842 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001843 Record *R = DI->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001844
Chris Lattnerc2173052010-03-28 06:50:34 +00001845 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbach66c9ee72011-07-06 23:38:13 +00001846 // TreePatternNode of its own. For example:
Chris Lattnerc2173052010-03-28 06:50:34 +00001847 /// (foo GPR, imm) -> (foo GPR, (imm))
1848 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenedcd35c72011-07-29 19:07:07 +00001849 return ParseTreePattern(
1850 DagInit::get(DI, "",
David Greene05bce0b2011-07-29 22:43:06 +00001851 std::vector<std::pair<Init*, std::string> >()),
David Greenedcd35c72011-07-29 19:07:07 +00001852 OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001853
Chris Lattnerc2173052010-03-28 06:50:34 +00001854 // Input argument?
1855 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001856 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001857 if (OpName.empty())
1858 error("'node' argument requires a name to match with operand list");
1859 Args.push_back(OpName);
1860 }
1861
1862 Res->setName(OpName);
1863 return Res;
1864 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001865
Jakob Stoklund Olesen8e3cb3e2013-03-24 19:37:00 +00001866 // ?:$name or just $name.
1867 if (TheInit == UnsetInit::get()) {
1868 if (OpName.empty())
1869 error("'?' argument requires a name to match with operand list");
1870 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
1871 Args.push_back(OpName);
1872 Res->setName(OpName);
1873 return Res;
1874 }
1875
Sean Silva6cfc8062012-10-10 20:24:43 +00001876 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001877 if (!OpName.empty())
1878 error("Constant int argument should not have a name!");
1879 return new TreePatternNode(II, 1);
1880 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001881
Sean Silva6cfc8062012-10-10 20:24:43 +00001882 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001883 // Turn this into an IntInit.
David Greene05bce0b2011-07-29 22:43:06 +00001884 Init *II = BI->convertInitializerTo(IntRecTy::get());
Sean Silva3f7b7f82012-10-10 20:24:47 +00001885 if (II == 0 || !isa<IntInit>(II))
Chris Lattnerc2173052010-03-28 06:50:34 +00001886 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001887 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00001888 }
1889
Sean Silva6cfc8062012-10-10 20:24:43 +00001890 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattnerc2173052010-03-28 06:50:34 +00001891 if (!Dag) {
1892 TheInit->dump();
1893 error("Pattern has unexpected init kind!");
1894 }
Sean Silva6cfc8062012-10-10 20:24:43 +00001895 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001896 if (!OpDef) error("Pattern has unexpected operator type!");
1897 Record *Operator = OpDef->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001898
Chris Lattner6cefb772008-01-05 22:25:12 +00001899 if (Operator->isSubClassOf("ValueType")) {
1900 // If the operator is a ValueType, then this must be "type cast" of a leaf
1901 // node.
1902 if (Dag->getNumArgs() != 1)
1903 error("Type cast only takes one operand!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001904
Chris Lattnerc2173052010-03-28 06:50:34 +00001905 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001906
Chris Lattner6cefb772008-01-05 22:25:12 +00001907 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001908 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1909 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001910
Chris Lattnerc2173052010-03-28 06:50:34 +00001911 if (!OpName.empty())
1912 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001913 return New;
1914 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001915
Chris Lattner6cefb772008-01-05 22:25:12 +00001916 // Verify that this is something that makes sense for an operator.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001917 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begeman7cee8172009-03-19 05:21:56 +00001918 !Operator->isSubClassOf("SDNode") &&
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001919 !Operator->isSubClassOf("Instruction") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001920 !Operator->isSubClassOf("SDNodeXForm") &&
1921 !Operator->isSubClassOf("Intrinsic") &&
1922 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001923 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001924 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001925
Chris Lattner6cefb772008-01-05 22:25:12 +00001926 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001927 if (isInputPattern) {
1928 if (Operator->isSubClassOf("Instruction") ||
1929 Operator->isSubClassOf("SDNodeXForm"))
1930 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1931 } else {
1932 if (Operator->isSubClassOf("Intrinsic"))
1933 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001934
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001935 if (Operator->isSubClassOf("SDNode") &&
1936 Operator->getName() != "imm" &&
1937 Operator->getName() != "fpimm" &&
1938 Operator->getName() != "tglobaltlsaddr" &&
1939 Operator->getName() != "tconstpool" &&
1940 Operator->getName() != "tjumptable" &&
1941 Operator->getName() != "tframeindex" &&
1942 Operator->getName() != "texternalsym" &&
1943 Operator->getName() != "tblockaddress" &&
1944 Operator->getName() != "tglobaladdr" &&
1945 Operator->getName() != "bb" &&
1946 Operator->getName() != "vt")
1947 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1948 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001949
Chris Lattner6cefb772008-01-05 22:25:12 +00001950 std::vector<TreePatternNode*> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00001951
1952 // Parse all the operands.
1953 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1954 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001955
Chris Lattner6cefb772008-01-05 22:25:12 +00001956 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001957 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner6cefb772008-01-05 22:25:12 +00001958 // convert the intrinsic name to a number.
1959 if (Operator->isSubClassOf("Intrinsic")) {
1960 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1961 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1962
1963 // If this intrinsic returns void, it must have side-effects and thus a
1964 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00001965 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001966 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001967 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00001968 // Has side-effects, requires chain.
1969 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001970 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00001971 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001972
David Greenedcd35c72011-07-29 19:07:07 +00001973 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001974 Children.insert(Children.begin(), IIDNode);
1975 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001976
Chris Lattnerd7349192010-03-19 21:37:09 +00001977 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1978 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00001979 Result->setName(OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001980
Chris Lattnerc2173052010-03-28 06:50:34 +00001981 if (!Dag->getName().empty()) {
1982 assert(Result->getName().empty());
1983 Result->setName(Dag->getName());
1984 }
Nate Begeman7cee8172009-03-19 05:21:56 +00001985 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001986}
1987
Chris Lattner7a0eb912010-03-28 08:38:32 +00001988/// SimplifyTree - See if we can simplify this tree to eliminate something that
1989/// will never match in favor of something obvious that will. This is here
1990/// strictly as a convenience to target authors because it allows them to write
1991/// more type generic things and have useless type casts fold away.
1992///
1993/// This returns true if any change is made.
1994static bool SimplifyTree(TreePatternNode *&N) {
1995 if (N->isLeaf())
1996 return false;
1997
1998 // If we have a bitconvert with a resolved type and if the source and
1999 // destination types are the same, then the bitconvert is useless, remove it.
2000 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattner7a0eb912010-03-28 08:38:32 +00002001 N->getExtType(0).isConcrete() &&
2002 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2003 N->getName().empty()) {
2004 N = N->getChild(0);
2005 SimplifyTree(N);
2006 return true;
2007 }
2008
2009 // Walk all children.
2010 bool MadeChange = false;
2011 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2012 TreePatternNode *Child = N->getChild(i);
2013 MadeChange |= SimplifyTree(Child);
2014 N->setChild(i, Child);
2015 }
2016 return MadeChange;
2017}
2018
2019
2020
Chris Lattner6cefb772008-01-05 22:25:12 +00002021/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00002022/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002023/// otherwise. Flags an error if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00002024bool TreePattern::
2025InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2026 if (NamedNodes.empty())
2027 ComputeNamedNodes();
2028
Chris Lattner6cefb772008-01-05 22:25:12 +00002029 bool MadeChange = true;
2030 while (MadeChange) {
2031 MadeChange = false;
Chris Lattner7a0eb912010-03-28 08:38:32 +00002032 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002033 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner7a0eb912010-03-28 08:38:32 +00002034 MadeChange |= SimplifyTree(Trees[i]);
2035 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002036
2037 // If there are constraints on our named nodes, apply them.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002038 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattner2cacec52010-03-15 06:00:16 +00002039 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2040 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002041
Chris Lattner2cacec52010-03-15 06:00:16 +00002042 // If we have input named node types, propagate their types to the named
2043 // values here.
2044 if (InNamedTypes) {
2045 // FIXME: Should be error?
2046 assert(InNamedTypes->count(I->getKey()) &&
2047 "Named node in output pattern but not input pattern?");
2048
2049 const SmallVectorImpl<TreePatternNode*> &InNodes =
2050 InNamedTypes->find(I->getKey())->second;
2051
2052 // The input types should be fully resolved by now.
2053 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2054 // If this node is a register class, and it is the root of the pattern
2055 // then we're mapping something onto an input register. We allow
2056 // changing the type of the input register in this case. This allows
2057 // us to match things like:
2058 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2059 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002060 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00002061 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2062 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner2cacec52010-03-15 06:00:16 +00002063 continue;
2064 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002065
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00002066 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00002067 InNodes[0]->getNumTypes() == 1 &&
2068 "FIXME: cannot name multiple result nodes yet");
2069 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2070 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002071 }
2072 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002073
Chris Lattner2cacec52010-03-15 06:00:16 +00002074 // If there are multiple nodes with the same name, they must all have the
2075 // same type.
2076 if (I->second.size() > 1) {
2077 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002078 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00002079 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00002080 "FIXME: cannot name multiple result nodes yet");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002081
Chris Lattnerd7349192010-03-19 21:37:09 +00002082 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2083 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002084 }
2085 }
2086 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002087 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002088
Chris Lattner6cefb772008-01-05 22:25:12 +00002089 bool HasUnresolvedTypes = false;
2090 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2091 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2092 return !HasUnresolvedTypes;
2093}
2094
Daniel Dunbar1a551802009-07-03 00:10:29 +00002095void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00002096 OS << getRecord()->getName();
2097 if (!Args.empty()) {
2098 OS << "(" << Args[0];
2099 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2100 OS << ", " << Args[i];
2101 OS << ")";
2102 }
2103 OS << ": ";
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002104
Chris Lattner6cefb772008-01-05 22:25:12 +00002105 if (Trees.size() > 1)
2106 OS << "[\n";
2107 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2108 OS << "\t";
2109 Trees[i]->print(OS);
2110 OS << "\n";
2111 }
2112
2113 if (Trees.size() > 1)
2114 OS << "]\n";
2115}
2116
Daniel Dunbar1a551802009-07-03 00:10:29 +00002117void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00002118
2119//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00002120// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00002121//
2122
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002123CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner67db8832010-12-13 00:23:57 +00002124 Records(R), Target(R) {
2125
Dale Johannesen49de9822009-02-05 01:49:45 +00002126 Intrinsics = LoadIntrinsics(Records, false);
2127 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00002128 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00002129 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00002130 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002131 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00002132 ParseDefaultOperands();
2133 ParseInstructions();
2134 ParsePatterns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002135
Chris Lattner6cefb772008-01-05 22:25:12 +00002136 // Generate variants. For example, commutative patterns can match
2137 // multiple ways. Add them to PatternsToMatch as well.
2138 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00002139
2140 // Infer instruction flags. For example, we can detect loads,
2141 // stores, and side effects in many cases by examining an
2142 // instruction's pattern.
2143 InferInstructionFlags();
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00002144
2145 // Verify that instruction flags match the patterns.
2146 VerifyInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00002147}
2148
Chris Lattnerfe718932008-01-06 01:10:31 +00002149CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002150 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002151 E = PatternFragments.end(); I != E; ++I)
2152 delete I->second;
2153}
2154
2155
Chris Lattnerfe718932008-01-06 01:10:31 +00002156Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00002157 Record *N = Records.getDef(Name);
2158 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002159 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00002160 exit(1);
2161 }
2162 return N;
2163}
2164
2165// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00002166void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002167 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2168 while (!Nodes.empty()) {
2169 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2170 Nodes.pop_back();
2171 }
2172
Jim Grosbachda4231f2009-03-26 16:17:51 +00002173 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00002174 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2175 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2176 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2177}
2178
2179/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2180/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002181void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002182 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2183 while (!Xforms.empty()) {
2184 Record *XFormNode = Xforms.back();
2185 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +00002186 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00002187 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002188
2189 Xforms.pop_back();
2190 }
2191}
2192
Chris Lattnerfe718932008-01-06 01:10:31 +00002193void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002194 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2195 while (!AMs.empty()) {
2196 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2197 AMs.pop_back();
2198 }
2199}
2200
2201
2202/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2203/// file, building up the PatternFragments map. After we've collected them all,
2204/// inline fragments together as necessary, so that there are no references left
2205/// inside a pattern fragment to a pattern fragment.
2206///
Chris Lattnerfe718932008-01-06 01:10:31 +00002207void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002208 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002209
Chris Lattnerdc32f982008-01-05 22:43:57 +00002210 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002211 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00002212 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattner6cefb772008-01-05 22:25:12 +00002213 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2214 PatternFragments[Fragments[i]] = P;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002215
Chris Lattnerdc32f982008-01-05 22:43:57 +00002216 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00002217 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002218 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002219
Chris Lattnerdc32f982008-01-05 22:43:57 +00002220 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00002221 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002222
Chris Lattner6cefb772008-01-05 22:25:12 +00002223 // Parse the operands list.
David Greene05bce0b2011-07-29 22:43:06 +00002224 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Sean Silva6cfc8062012-10-10 20:24:43 +00002225 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00002226 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00002227 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00002228 if (!OpsOp ||
2229 (OpsOp->getDef()->getName() != "ops" &&
2230 OpsOp->getDef()->getName() != "outs" &&
2231 OpsOp->getDef()->getName() != "ins"))
2232 P->error("Operands list should start with '(ops ... '!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002233
2234 // Copy over the arguments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002235 Args.clear();
2236 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva3f7b7f82012-10-10 20:24:47 +00002237 if (!isa<DefInit>(OpsList->getArg(j)) ||
2238 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner6cefb772008-01-05 22:25:12 +00002239 P->error("Operands list should all be 'node' values.");
2240 if (OpsList->getArgName(j).empty())
2241 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002242 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00002243 P->error("'" + OpsList->getArgName(j) +
2244 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002245 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00002246 Args.push_back(OpsList->getArgName(j));
2247 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002248
Chris Lattnerdc32f982008-01-05 22:43:57 +00002249 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00002250 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00002251 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002252
Chris Lattnerdc32f982008-01-05 22:43:57 +00002253 // If there is a code init for this fragment, keep track of the fact that
2254 // this fragment uses it.
Chris Lattner54379062011-04-17 21:38:24 +00002255 TreePredicateFn PredFn(P);
2256 if (!PredFn.isAlwaysTrue())
2257 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002258
Chris Lattner6cefb772008-01-05 22:25:12 +00002259 // If there is a node transformation corresponding to this, keep track of
2260 // it.
2261 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2262 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2263 P->getOnlyTree()->setTransformFn(Transform);
2264 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002265
Chris Lattner6cefb772008-01-05 22:25:12 +00002266 // Now that we've parsed all of the tree fragments, do a closure on them so
2267 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00002268 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2269 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00002270 ThePat->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002271
Chris Lattner6cefb772008-01-05 22:25:12 +00002272 // Infer as many types as possible. Don't worry about it if we don't infer
2273 // all of them, some may depend on the inputs of the pattern.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002274 ThePat->InferAllTypes();
2275 ThePat->resetError();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002276
Chris Lattner6cefb772008-01-05 22:25:12 +00002277 // If debugging, print out the pattern fragment result.
2278 DEBUG(ThePat->dump());
2279 }
2280}
2281
Chris Lattnerfe718932008-01-06 01:10:31 +00002282void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellard6d3d7652012-09-06 14:15:52 +00002283 std::vector<Record*> DefaultOps;
2284 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner6cefb772008-01-05 22:25:12 +00002285
2286 // Find some SDNode.
2287 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greene05bce0b2011-07-29 22:43:06 +00002288 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002289
Tom Stellard6d3d7652012-09-06 14:15:52 +00002290 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2291 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002292
Tom Stellard6d3d7652012-09-06 14:15:52 +00002293 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2294 // SomeSDnode so that we can parse this.
2295 std::vector<std::pair<Init*, std::string> > Ops;
2296 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2297 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2298 DefaultInfo->getArgName(op)));
2299 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002300
Tom Stellard6d3d7652012-09-06 14:15:52 +00002301 // Create a TreePattern to parse this.
2302 TreePattern P(DefaultOps[i], DI, false, *this);
2303 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002304
Tom Stellard6d3d7652012-09-06 14:15:52 +00002305 // Copy the operands over into a DAGDefaultOperand.
2306 DAGDefaultOperand DefaultOpInfo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002307
Tom Stellard6d3d7652012-09-06 14:15:52 +00002308 TreePatternNode *T = P.getTree(0);
2309 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2310 TreePatternNode *TPN = T->getChild(op);
2311 while (TPN->ApplyTypeConstraints(P, false))
2312 /* Resolve all types */;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002313
Tom Stellard6d3d7652012-09-06 14:15:52 +00002314 if (TPN->ContainsUnresolvedType()) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002315 PrintFatalError("Value #" + utostr(i) + " of OperandWithDefaultOps '" +
2316 DefaultOps[i]->getName() +"' doesn't have a concrete type!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002317 }
Tom Stellard6d3d7652012-09-06 14:15:52 +00002318 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner6cefb772008-01-05 22:25:12 +00002319 }
Tom Stellard6d3d7652012-09-06 14:15:52 +00002320
2321 // Insert it into the DefaultOperands map so we can find it later.
2322 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner6cefb772008-01-05 22:25:12 +00002323 }
2324}
2325
2326/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2327/// instruction input. Return true if this is a real use.
2328static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002329 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002330 // No name -> not interesting.
2331 if (Pat->getName().empty()) {
2332 if (Pat->isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002333 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00002334 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2335 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002336 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002337 }
2338 return false;
2339 }
2340
2341 Record *Rec;
2342 if (Pat->isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002343 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002344 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2345 Rec = DI->getDef();
2346 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00002347 Rec = Pat->getOperator();
2348 }
2349
2350 // SRCVALUE nodes are ignored.
2351 if (Rec->getName() == "srcvalue")
2352 return false;
2353
2354 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2355 if (!Slot) {
2356 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00002357 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00002358 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00002359 Record *SlotRec;
2360 if (Slot->isLeaf()) {
Sean Silva3f7b7f82012-10-10 20:24:47 +00002361 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattner53d09bd2010-02-23 05:59:10 +00002362 } else {
2363 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2364 SlotRec = Slot->getOperator();
2365 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002366
Chris Lattner53d09bd2010-02-23 05:59:10 +00002367 // Ensure that the inputs agree if we've already seen this input.
2368 if (Rec != SlotRec)
2369 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00002370 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00002371 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00002372 return true;
2373}
2374
2375/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2376/// part of "I", the instruction), computing the set of inputs and outputs of
2377/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00002378void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00002379FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2380 std::map<std::string, TreePatternNode*> &InstInputs,
2381 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner6cefb772008-01-05 22:25:12 +00002382 std::vector<Record*> &InstImpResults) {
2383 if (Pat->isLeaf()) {
Chris Lattneracfb70f2010-04-20 06:30:25 +00002384 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002385 if (!isUse && Pat->getTransformFn())
2386 I->error("Cannot specify a transform function for a non-input value!");
2387 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002388 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002389
Chris Lattner84aa60b2010-02-17 06:53:36 +00002390 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002391 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2392 TreePatternNode *Dest = Pat->getChild(i);
2393 if (!Dest->isLeaf())
2394 I->error("implicitly defined value should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002395
Sean Silva6cfc8062012-10-10 20:24:43 +00002396 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002397 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2398 I->error("implicitly defined value should be a register!");
2399 InstImpResults.push_back(Val->getDef());
2400 }
2401 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002402 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002403
Chris Lattner84aa60b2010-02-17 06:53:36 +00002404 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002405 // If this is not a set, verify that the children nodes are not void typed,
2406 // and recurse.
2407 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002408 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002409 I->error("Cannot have void nodes inside of patterns!");
2410 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002411 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002412 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002413
Chris Lattner6cefb772008-01-05 22:25:12 +00002414 // If this is a non-leaf node with no children, treat it basically as if
2415 // it were a leaf. This handles nodes like (imm).
Chris Lattneracfb70f2010-04-20 06:30:25 +00002416 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002417
Chris Lattner6cefb772008-01-05 22:25:12 +00002418 if (!isUse && Pat->getTransformFn())
2419 I->error("Cannot specify a transform function for a non-input value!");
2420 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002421 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002422
Chris Lattner6cefb772008-01-05 22:25:12 +00002423 // Otherwise, this is a set, validate and collect instruction results.
2424 if (Pat->getNumChildren() == 0)
2425 I->error("set requires operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002426
Chris Lattner6cefb772008-01-05 22:25:12 +00002427 if (Pat->getTransformFn())
2428 I->error("Cannot specify a transform function on a set node!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002429
Chris Lattner6cefb772008-01-05 22:25:12 +00002430 // Check the set destinations.
2431 unsigned NumDests = Pat->getNumChildren()-1;
2432 for (unsigned i = 0; i != NumDests; ++i) {
2433 TreePatternNode *Dest = Pat->getChild(i);
2434 if (!Dest->isLeaf())
2435 I->error("set destination should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002436
Sean Silva6cfc8062012-10-10 20:24:43 +00002437 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002438 if (!Val)
2439 I->error("set destination should be a register!");
2440
2441 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen19209962013-03-24 00:56:16 +00002442 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersonbea6f612011-06-27 21:06:21 +00002443 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002444 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002445 if (Dest->getName().empty())
2446 I->error("set destination must have a name!");
2447 if (InstResults.count(Dest->getName()))
2448 I->error("cannot set '" + Dest->getName() +"' multiple times");
2449 InstResults[Dest->getName()] = Dest;
2450 } else if (Val->getDef()->isSubClassOf("Register")) {
2451 InstImpResults.push_back(Val->getDef());
2452 } else {
2453 I->error("set destination should be a register!");
2454 }
2455 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002456
Chris Lattner6cefb772008-01-05 22:25:12 +00002457 // Verify and collect info from the computation.
2458 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattneracfb70f2010-04-20 06:30:25 +00002459 InstInputs, InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002460}
2461
Dan Gohmanee4fa192008-04-03 00:02:49 +00002462//===----------------------------------------------------------------------===//
2463// Instruction Analysis
2464//===----------------------------------------------------------------------===//
2465
2466class InstAnalyzer {
2467 const CodeGenDAGPatterns &CDP;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002468public:
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002469 bool hasSideEffects;
2470 bool mayStore;
2471 bool mayLoad;
2472 bool isBitcast;
2473 bool isVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002474
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002475 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2476 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2477 isBitcast(false), isVariadic(false) {}
Dan Gohmanee4fa192008-04-03 00:02:49 +00002478
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002479 void Analyze(const TreePattern *Pat) {
2480 // Assume only the first tree is the pattern. The others are clobber nodes.
2481 AnalyzeNode(Pat->getTree(0));
Dan Gohmanee4fa192008-04-03 00:02:49 +00002482 }
2483
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00002484 void Analyze(const PatternToMatch *Pat) {
2485 AnalyzeNode(Pat->getSrcPattern());
2486 }
2487
Dan Gohmanee4fa192008-04-03 00:02:49 +00002488private:
Evan Cheng0f040a22011-03-15 05:09:26 +00002489 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002490 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng0f040a22011-03-15 05:09:26 +00002491 return false;
2492
2493 if (N->getNumChildren() != 2)
2494 return false;
2495
2496 const TreePatternNode *N0 = N->getChild(0);
Sean Silva3f7b7f82012-10-10 20:24:47 +00002497 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng0f040a22011-03-15 05:09:26 +00002498 return false;
2499
2500 const TreePatternNode *N1 = N->getChild(1);
2501 if (N1->isLeaf())
2502 return false;
2503 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2504 return false;
2505
2506 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2507 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2508 return false;
2509 return OpInfo.getEnumName() == "ISD::BITCAST";
2510 }
2511
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00002512public:
Dan Gohmanee4fa192008-04-03 00:02:49 +00002513 void AnalyzeNode(const TreePatternNode *N) {
2514 if (N->isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002515 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002516 Record *LeafRec = DI->getDef();
2517 // Handle ComplexPattern leaves.
2518 if (LeafRec->isSubClassOf("ComplexPattern")) {
2519 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2520 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2521 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002522 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002523 }
2524 }
2525 return;
2526 }
2527
2528 // Analyze children.
2529 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2530 AnalyzeNode(N->getChild(i));
2531
2532 // Ignore set nodes, which are not SDNodes.
Evan Cheng0f040a22011-03-15 05:09:26 +00002533 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002534 isBitcast = IsNodeBitcast(N);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002535 return;
Evan Cheng0f040a22011-03-15 05:09:26 +00002536 }
Dan Gohmanee4fa192008-04-03 00:02:49 +00002537
2538 // Get information about the SDNode for the operator.
2539 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2540
2541 // Notice properties of the node.
2542 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2543 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002544 if (OpInfo.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2545 if (OpInfo.hasProperty(SDNPVariadic)) isVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002546
2547 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2548 // If this is an intrinsic, analyze it.
2549 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2550 mayLoad = true;// These may load memory.
2551
Dan Gohman7365c092010-08-05 23:36:21 +00002552 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002553 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2554
Dan Gohman7365c092010-08-05 23:36:21 +00002555 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002556 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002557 hasSideEffects = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002558 }
2559 }
2560
2561};
2562
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002563static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002564 const InstAnalyzer &PatInfo,
2565 Record *PatDef) {
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002566 bool Error = false;
2567
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002568 // Remember where InstInfo got its flags.
2569 if (InstInfo.hasUndefFlags())
2570 InstInfo.InferredFrom = PatDef;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002571
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002572 // Check explicitly set flags for consistency.
2573 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2574 !InstInfo.hasSideEffects_Unset) {
2575 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2576 // the pattern has no side effects. That could be useful for div/rem
2577 // instructions that may trap.
2578 if (!InstInfo.hasSideEffects) {
2579 Error = true;
2580 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2581 Twine(InstInfo.hasSideEffects));
2582 }
2583 }
2584
2585 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2586 Error = true;
2587 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2588 Twine(InstInfo.mayStore));
2589 }
2590
2591 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2592 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2593 // Some targets translate imediates to loads.
2594 if (!InstInfo.mayLoad) {
2595 Error = true;
2596 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2597 Twine(InstInfo.mayLoad));
2598 }
2599 }
2600
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002601 // Transfer inferred flags.
2602 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2603 InstInfo.mayStore |= PatInfo.mayStore;
2604 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002605
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002606 // These flags are silently added without any verification.
2607 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenaaaecfc2012-08-24 21:08:09 +00002608
2609 // Don't infer isVariadic. This flag means something different on SDNodes and
2610 // instructions. For example, a CALL SDNode is variadic because it has the
2611 // call arguments as operands, but a CALL instruction is not variadic - it
2612 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002613
2614 return Error;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002615}
2616
Jim Grosbachac915b42012-07-17 00:47:06 +00002617/// hasNullFragReference - Return true if the DAG has any reference to the
2618/// null_frag operator.
2619static bool hasNullFragReference(DagInit *DI) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002620 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbachac915b42012-07-17 00:47:06 +00002621 if (!OpDef) return false;
2622 Record *Operator = OpDef->getDef();
2623
2624 // If this is the null fragment, return true.
2625 if (Operator->getName() == "null_frag") return true;
2626 // If any of the arguments reference the null fragment, return true.
2627 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002628 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbachac915b42012-07-17 00:47:06 +00002629 if (Arg && hasNullFragReference(Arg))
2630 return true;
2631 }
2632
2633 return false;
2634}
2635
2636/// hasNullFragReference - Return true if any DAG in the list references
2637/// the null_frag operator.
2638static bool hasNullFragReference(ListInit *LI) {
2639 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002640 DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
Jim Grosbachac915b42012-07-17 00:47:06 +00002641 assert(DI && "non-dag in an instruction Pattern list?!");
2642 if (hasNullFragReference(DI))
2643 return true;
2644 }
2645 return false;
2646}
2647
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00002648/// Get all the instructions in a tree.
2649static void
2650getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2651 if (Tree->isLeaf())
2652 return;
2653 if (Tree->getOperator()->isSubClassOf("Instruction"))
2654 Instrs.push_back(Tree->getOperator());
2655 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2656 getInstructionsInTree(Tree->getChild(i), Instrs);
2657}
2658
Jakob Stoklund Olesen19209962013-03-24 00:56:16 +00002659/// Check the class of a pattern leaf node against the instruction operand it
2660/// represents.
2661static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2662 Record *Leaf) {
2663 if (OI.Rec == Leaf)
2664 return true;
2665
2666 // Allow direct value types to be used in instruction set patterns.
2667 // The type will be checked later.
2668 if (Leaf->isSubClassOf("ValueType"))
2669 return true;
2670
2671 // Patterns can also be ComplexPattern instances.
2672 if (Leaf->isSubClassOf("ComplexPattern"))
2673 return true;
2674
2675 return false;
2676}
2677
Chris Lattner6cefb772008-01-05 22:25:12 +00002678/// ParseInstructions - Parse all of the instructions, inlining and resolving
2679/// any fragments involved. This populates the Instructions list with fully
2680/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002681void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002682 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002683
Chris Lattner6cefb772008-01-05 22:25:12 +00002684 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00002685 ListInit *LI = 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002686
Sean Silva3f7b7f82012-10-10 20:24:47 +00002687 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002688 LI = Instrs[i]->getValueAsListInit("Pattern");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002689
Chris Lattner6cefb772008-01-05 22:25:12 +00002690 // If there is no pattern, only collect minimal information about the
2691 // instruction for its operand list. We have to assume that there is one
Jim Grosbachac915b42012-07-17 00:47:06 +00002692 // result, as we have no detailed info. A pattern which references the
2693 // null_frag operator is as-if no pattern were specified. Normally this
2694 // is from a multiclass expansion w/ a SDPatternOperator passed in as
2695 // null_frag.
2696 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002697 std::vector<Record*> Results;
2698 std::vector<Record*> Operands;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002699
Chris Lattnerf30187a2010-03-19 00:07:20 +00002700 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002701
Chris Lattnerc240bb02010-11-01 04:03:32 +00002702 if (InstInfo.Operands.size() != 0) {
2703 if (InstInfo.Operands.NumDefs == 0) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002704 // These produce no results
Chris Lattnerc240bb02010-11-01 04:03:32 +00002705 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2706 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002707 } else {
2708 // Assume the first operand is the result.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002709 Results.push_back(InstInfo.Operands[0].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002710
Chris Lattner6cefb772008-01-05 22:25:12 +00002711 // The rest are inputs.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002712 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2713 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002714 }
2715 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002716
Chris Lattner6cefb772008-01-05 22:25:12 +00002717 // Create and insert the instruction.
2718 std::vector<Record*> ImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002719 Instructions.insert(std::make_pair(Instrs[i],
Chris Lattner62bcec82010-04-20 06:28:43 +00002720 DAGInstruction(0, Results, Operands, ImpResults)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002721 continue; // no pattern.
2722 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002723
Chris Lattner6cefb772008-01-05 22:25:12 +00002724 // Parse the instruction.
2725 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2726 // Inline pattern fragments into it.
2727 I->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002728
Chris Lattner6cefb772008-01-05 22:25:12 +00002729 // Infer as many types as possible. If we cannot infer all of them, we can
2730 // never do anything with this instruction pattern: report it to the user.
2731 if (!I->InferAllTypes())
2732 I->error("Could not infer all types in pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002733
2734 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner6cefb772008-01-05 22:25:12 +00002735 // with the record they are declared as.
2736 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002737
Chris Lattner6cefb772008-01-05 22:25:12 +00002738 // InstResults - Keep track of all the virtual registers that are 'set'
2739 // in the instruction, including what reg class they are.
2740 std::map<std::string, TreePatternNode*> InstResults;
2741
Chris Lattner6cefb772008-01-05 22:25:12 +00002742 std::vector<Record*> InstImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002743
Chris Lattner6cefb772008-01-05 22:25:12 +00002744 // Verify that the top-level forms in the instruction are of void type, and
2745 // fill in the InstResults map.
2746 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2747 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002748 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002749 I->error("Top-level forms in instruction pattern should have"
2750 " void types");
2751
2752 // Find inputs and outputs, and verify the structure of the uses/defs.
2753 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002754 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002755 }
2756
2757 // Now that we have inputs and outputs of the pattern, inspect the operands
2758 // list for the instruction. This determines the order that operands are
2759 // added to the machine instruction the node corresponds to.
2760 unsigned NumResults = InstResults.size();
2761
2762 // Parse the operands list from the (ops) list, validating it.
2763 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002764 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002765
2766 // Check that all of the results occur first in the list.
2767 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002768 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002769 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00002770 if (i == CGI.Operands.size())
Chris Lattner6cefb772008-01-05 22:25:12 +00002771 I->error("'" + InstResults.begin()->first +
2772 "' set but does not appear in operand list!");
Chris Lattnerc240bb02010-11-01 04:03:32 +00002773 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002774
Chris Lattner6cefb772008-01-05 22:25:12 +00002775 // Check that it exists in InstResults.
2776 TreePatternNode *RNode = InstResults[OpName];
2777 if (RNode == 0)
2778 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002779
Chris Lattner6cefb772008-01-05 22:25:12 +00002780 if (i == 0)
2781 Res0Node = RNode;
Sean Silva3f7b7f82012-10-10 20:24:47 +00002782 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Chris Lattner6cefb772008-01-05 22:25:12 +00002783 if (R == 0)
2784 I->error("Operand $" + OpName + " should be a set destination: all "
2785 "outputs must occur before inputs in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002786
Jakob Stoklund Olesen19209962013-03-24 00:56:16 +00002787 if (!checkOperandClass(CGI.Operands[i], R))
Chris Lattner6cefb772008-01-05 22:25:12 +00002788 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002789
Chris Lattner6cefb772008-01-05 22:25:12 +00002790 // Remember the return type.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002791 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002792
Chris Lattner6cefb772008-01-05 22:25:12 +00002793 // Okay, this one checks out.
2794 InstResults.erase(OpName);
2795 }
2796
2797 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2798 // the copy while we're checking the inputs.
2799 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2800
2801 std::vector<TreePatternNode*> ResultNodeOperands;
2802 std::vector<Record*> Operands;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002803 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2804 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner6cefb772008-01-05 22:25:12 +00002805 const std::string &OpName = Op.Name;
2806 if (OpName.empty())
2807 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2808
2809 if (!InstInputsCheck.count(OpName)) {
Tom Stellard6d3d7652012-09-06 14:15:52 +00002810 // If this is an operand with a DefaultOps set filled in, we can ignore
2811 // this. When we codegen it, we will do so as always executed.
2812 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002813 // Does it have a non-empty DefaultOps field? If so, ignore this
2814 // operand.
2815 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2816 continue;
2817 }
2818 I->error("Operand $" + OpName +
2819 " does not appear in the instruction pattern");
2820 }
2821 TreePatternNode *InVal = InstInputsCheck[OpName];
2822 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002823
Sean Silva3f7b7f82012-10-10 20:24:47 +00002824 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
David Greene05bce0b2011-07-29 22:43:06 +00002825 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Jakob Stoklund Olesen19209962013-03-24 00:56:16 +00002826 if (!checkOperandClass(Op, InRec))
Chris Lattner6cefb772008-01-05 22:25:12 +00002827 I->error("Operand $" + OpName + "'s register class disagrees"
2828 " between the operand and pattern");
2829 }
2830 Operands.push_back(Op.Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002831
Chris Lattner6cefb772008-01-05 22:25:12 +00002832 // Construct the result for the dest-pattern operand list.
2833 TreePatternNode *OpNode = InVal->clone();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002834
Chris Lattner6cefb772008-01-05 22:25:12 +00002835 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002836 OpNode->clearPredicateFns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002837
Chris Lattner6cefb772008-01-05 22:25:12 +00002838 // Promote the xform function to be an explicit node if set.
2839 if (Record *Xform = OpNode->getTransformFn()) {
2840 OpNode->setTransformFn(0);
2841 std::vector<TreePatternNode*> Children;
2842 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002843 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002844 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002845
Chris Lattner6cefb772008-01-05 22:25:12 +00002846 ResultNodeOperands.push_back(OpNode);
2847 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002848
Chris Lattner6cefb772008-01-05 22:25:12 +00002849 if (!InstInputsCheck.empty())
2850 I->error("Input operand $" + InstInputsCheck.begin()->first +
2851 " occurs in pattern but not in operands list!");
2852
2853 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002854 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2855 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002856 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002857 for (unsigned i = 0; i != NumResults; ++i)
2858 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002859
2860 // Create and insert the instruction.
Chris Lattneracfb70f2010-04-20 06:30:25 +00002861 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner62bcec82010-04-20 06:28:43 +00002862 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002863 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2864
2865 // Use a temporary tree pattern to infer all types and make sure that the
2866 // constructed result is correct. This depends on the instruction already
2867 // being inserted into the Instructions map.
2868 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002869 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002870
2871 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2872 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002873
Chris Lattner6cefb772008-01-05 22:25:12 +00002874 DEBUG(I->dump());
2875 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002876
Chris Lattner6cefb772008-01-05 22:25:12 +00002877 // If we can, convert the instructions to be patterns that are matched!
Sean Silva90fee072012-09-19 01:47:00 +00002878 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002879 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002880 E = Instructions.end(); II != E; ++II) {
2881 DAGInstruction &TheInst = II->second;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002882 TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002883 if (I == 0) continue; // No pattern.
2884
2885 // FIXME: Assume only the first tree is the pattern. The others are clobber
2886 // nodes.
2887 TreePatternNode *Pattern = I->getTree(0);
2888 TreePatternNode *SrcPattern;
2889 if (Pattern->getOperator()->getName() == "set") {
2890 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2891 } else{
2892 // Not a set (store or something?)
2893 SrcPattern = Pattern;
2894 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002895
Chris Lattner6cefb772008-01-05 22:25:12 +00002896 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002897 AddPatternToMatch(I,
Jim Grosbach997759a2010-12-07 23:05:49 +00002898 PatternToMatch(Instr,
2899 Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002900 SrcPattern,
2901 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002902 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002903 Instr->getValueAsInt("AddedComplexity"),
2904 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002905 }
2906}
2907
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002908
2909typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2910
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002911static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002912 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002913 TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002914 if (!P->getName().empty()) {
2915 NameRecord &Rec = Names[P->getName()];
2916 // If this is the first instance of the name, remember the node.
2917 if (Rec.second++ == 0)
2918 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002919 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002920 PatternTop->error("repetition of value: $" + P->getName() +
2921 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002922 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002923
Chris Lattner967d54a2010-02-23 06:35:45 +00002924 if (!P->isLeaf()) {
2925 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002926 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002927 }
2928}
2929
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002930void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner25b6f912010-02-23 06:16:51 +00002931 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002932 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002933 std::string Reason;
Owen Andersoneb79b542012-09-19 22:15:06 +00002934 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
2935 PrintWarning(Pattern->getRecord()->getLoc(),
2936 Twine("Pattern can never match: ") + Reason);
2937 return;
2938 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002939
Chris Lattner405f1252010-03-01 22:29:19 +00002940 // If the source pattern's root is a complex pattern, that complex pattern
2941 // must specify the nodes it can potentially match.
2942 if (const ComplexPattern *CP =
2943 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2944 if (CP->getRootNodes().empty())
2945 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2946 " could match");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002947
2948
Chris Lattner967d54a2010-02-23 06:35:45 +00002949 // Find all of the named values in the input and output, ensure they have the
2950 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002951 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002952 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2953 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002954
2955 // Scan all of the named values in the destination pattern, rejecting them if
2956 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002957 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002958 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002959 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002960 Pattern->error("Pattern has input without matching name in output: $" +
2961 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002962 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002963
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002964 // Scan all of the named values in the source pattern, rejecting them if the
2965 // name isn't used in the dest, and isn't used to tie two values together.
2966 for (std::map<std::string, NameRecord>::iterator
2967 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2968 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2969 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002970
Chris Lattner25b6f912010-02-23 06:16:51 +00002971 PatternsToMatch.push_back(PTM);
2972}
2973
2974
Dan Gohmanee4fa192008-04-03 00:02:49 +00002975
2976void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002977 const std::vector<const CodeGenInstruction*> &Instructions =
2978 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002979
2980 // First try to infer flags from the primary instruction pattern, if any.
2981 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002982 unsigned Errors = 0;
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002983 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2984 CodeGenInstruction &InstInfo =
2985 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesenccbe6032011-10-14 01:00:49 +00002986
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002987 // Treat neverHasSideEffects = 1 as the equivalent of hasSideEffects = 0.
2988 // This flag is obsolete and will be removed.
2989 if (InstInfo.neverHasSideEffects) {
2990 assert(!InstInfo.hasSideEffects);
2991 InstInfo.hasSideEffects_Unset = false;
2992 }
2993
2994 // Get the primary instruction pattern.
2995 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
2996 if (!Pattern) {
2997 if (InstInfo.hasUndefFlags())
2998 Revisit.push_back(&InstInfo);
2999 continue;
3000 }
3001 InstAnalyzer PatInfo(*this);
3002 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00003003 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003004 }
3005
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00003006 // Second, look for single-instruction patterns defined outside the
3007 // instruction.
3008 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3009 const PatternToMatch &PTM = *I;
3010
3011 // We can only infer from single-instruction patterns, otherwise we won't
3012 // know which instruction should get the flags.
3013 SmallVector<Record*, 8> PatInstrs;
3014 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3015 if (PatInstrs.size() != 1)
3016 continue;
3017
3018 // Get the single instruction.
3019 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3020
3021 // Only infer properties from the first pattern. We'll verify the others.
3022 if (InstInfo.InferredFrom)
3023 continue;
3024
3025 InstAnalyzer PatInfo(*this);
3026 PatInfo.Analyze(&PTM);
3027 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3028 }
3029
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00003030 if (Errors)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00003031 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00003032
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003033 // Revisit instructions with undefined flags and no pattern.
3034 if (Target.guessInstructionProperties()) {
3035 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3036 CodeGenInstruction &InstInfo = *Revisit[i];
3037 if (InstInfo.InferredFrom)
3038 continue;
3039 // The mayLoad and mayStore flags default to false.
3040 // Conservatively assume hasSideEffects if it wasn't explicit.
3041 if (InstInfo.hasSideEffects_Unset)
3042 InstInfo.hasSideEffects = true;
3043 }
3044 return;
3045 }
3046
3047 // Complain about any flags that are still undefined.
3048 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3049 CodeGenInstruction &InstInfo = *Revisit[i];
3050 if (InstInfo.InferredFrom)
3051 continue;
3052 if (InstInfo.hasSideEffects_Unset)
3053 PrintError(InstInfo.TheDef->getLoc(),
3054 "Can't infer hasSideEffects from patterns");
3055 if (InstInfo.mayStore_Unset)
3056 PrintError(InstInfo.TheDef->getLoc(),
3057 "Can't infer mayStore from patterns");
3058 if (InstInfo.mayLoad_Unset)
3059 PrintError(InstInfo.TheDef->getLoc(),
3060 "Can't infer mayLoad from patterns");
Dan Gohmanee4fa192008-04-03 00:02:49 +00003061 }
3062}
3063
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003064
3065/// Verify instruction flags against pattern node properties.
3066void CodeGenDAGPatterns::VerifyInstructionFlags() {
3067 unsigned Errors = 0;
3068 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3069 const PatternToMatch &PTM = *I;
3070 SmallVector<Record*, 8> Instrs;
3071 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3072 if (Instrs.empty())
3073 continue;
3074
3075 // Count the number of instructions with each flag set.
3076 unsigned NumSideEffects = 0;
3077 unsigned NumStores = 0;
3078 unsigned NumLoads = 0;
3079 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3080 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3081 NumSideEffects += InstInfo.hasSideEffects;
3082 NumStores += InstInfo.mayStore;
3083 NumLoads += InstInfo.mayLoad;
3084 }
3085
3086 // Analyze the source pattern.
3087 InstAnalyzer PatInfo(*this);
3088 PatInfo.Analyze(&PTM);
3089
3090 // Collect error messages.
3091 SmallVector<std::string, 4> Msgs;
3092
3093 // Check for missing flags in the output.
3094 // Permit extra flags for now at least.
3095 if (PatInfo.hasSideEffects && !NumSideEffects)
3096 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3097
3098 // Don't verify store flags on instructions with side effects. At least for
3099 // intrinsics, side effects implies mayStore.
3100 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3101 Msgs.push_back("pattern may store, but mayStore isn't set");
3102
3103 // Similarly, mayStore implies mayLoad on intrinsics.
3104 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3105 Msgs.push_back("pattern may load, but mayLoad isn't set");
3106
3107 // Print error messages.
3108 if (Msgs.empty())
3109 continue;
3110 ++Errors;
3111
3112 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3113 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3114 (Instrs.size() == 1 ?
3115 "instruction" : "output instructions"));
3116 // Provide the location of the relevant instruction definitions.
3117 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3118 if (Instrs[i] != PTM.getSrcRecord())
3119 PrintError(Instrs[i]->getLoc(), "defined here");
3120 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3121 if (InstInfo.InferredFrom &&
3122 InstInfo.InferredFrom != InstInfo.TheDef &&
3123 InstInfo.InferredFrom != PTM.getSrcRecord())
3124 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
3125 }
3126 }
3127 if (Errors)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00003128 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003129}
3130
Chris Lattner2cacec52010-03-15 06:00:16 +00003131/// Given a pattern result with an unresolved type, see if we can find one
3132/// instruction with an unresolved result type. Force this result type to an
3133/// arbitrary element if it's possible types to converge results.
3134static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3135 if (N->isLeaf())
3136 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003137
Chris Lattner2cacec52010-03-15 06:00:16 +00003138 // Analyze children.
3139 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3140 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3141 return true;
3142
3143 if (!N->getOperator()->isSubClassOf("Instruction"))
3144 return false;
3145
3146 // If this type is already concrete or completely unknown we can't do
3147 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00003148 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3149 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3150 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003151
Chris Lattnerd7349192010-03-19 21:37:09 +00003152 // Otherwise, force its type to the first possibility (an arbitrary choice).
3153 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3154 return true;
3155 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003156
Chris Lattnerd7349192010-03-19 21:37:09 +00003157 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00003158}
3159
Chris Lattnerfe718932008-01-06 01:10:31 +00003160void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00003161 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3162
3163 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00003164 Record *CurPattern = Patterns[i];
David Greene05bce0b2011-07-29 22:43:06 +00003165 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachd3e31212012-07-17 18:39:36 +00003166
3167 // If the pattern references the null_frag, there's nothing to do.
3168 if (hasNullFragReference(Tree))
3169 continue;
3170
Chris Lattner310adf12010-03-27 02:53:27 +00003171 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00003172
3173 // Inline pattern fragments into it.
3174 Pattern->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003175
David Greene05bce0b2011-07-29 22:43:06 +00003176 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00003177 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003178
Chris Lattner6cefb772008-01-05 22:25:12 +00003179 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00003180 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003181
Chris Lattner6cefb772008-01-05 22:25:12 +00003182 // Inline pattern fragments into it.
3183 Result->InlinePatternFragments();
3184
3185 if (Result->getNumTrees() != 1)
3186 Result->error("Cannot handle instructions producing instructions "
3187 "with temporaries yet!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003188
Chris Lattner6cefb772008-01-05 22:25:12 +00003189 bool IterateInference;
3190 bool InferredAllPatternTypes, InferredAllResultTypes;
3191 do {
3192 // Infer as many types as possible. If we cannot infer all of them, we
3193 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00003194 InferredAllPatternTypes =
3195 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003196
Chris Lattner6cefb772008-01-05 22:25:12 +00003197 // Infer as many types as possible. If we cannot infer all of them, we
3198 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00003199 InferredAllResultTypes =
3200 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00003201
Chris Lattner6c6ba362010-03-18 23:15:10 +00003202 IterateInference = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003203
Chris Lattner6cefb772008-01-05 22:25:12 +00003204 // Apply the type of the result to the source pattern. This helps us
3205 // resolve cases where the input type is known to be a pointer type (which
3206 // is considered resolved), but the result knows it needs to be 32- or
3207 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00003208 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
3209 Pattern->getTree(0)->getNumTypes());
3210 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00003211 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00003212 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00003213 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00003214 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00003215 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003216
Chris Lattner2cacec52010-03-15 06:00:16 +00003217 // If our iteration has converged and the input pattern's types are fully
3218 // resolved but the result pattern is not fully resolved, we may have a
3219 // situation where we have two instructions in the result pattern and
3220 // the instructions require a common register class, but don't care about
3221 // what actual MVT is used. This is actually a bug in our modelling:
3222 // output patterns should have register classes, not MVTs.
3223 //
3224 // In any case, to handle this, we just go through and disambiguate some
3225 // arbitrary types to the result pattern's nodes.
3226 if (!IterateInference && InferredAllPatternTypes &&
3227 !InferredAllResultTypes)
3228 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
3229 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00003230 } while (IterateInference);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003231
Chris Lattner6cefb772008-01-05 22:25:12 +00003232 // Verify that we inferred enough types that we can do something with the
3233 // pattern and result. If these fire the user has to add type casts.
3234 if (!InferredAllPatternTypes)
3235 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00003236 if (!InferredAllResultTypes) {
3237 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00003238 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00003239 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003240
Chris Lattner6cefb772008-01-05 22:25:12 +00003241 // Validate that the input pattern is correct.
3242 std::map<std::string, TreePatternNode*> InstInputs;
3243 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00003244 std::vector<Record*> InstImpResults;
3245 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3246 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3247 InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00003248 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00003249
3250 // Promote the xform function to be an explicit node if set.
3251 TreePatternNode *DstPattern = Result->getOnlyTree();
3252 std::vector<TreePatternNode*> ResultNodeOperands;
3253 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3254 TreePatternNode *OpNode = DstPattern->getChild(ii);
3255 if (Record *Xform = OpNode->getTransformFn()) {
3256 OpNode->setTransformFn(0);
3257 std::vector<TreePatternNode*> Children;
3258 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00003259 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00003260 }
3261 ResultNodeOperands.push_back(OpNode);
3262 }
3263 DstPattern = Result->getOnlyTree();
3264 if (!DstPattern->isLeaf())
3265 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00003266 ResultNodeOperands,
3267 DstPattern->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003268
Chris Lattnerd7349192010-03-19 21:37:09 +00003269 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
3270 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003271
Chris Lattner6cefb772008-01-05 22:25:12 +00003272 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
3273 Temp.InferAllTypes();
3274
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003275
Chris Lattner25b6f912010-02-23 06:16:51 +00003276 AddPatternToMatch(Pattern,
Jim Grosbach997759a2010-12-07 23:05:49 +00003277 PatternToMatch(CurPattern,
3278 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerd7349192010-03-19 21:37:09 +00003279 Pattern->getTree(0),
3280 Temp.getOnlyTree(), InstImpResults,
3281 CurPattern->getValueAsInt("AddedComplexity"),
3282 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003283 }
3284}
3285
3286/// CombineChildVariants - Given a bunch of permutations of each child of the
3287/// 'operator' node, put them together in all possible ways.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003288static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00003289 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3290 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003291 CodeGenDAGPatterns &CDP,
3292 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003293 // Make sure that each operand has at least one variant to choose from.
3294 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3295 if (ChildVariants[i].empty())
3296 return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003297
Chris Lattner6cefb772008-01-05 22:25:12 +00003298 // The end result is an all-pairs construction of the resultant pattern.
3299 std::vector<unsigned> Idxs;
3300 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00003301 bool NotDone;
3302 do {
3303#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00003304 DEBUG(if (!Idxs.empty()) {
3305 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3306 for (unsigned i = 0; i < Idxs.size(); ++i) {
3307 errs() << Idxs[i] << " ";
3308 }
3309 errs() << "]\n";
3310 });
Scott Michel327d0652008-03-05 17:49:05 +00003311#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00003312 // Create the variant and add it to the output list.
3313 std::vector<TreePatternNode*> NewChildren;
3314 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3315 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00003316 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3317 Orig->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003318
Chris Lattner6cefb772008-01-05 22:25:12 +00003319 // Copy over properties.
3320 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00003321 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00003322 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00003323 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3324 R->setType(i, Orig->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003325
Scott Michel327d0652008-03-05 17:49:05 +00003326 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00003327 std::string ErrString;
3328 if (!R->canPatternMatch(ErrString, CDP)) {
3329 delete R;
3330 } else {
3331 bool AlreadyExists = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003332
Chris Lattner6cefb772008-01-05 22:25:12 +00003333 // Scan to see if this pattern has already been emitted. We can get
3334 // duplication due to things like commuting:
3335 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3336 // which are the same pattern. Ignore the dups.
3337 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003338 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003339 AlreadyExists = true;
3340 break;
3341 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003342
Chris Lattner6cefb772008-01-05 22:25:12 +00003343 if (AlreadyExists)
3344 delete R;
3345 else
3346 OutVariants.push_back(R);
3347 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003348
Scott Michel327d0652008-03-05 17:49:05 +00003349 // Increment indices to the next permutation by incrementing the
3350 // indicies from last index backward, e.g., generate the sequence
3351 // [0, 0], [0, 1], [1, 0], [1, 1].
3352 int IdxsIdx;
3353 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3354 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3355 Idxs[IdxsIdx] = 0;
3356 else
Chris Lattner6cefb772008-01-05 22:25:12 +00003357 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00003358 }
Scott Michel327d0652008-03-05 17:49:05 +00003359 NotDone = (IdxsIdx >= 0);
3360 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00003361}
3362
3363/// CombineChildVariants - A helper function for binary operators.
3364///
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003365static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00003366 const std::vector<TreePatternNode*> &LHS,
3367 const std::vector<TreePatternNode*> &RHS,
3368 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003369 CodeGenDAGPatterns &CDP,
3370 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003371 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3372 ChildVariants.push_back(LHS);
3373 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00003374 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003375}
Chris Lattner6cefb772008-01-05 22:25:12 +00003376
3377
3378static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3379 std::vector<TreePatternNode *> &Children) {
3380 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3381 Record *Operator = N->getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003382
Chris Lattner6cefb772008-01-05 22:25:12 +00003383 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00003384 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00003385 N->getTransformFn()) {
3386 Children.push_back(N);
3387 return;
3388 }
3389
3390 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3391 Children.push_back(N->getChild(0));
3392 else
3393 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3394
3395 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3396 Children.push_back(N->getChild(1));
3397 else
3398 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3399}
3400
3401/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3402/// the (potentially recursive) pattern by using algebraic laws.
3403///
3404static void GenerateVariantsOf(TreePatternNode *N,
3405 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003406 CodeGenDAGPatterns &CDP,
3407 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003408 // We cannot permute leaves.
3409 if (N->isLeaf()) {
3410 OutVariants.push_back(N);
3411 return;
3412 }
3413
3414 // Look up interesting info about the node.
3415 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3416
Jim Grosbachda4231f2009-03-26 16:17:51 +00003417 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00003418 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003419 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00003420 std::vector<TreePatternNode*> MaximalChildren;
3421 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3422
3423 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3424 // permutations.
3425 if (MaximalChildren.size() == 3) {
3426 // Find the variants of all of our maximal children.
3427 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003428 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3429 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3430 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003431
Chris Lattner6cefb772008-01-05 22:25:12 +00003432 // There are only two ways we can permute the tree:
3433 // (A op B) op C and A op (B op C)
3434 // Within these forms, we can also permute A/B/C.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003435
Chris Lattner6cefb772008-01-05 22:25:12 +00003436 // Generate legal pair permutations of A/B/C.
3437 std::vector<TreePatternNode*> ABVariants;
3438 std::vector<TreePatternNode*> BAVariants;
3439 std::vector<TreePatternNode*> ACVariants;
3440 std::vector<TreePatternNode*> CAVariants;
3441 std::vector<TreePatternNode*> BCVariants;
3442 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003443 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3444 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3445 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3446 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3447 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3448 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003449
3450 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00003451 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3452 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3453 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3454 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3455 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3456 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003457
3458 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00003459 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3460 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3461 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3462 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3463 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3464 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003465 return;
3466 }
3467 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003468
Chris Lattner6cefb772008-01-05 22:25:12 +00003469 // Compute permutations of all children.
3470 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3471 ChildVariants.resize(N->getNumChildren());
3472 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003473 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003474
3475 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00003476 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003477
3478 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003479 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3480 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3481 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3482 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003483 // Don't count children which are actually register references.
3484 unsigned NC = 0;
3485 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3486 TreePatternNode *Child = N->getChild(i);
3487 if (Child->isLeaf())
Sean Silva6cfc8062012-10-10 20:24:43 +00003488 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003489 Record *RR = DI->getDef();
3490 if (RR->isSubClassOf("Register"))
3491 continue;
3492 }
3493 NC++;
3494 }
3495 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003496 if (isCommIntrinsic) {
3497 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3498 // operands are the commutative operands, and there might be more operands
3499 // after those.
3500 assert(NC >= 3 &&
3501 "Commutative intrinsic should have at least 3 childrean!");
3502 std::vector<std::vector<TreePatternNode*> > Variants;
3503 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3504 Variants.push_back(ChildVariants[2]);
3505 Variants.push_back(ChildVariants[1]);
3506 for (unsigned i = 3; i != NC; ++i)
3507 Variants.push_back(ChildVariants[i]);
3508 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3509 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00003510 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00003511 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003512 }
3513}
3514
3515
3516// GenerateVariants - Generate variants. For example, commutative patterns can
3517// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00003518void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00003519 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003520
Chris Lattner6cefb772008-01-05 22:25:12 +00003521 // Loop over all of the patterns we've collected, checking to see if we can
3522 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00003523 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00003524 // the .td file having to contain tons of variants of instructions.
3525 //
3526 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3527 // intentionally do not reconsider these. Any variants of added patterns have
3528 // already been added.
3529 //
3530 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00003531 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00003532 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00003533 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00003534 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00003535 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00003536 DEBUG(errs() << "\n");
Jim Grosbachbb168242010-10-08 18:13:57 +00003537 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3538 DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003539
3540 assert(!Variants.empty() && "Must create at least original variant!");
3541 Variants.erase(Variants.begin()); // Remove the original pattern.
3542
3543 if (Variants.empty()) // No variants for this pattern.
3544 continue;
3545
Chris Lattner569f1212009-08-23 04:44:11 +00003546 DEBUG(errs() << "FOUND VARIANTS OF: ";
3547 PatternsToMatch[i].getSrcPattern()->dump();
3548 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003549
3550 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3551 TreePatternNode *Variant = Variants[v];
3552
Chris Lattner569f1212009-08-23 04:44:11 +00003553 DEBUG(errs() << " VAR#" << v << ": ";
3554 Variant->dump();
3555 errs() << "\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003556
Chris Lattner6cefb772008-01-05 22:25:12 +00003557 // Scan to see if an instruction or explicit pattern already matches this.
3558 bool AlreadyExists = false;
3559 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00003560 // Skip if the top level predicates do not match.
3561 if (PatternsToMatch[i].getPredicates() !=
3562 PatternsToMatch[p].getPredicates())
3563 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00003564 // Check to see if this variant already exists.
Jim Grosbachbb168242010-10-08 18:13:57 +00003565 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3566 DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00003567 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003568 AlreadyExists = true;
3569 break;
3570 }
3571 }
3572 // If we already have it, ignore the variant.
3573 if (AlreadyExists) continue;
3574
3575 // Otherwise, add it to the list of patterns we have.
3576 PatternsToMatch.
Jim Grosbach997759a2010-12-07 23:05:49 +00003577 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3578 PatternsToMatch[i].getPredicates(),
Chris Lattner6cefb772008-01-05 22:25:12 +00003579 Variant, PatternsToMatch[i].getDstPattern(),
3580 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00003581 PatternsToMatch[i].getAddedComplexity(),
3582 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003583 }
3584
Chris Lattner569f1212009-08-23 04:44:11 +00003585 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003586 }
3587}