blob: 443a6622adff9beb6b964d60376bd061b621ebb8 [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"
Peter Collingbourne7c788882011-10-01 16:41:13 +000016#include "llvm/TableGen/Error.h"
17#include "llvm/TableGen/Record.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000018#include "llvm/ADT/StringExtras.h"
Chris Lattner2cacec52010-03-15 06:00:16 +000019#include "llvm/ADT/STLExtras.h"
Jim Grosbach9b29ea42012-04-18 17:46:41 +000020#include "llvm/ADT/Twine.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000021#include "llvm/Support/Debug.h"
David Blaikiefdebc382012-01-17 04:43:56 +000022#include "llvm/Support/ErrorHandling.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) {
Owen Andersone50ed302009-08-10 22:56:29 +000033 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000034}
Owen Anderson825b72b2009-08-11 20:47:22 +000035static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000036 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000037}
Owen Anderson825b72b2009-08-11 20:47:22 +000038static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000039 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000040}
Chris Lattner774ce292010-03-19 17:41:26 +000041static inline bool isScalar(MVT::SimpleValueType VT) {
42 return !EVT(VT).isVector();
43}
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
60EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
61 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());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000079 const std::vector<MVT::SimpleValueType> &LegalTypes =
Chris Lattner774ce292010-03-19 17:41:26 +000080 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +000081
Chris Lattner774ce292010-03-19 17:41:26 +000082 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
83 if (Pred == 0 || Pred(LegalTypes[i]))
84 TypeVec.push_back(LegalTypes[i]);
85
86 // If we have nothing that matches the predicate, bail out.
87 if (TypeVec.empty())
88 TP.error("Type inference contradiction found, no " +
Jim Grosbachfbadcd02010-12-21 16:16:00 +000089 std::string(PredicateName) + " types found");
Chris Lattner774ce292010-03-19 17:41:26 +000090 // No need to sort with one element.
91 if (TypeVec.size() == 1) return true;
92
93 // Remove duplicates.
94 array_pod_sort(TypeVec.begin(), TypeVec.end());
95 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000096
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000097 return true;
98}
Chris Lattner2cacec52010-03-15 06:00:16 +000099
100/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
101/// integer value type.
102bool EEVT::TypeSet::hasIntegerTypes() const {
103 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
104 if (isInteger(TypeVec[i]))
105 return true;
106 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000107}
Chris Lattner2cacec52010-03-15 06:00:16 +0000108
109/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
110/// a floating point value type.
111bool EEVT::TypeSet::hasFloatingPointTypes() const {
112 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
113 if (isFloatingPoint(TypeVec[i]))
114 return true;
115 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000116}
Chris Lattner2cacec52010-03-15 06:00:16 +0000117
118/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
119/// value type.
120bool EEVT::TypeSet::hasVectorTypes() const {
121 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
122 if (isVector(TypeVec[i]))
123 return true;
124 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +0000125}
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000126
Chris Lattner2cacec52010-03-15 06:00:16 +0000127
128std::string EEVT::TypeSet::getName() const {
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000129 if (TypeVec.empty()) return "<empty>";
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000130
Chris Lattner2cacec52010-03-15 06:00:16 +0000131 std::string Result;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000132
Chris Lattner2cacec52010-03-15 06:00:16 +0000133 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
134 std::string VTName = llvm::getEnumName(TypeVec[i]);
135 // Strip off MVT:: prefix if present.
136 if (VTName.substr(0,5) == "MVT::")
137 VTName = VTName.substr(5);
138 if (i) Result += ':';
139 Result += VTName;
140 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000141
Chris Lattner2cacec52010-03-15 06:00:16 +0000142 if (TypeVec.size() == 1)
143 return Result;
144 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000145}
Chris Lattner2cacec52010-03-15 06:00:16 +0000146
147/// MergeInTypeInfo - This merges in type information from the specified
148/// argument. If 'this' changes, it returns true. If the two types are
149/// contradictory (e.g. merge f32 into i32) then this throws an exception.
150bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
151 if (InVT.isCompletelyUnknown() || *this == InVT)
152 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000153
Chris Lattner2cacec52010-03-15 06:00:16 +0000154 if (isCompletelyUnknown()) {
155 *this = InVT;
156 return true;
157 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000158
Chris Lattner2cacec52010-03-15 06:00:16 +0000159 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000160
Chris Lattner2cacec52010-03-15 06:00:16 +0000161 // Handle the abstract cases, seeing if we can resolve them better.
162 switch (TypeVec[0]) {
163 default: break;
164 case MVT::iPTR:
165 case MVT::iPTRAny:
166 if (InVT.hasIntegerTypes()) {
167 EEVT::TypeSet InCopy(InVT);
168 InCopy.EnforceInteger(TP);
169 InCopy.EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000170
Chris Lattner2cacec52010-03-15 06:00:16 +0000171 if (InCopy.isConcrete()) {
172 // If the RHS has one integer type, upgrade iPTR to i32.
173 TypeVec[0] = InVT.TypeVec[0];
174 return true;
175 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000176
Chris Lattner2cacec52010-03-15 06:00:16 +0000177 // If the input has multiple scalar integers, this doesn't add any info.
178 if (!InCopy.isCompletelyUnknown())
179 return false;
180 }
181 break;
182 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000183
Chris Lattner2cacec52010-03-15 06:00:16 +0000184 // If the input constraint is iAny/iPTR and this is an integer type list,
185 // remove non-integer types from the list.
186 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
187 hasIntegerTypes()) {
188 bool MadeChange = EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000189
Chris Lattner2cacec52010-03-15 06:00:16 +0000190 // If we're merging in iPTR/iPTRAny and the node currently has a list of
191 // multiple different integer types, replace them with a single iPTR.
192 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
193 TypeVec.size() != 1) {
194 TypeVec.resize(1);
195 TypeVec[0] = InVT.TypeVec[0];
196 MadeChange = true;
197 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000198
Chris Lattner2cacec52010-03-15 06:00:16 +0000199 return MadeChange;
200 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000201
Chris Lattner2cacec52010-03-15 06:00:16 +0000202 // If this is a type list and the RHS is a typelist as well, eliminate entries
203 // from this list that aren't in the other one.
204 bool MadeChange = false;
205 TypeSet InputSet(*this);
206
207 for (unsigned i = 0; i != TypeVec.size(); ++i) {
208 bool InInVT = false;
209 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
210 if (TypeVec[i] == InVT.TypeVec[j]) {
211 InInVT = true;
212 break;
213 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000214
Chris Lattner2cacec52010-03-15 06:00:16 +0000215 if (InInVT) continue;
216 TypeVec.erase(TypeVec.begin()+i--);
217 MadeChange = true;
218 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000219
Chris Lattner2cacec52010-03-15 06:00:16 +0000220 // If we removed all of our types, we have a type contradiction.
221 if (!TypeVec.empty())
222 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000223
Chris Lattner2cacec52010-03-15 06:00:16 +0000224 // FIXME: Really want an SMLoc here!
225 TP.error("Type inference contradiction found, merging '" +
226 InVT.getName() + "' into '" + InputSet.getName() + "'");
227 return true; // unreachable
228}
229
230/// EnforceInteger - Remove all non-integer types from this set.
231bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000232 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000233 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000234 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattner2cacec52010-03-15 06:00:16 +0000235 if (!hasFloatingPointTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000236 return false;
237
238 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000239
Chris Lattner2cacec52010-03-15 06:00:16 +0000240 // Filter out all the fp types.
241 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000242 if (!isInteger(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000243 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000244
Chris Lattner2cacec52010-03-15 06:00:16 +0000245 if (TypeVec.empty())
246 TP.error("Type inference contradiction found, '" +
247 InputSet.getName() + "' needs to be integer");
Chris Lattner774ce292010-03-19 17:41:26 +0000248 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000249}
250
251/// EnforceFloatingPoint - Remove all integer types from this set.
252bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000253 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000254 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000255 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
256
Chris Lattner2cacec52010-03-15 06:00:16 +0000257 if (!hasIntegerTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000258 return false;
259
260 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000261
Chris Lattner2cacec52010-03-15 06:00:16 +0000262 // Filter out all the fp types.
263 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000264 if (!isFloatingPoint(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000265 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000266
Chris Lattner2cacec52010-03-15 06:00:16 +0000267 if (TypeVec.empty())
268 TP.error("Type inference contradiction found, '" +
269 InputSet.getName() + "' needs to be floating point");
Chris Lattner774ce292010-03-19 17:41:26 +0000270 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000271}
272
273/// EnforceScalar - Remove all vector types from this.
274bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000275 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000276 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000277 return FillWithPossibleTypes(TP, isScalar, "scalar");
278
Chris Lattner2cacec52010-03-15 06:00:16 +0000279 if (!hasVectorTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000280 return false;
281
282 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000283
Chris Lattner2cacec52010-03-15 06:00:16 +0000284 // Filter out all the vector types.
285 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000286 if (!isScalar(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000287 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000288
Chris Lattner2cacec52010-03-15 06:00:16 +0000289 if (TypeVec.empty())
290 TP.error("Type inference contradiction found, '" +
291 InputSet.getName() + "' needs to be scalar");
Chris Lattner774ce292010-03-19 17:41:26 +0000292 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000293}
294
295/// EnforceVector - Remove all vector types from this.
296bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Chris Lattner774ce292010-03-19 17:41:26 +0000297 // If we know nothing, then get the full set.
298 if (TypeVec.empty())
299 return FillWithPossibleTypes(TP, isVector, "vector");
300
Chris Lattner2cacec52010-03-15 06:00:16 +0000301 TypeSet InputSet(*this);
302 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000303
Chris Lattner2cacec52010-03-15 06:00:16 +0000304 // Filter out all the scalar types.
305 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000306 if (!isVector(TypeVec[i])) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000307 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner774ce292010-03-19 17:41:26 +0000308 MadeChange = true;
309 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000310
Chris Lattner2cacec52010-03-15 06:00:16 +0000311 if (TypeVec.empty())
312 TP.error("Type inference contradiction found, '" +
313 InputSet.getName() + "' needs to be a vector");
314 return MadeChange;
315}
316
317
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000318
Chris Lattner2cacec52010-03-15 06:00:16 +0000319/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
320/// this an other based on this information.
321bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
322 // Both operands must be integer or FP, but we don't care which.
323 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000324
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000325 if (isCompletelyUnknown())
326 MadeChange = FillWithPossibleTypes(TP);
327
328 if (Other.isCompletelyUnknown())
329 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000330
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000331 // If one side is known to be integer or known to be FP but the other side has
332 // no information, get at least the type integrality info in there.
333 if (!hasFloatingPointTypes())
334 MadeChange |= Other.EnforceInteger(TP);
335 else if (!hasIntegerTypes())
336 MadeChange |= Other.EnforceFloatingPoint(TP);
337 if (!Other.hasFloatingPointTypes())
338 MadeChange |= EnforceInteger(TP);
339 else if (!Other.hasIntegerTypes())
340 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000341
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000342 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
343 "Should have a type list now");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000344
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000345 // If one contains vectors but the other doesn't pull vectors out.
346 if (!hasVectorTypes())
347 MadeChange |= Other.EnforceScalar(TP);
348 if (!hasVectorTypes())
349 MadeChange |= EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000350
David Greene9d7f0112011-02-01 19:12:32 +0000351 if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
352 // If we are down to concrete types, this code does not currently
353 // handle nodes which have multiple types, where some types are
354 // integer, and some are fp. Assert that this is not the case.
355 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
356 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
357 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
358
359 // Otherwise, if these are both vector types, either this vector
360 // must have a larger bitsize than the other, or this element type
361 // must be larger than the other.
362 EVT Type(TypeVec[0]);
363 EVT OtherType(Other.TypeVec[0]);
364
365 if (hasVectorTypes() && Other.hasVectorTypes()) {
366 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
367 if (Type.getVectorElementType().getSizeInBits()
368 >= OtherType.getVectorElementType().getSizeInBits())
369 TP.error("Type inference contradiction found, '" +
370 getName() + "' element type not smaller than '" +
371 Other.getName() +"'!");
372 }
373 else
374 // For scalar types, the bitsize of this type must be larger
375 // than that of the other.
376 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
377 TP.error("Type inference contradiction found, '" +
378 getName() + "' is not smaller than '" +
379 Other.getName() +"'!");
380
381 }
382
383
384 // Handle int and fp as disjoint sets. This won't work for patterns
385 // that have mixed fp/int types but those are likely rare and would
386 // not have been accepted by this code previously.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000387
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000388 // Okay, find the smallest type from the current set and remove it from the
389 // largest set.
David Greenec83e2032011-02-04 17:01:53 +0000390 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000391 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
392 if (isInteger(TypeVec[i])) {
393 SmallestInt = TypeVec[i];
394 break;
395 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000396 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000397 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
398 SmallestInt = TypeVec[i];
399
David Greenec83e2032011-02-04 17:01:53 +0000400 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000401 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
402 if (isFloatingPoint(TypeVec[i])) {
403 SmallestFP = TypeVec[i];
404 break;
405 }
406 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
407 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
408 SmallestFP = TypeVec[i];
409
410 int OtherIntSize = 0;
411 int OtherFPSize = 0;
412 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
413 Other.TypeVec.begin();
414 TVI != Other.TypeVec.end();
415 /* NULL */) {
416 if (isInteger(*TVI)) {
417 ++OtherIntSize;
418 if (*TVI == SmallestInt) {
419 TVI = Other.TypeVec.erase(TVI);
420 --OtherIntSize;
421 MadeChange = true;
422 continue;
423 }
424 }
425 else if (isFloatingPoint(*TVI)) {
426 ++OtherFPSize;
427 if (*TVI == SmallestFP) {
428 TVI = Other.TypeVec.erase(TVI);
429 --OtherFPSize;
430 MadeChange = true;
431 continue;
432 }
433 }
434 ++TVI;
435 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000436
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000437 // If this is the only type in the large set, the constraint can never be
438 // satisfied.
David Greene9d7f0112011-02-01 19:12:32 +0000439 if ((Other.hasIntegerTypes() && OtherIntSize == 0)
440 || (Other.hasFloatingPointTypes() && OtherFPSize == 0))
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000441 TP.error("Type inference contradiction found, '" +
442 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000443
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000444 // Okay, find the largest type in the Other set and remove it from the
445 // current set.
David Greenec83e2032011-02-04 17:01:53 +0000446 MVT::SimpleValueType LargestInt = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000447 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
448 if (isInteger(Other.TypeVec[i])) {
449 LargestInt = Other.TypeVec[i];
450 break;
451 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000452 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000453 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
454 LargestInt = Other.TypeVec[i];
455
David Greenec83e2032011-02-04 17:01:53 +0000456 MVT::SimpleValueType LargestFP = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000457 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
458 if (isFloatingPoint(Other.TypeVec[i])) {
459 LargestFP = Other.TypeVec[i];
460 break;
461 }
462 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
463 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
464 LargestFP = Other.TypeVec[i];
465
466 int IntSize = 0;
467 int FPSize = 0;
468 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
469 TypeVec.begin();
470 TVI != TypeVec.end();
471 /* NULL */) {
472 if (isInteger(*TVI)) {
473 ++IntSize;
474 if (*TVI == LargestInt) {
475 TVI = TypeVec.erase(TVI);
476 --IntSize;
477 MadeChange = true;
478 continue;
479 }
480 }
481 else if (isFloatingPoint(*TVI)) {
482 ++FPSize;
483 if (*TVI == LargestFP) {
484 TVI = TypeVec.erase(TVI);
485 --FPSize;
486 MadeChange = true;
487 continue;
488 }
489 }
490 ++TVI;
491 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000492
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000493 // If this is the only type in the small set, the constraint can never be
494 // satisfied.
David Greene9d7f0112011-02-01 19:12:32 +0000495 if ((hasIntegerTypes() && IntSize == 0)
496 || (hasFloatingPointTypes() && FPSize == 0))
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000497 TP.error("Type inference contradiction found, '" +
498 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000499
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000500 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000501}
502
503/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner66fb9d22010-03-24 00:01:16 +0000504/// whose element is specified by VTOperand.
505bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattner2cacec52010-03-15 06:00:16 +0000506 TreePattern &TP) {
Chris Lattner66fb9d22010-03-24 00:01:16 +0000507 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattner2cacec52010-03-15 06:00:16 +0000508 bool MadeChange = false;
Chris Lattner66fb9d22010-03-24 00:01:16 +0000509 MadeChange |= EnforceVector(TP);
510 MadeChange |= VTOperand.EnforceScalar(TP);
511
512 // If we know the vector type, it forces the scalar to agree.
513 if (isConcrete()) {
514 EVT IVT = getConcrete();
515 IVT = IVT.getVectorElementType();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000516 return MadeChange |
Chris Lattner66fb9d22010-03-24 00:01:16 +0000517 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
518 }
519
520 // If the scalar type is known, filter out vector types whose element types
521 // disagree.
522 if (!VTOperand.isConcrete())
523 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000524
Chris Lattner66fb9d22010-03-24 00:01:16 +0000525 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000526
Chris Lattner66fb9d22010-03-24 00:01:16 +0000527 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000528
Chris Lattner66fb9d22010-03-24 00:01:16 +0000529 // Filter out all the types which don't have the right element type.
530 for (unsigned i = 0; i != TypeVec.size(); ++i) {
531 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
532 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000533 TypeVec.erase(TypeVec.begin()+i--);
534 MadeChange = true;
535 }
Chris Lattner66fb9d22010-03-24 00:01:16 +0000536 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000537
Chris Lattner2cacec52010-03-15 06:00:16 +0000538 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
539 TP.error("Type inference contradiction found, forcing '" +
540 InputSet.getName() + "' to have a vector element");
541 return MadeChange;
542}
543
David Greene60322692011-01-24 20:53:18 +0000544/// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
545/// vector type specified by VTOperand.
546bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
547 TreePattern &TP) {
548 // "This" must be a vector and "VTOperand" must be a vector.
549 bool MadeChange = false;
550 MadeChange |= EnforceVector(TP);
551 MadeChange |= VTOperand.EnforceVector(TP);
552
553 // "This" must be larger than "VTOperand."
554 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
555
556 // If we know the vector type, it forces the scalar types to agree.
557 if (isConcrete()) {
558 EVT IVT = getConcrete();
559 IVT = IVT.getVectorElementType();
560
561 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
562 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
563 } else if (VTOperand.isConcrete()) {
564 EVT IVT = VTOperand.getConcrete();
565 IVT = IVT.getVectorElementType();
566
567 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
568 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
569 }
570
571 return MadeChange;
572}
573
Chris Lattner2cacec52010-03-15 06:00:16 +0000574//===----------------------------------------------------------------------===//
575// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000576
Scott Michel327d0652008-03-05 17:49:05 +0000577/// Dependent variable map for CodeGenDAGPattern variant generation
578typedef std::map<std::string, int> DepVarMap;
579
580/// Const iterator shorthand for DepVarMap
581typedef DepVarMap::const_iterator DepVarMap_citer;
582
Chris Lattner54379062011-04-17 21:38:24 +0000583static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel327d0652008-03-05 17:49:05 +0000584 if (N->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +0000585 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL)
Scott Michel327d0652008-03-05 17:49:05 +0000586 DepMap[N->getName()]++;
Scott Michel327d0652008-03-05 17:49:05 +0000587 } else {
588 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
589 FindDepVarsOf(N->getChild(i), DepMap);
590 }
591}
Chris Lattner54379062011-04-17 21:38:24 +0000592
593/// Find dependent variables within child patterns
594static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000595 DepVarMap depcounts;
596 FindDepVarsOf(N, depcounts);
597 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner54379062011-04-17 21:38:24 +0000598 if (i->second > 1) // std::pair<std::string, int>
Scott Michel327d0652008-03-05 17:49:05 +0000599 DepVars.insert(i->first);
Scott Michel327d0652008-03-05 17:49:05 +0000600 }
601}
602
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000603#ifndef NDEBUG
Chris Lattner54379062011-04-17 21:38:24 +0000604/// Dump the dependent variable set:
605static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000606 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000607 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000608 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000609 DEBUG(errs() << "[ ");
Jim Grosbachbb168242010-10-08 18:13:57 +0000610 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
611 e = DepVars.end(); i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000612 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000613 }
Chris Lattner569f1212009-08-23 04:44:11 +0000614 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000615 }
616}
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000617#endif
618
Chris Lattner54379062011-04-17 21:38:24 +0000619
620//===----------------------------------------------------------------------===//
621// TreePredicateFn Implementation
622//===----------------------------------------------------------------------===//
623
Chris Lattner7ed13912011-04-17 22:05:17 +0000624/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
625TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
626 assert((getPredCode().empty() || getImmCode().empty()) &&
627 ".td file corrupt: can't have a node predicate *and* an imm predicate");
628}
629
Chris Lattner54379062011-04-17 21:38:24 +0000630std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +0000631 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner54379062011-04-17 21:38:24 +0000632}
633
Chris Lattner7ed13912011-04-17 22:05:17 +0000634std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +0000635 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner7ed13912011-04-17 22:05:17 +0000636}
637
Chris Lattner54379062011-04-17 21:38:24 +0000638
639/// isAlwaysTrue - Return true if this is a noop predicate.
640bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000641 return getPredCode().empty() && getImmCode().empty();
Chris Lattner54379062011-04-17 21:38:24 +0000642}
643
644/// Return the name to use in the generated code to reference this, this is
645/// "Predicate_foo" if from a pattern fragment "foo".
646std::string TreePredicateFn::getFnName() const {
647 return "Predicate_" + PatFragRec->getRecord()->getName();
648}
649
650/// getCodeToRunOnSDNode - Return the code for the function body that
651/// evaluates this predicate. The argument is expected to be in "Node",
652/// not N. This handles casting and conversion to a concrete node type as
653/// appropriate.
654std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000655 // Handle immediate predicates first.
656 std::string ImmCode = getImmCode();
657 if (!ImmCode.empty()) {
658 std::string Result =
659 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner7ed13912011-04-17 22:05:17 +0000660 return Result + ImmCode;
661 }
662
663 // Handle arbitrary node predicates.
664 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner54379062011-04-17 21:38:24 +0000665 std::string ClassName;
666 if (PatFragRec->getOnlyTree()->isLeaf())
667 ClassName = "SDNode";
668 else {
669 Record *Op = PatFragRec->getOnlyTree()->getOperator();
670 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
671 }
672 std::string Result;
673 if (ClassName == "SDNode")
674 Result = " SDNode *N = Node;\n";
675 else
676 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
677
678 return Result + getPredCode();
Scott Michel327d0652008-03-05 17:49:05 +0000679}
680
Chris Lattner6cefb772008-01-05 22:25:12 +0000681//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000682// PatternToMatch implementation
683//
684
Chris Lattner48e86db2010-03-29 01:40:38 +0000685
686/// getPatternSize - Return the 'size' of this pattern. We want to match large
687/// patterns before small ones. This is used to determine the size of a
688/// pattern.
689static unsigned getPatternSize(const TreePatternNode *P,
690 const CodeGenDAGPatterns &CGP) {
691 unsigned Size = 3; // The node itself.
692 // If the root node is a ConstantSDNode, increases its size.
693 // e.g. (set R32:$dst, 0).
David Greene05bce0b2011-07-29 22:43:06 +0000694 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000695 Size += 2;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000696
Chris Lattner48e86db2010-03-29 01:40:38 +0000697 // FIXME: This is a hack to statically increase the priority of patterns
698 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
699 // Later we can allow complexity / cost for each pattern to be (optionally)
700 // specified. To get best possible pattern match we'll need to dynamically
701 // calculate the complexity of all patterns a dag can potentially map to.
702 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
703 if (AM)
704 Size += AM->getNumOperands() * 3;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000705
Chris Lattner48e86db2010-03-29 01:40:38 +0000706 // If this node has some predicate function that must match, it adds to the
707 // complexity of this node.
708 if (!P->getPredicateFns().empty())
709 ++Size;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000710
Chris Lattner48e86db2010-03-29 01:40:38 +0000711 // Count children in the count if they are also nodes.
712 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
713 TreePatternNode *Child = P->getChild(i);
714 if (!Child->isLeaf() && Child->getNumTypes() &&
715 Child->getType(0) != MVT::Other)
716 Size += getPatternSize(Child, CGP);
717 else if (Child->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +0000718 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000719 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
720 else if (Child->getComplexPatternInfo(CGP))
721 Size += getPatternSize(Child, CGP);
722 else if (!Child->getPredicateFns().empty())
723 ++Size;
724 }
725 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000726
Chris Lattner48e86db2010-03-29 01:40:38 +0000727 return Size;
728}
729
730/// Compute the complexity metric for the input pattern. This roughly
731/// corresponds to the number of nodes that are covered.
732unsigned PatternToMatch::
733getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
734 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
735}
736
737
Dan Gohman22bb3112008-08-22 00:20:26 +0000738/// getPredicateCheck - Return a single string containing all of this
739/// pattern's predicates concatenated with "&&" operators.
740///
741std::string PatternToMatch::getPredicateCheck() const {
742 std::string PredicateCheck;
743 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +0000744 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
Dan Gohman22bb3112008-08-22 00:20:26 +0000745 Record *Def = Pred->getDef();
746 if (!Def->isSubClassOf("Predicate")) {
747#ifndef NDEBUG
748 Def->dump();
749#endif
Craig Topper655b8de2012-02-05 07:21:30 +0000750 llvm_unreachable("Unknown predicate type!");
Dan Gohman22bb3112008-08-22 00:20:26 +0000751 }
752 if (!PredicateCheck.empty())
753 PredicateCheck += " && ";
754 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
755 }
756 }
757
758 return PredicateCheck;
759}
760
761//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000762// SDTypeConstraint implementation
763//
764
765SDTypeConstraint::SDTypeConstraint(Record *R) {
766 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000767
Chris Lattner6cefb772008-01-05 22:25:12 +0000768 if (R->isSubClassOf("SDTCisVT")) {
769 ConstraintType = SDTCisVT;
770 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerc8122612010-03-28 06:04:39 +0000771 if (x.SDTCisVT_Info.VT == MVT::isVoid)
772 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000773
Chris Lattner6cefb772008-01-05 22:25:12 +0000774 } else if (R->isSubClassOf("SDTCisPtrTy")) {
775 ConstraintType = SDTCisPtrTy;
776 } else if (R->isSubClassOf("SDTCisInt")) {
777 ConstraintType = SDTCisInt;
778 } else if (R->isSubClassOf("SDTCisFP")) {
779 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000780 } else if (R->isSubClassOf("SDTCisVec")) {
781 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000782 } else if (R->isSubClassOf("SDTCisSameAs")) {
783 ConstraintType = SDTCisSameAs;
784 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
785 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
786 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000787 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000788 R->getValueAsInt("OtherOperandNum");
789 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
790 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000791 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000792 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000793 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
794 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000795 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene60322692011-01-24 20:53:18 +0000796 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
797 ConstraintType = SDTCisSubVecOfVec;
798 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
799 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000800 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000801 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000802 exit(1);
803 }
804}
805
806/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000807/// N, and the result number in ResNo.
808static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
809 const SDNodeInfo &NodeInfo,
810 unsigned &ResNo) {
811 unsigned NumResults = NodeInfo.getNumResults();
812 if (OpNo < NumResults) {
813 ResNo = OpNo;
814 return N;
815 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000816
Chris Lattner2e68a022010-03-19 21:56:21 +0000817 OpNo -= NumResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000818
Chris Lattner2e68a022010-03-19 21:56:21 +0000819 if (OpNo >= N->getNumChildren()) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000820 errs() << "Invalid operand number in type constraint "
Chris Lattner2e68a022010-03-19 21:56:21 +0000821 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000822 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000823 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000824 exit(1);
825 }
826
Chris Lattner2e68a022010-03-19 21:56:21 +0000827 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000828}
829
830/// ApplyTypeConstraint - Given a node in a pattern, apply this type
831/// constraint to the nodes operands. This returns true if it makes a
832/// change, false otherwise. If a type contradiction is found, throw an
833/// exception.
834bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
835 const SDNodeInfo &NodeInfo,
836 TreePattern &TP) const {
Chris Lattner2e68a022010-03-19 21:56:21 +0000837 unsigned ResNo = 0; // The result number being referenced.
838 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000839
Chris Lattner6cefb772008-01-05 22:25:12 +0000840 switch (ConstraintType) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000841 case SDTCisVT:
842 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000843 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000844 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000845 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000846 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000847 case SDTCisInt:
848 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000849 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000850 case SDTCisFP:
851 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000852 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000853 case SDTCisVec:
854 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000855 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000856 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000857 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000858 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000859 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000860 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
861 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000862 }
863 case SDTCisVTSmallerThanOp: {
864 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
865 // have an integer type that is smaller than the VT.
866 if (!NodeToApply->isLeaf() ||
David Greene05bce0b2011-07-29 22:43:06 +0000867 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
868 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Chris Lattner6cefb772008-01-05 22:25:12 +0000869 ->isSubClassOf("ValueType"))
870 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000871 MVT::SimpleValueType VT =
David Greene05bce0b2011-07-29 22:43:06 +0000872 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000873
Chris Lattnercc878302010-03-24 00:06:46 +0000874 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000875
Chris Lattner2e68a022010-03-19 21:56:21 +0000876 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000877 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000878 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
879 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000880
Chris Lattnercc878302010-03-24 00:06:46 +0000881 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000882 }
883 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000884 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000885 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000886 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
887 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000888 return NodeToApply->getExtType(ResNo).
889 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000890 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000891 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000892 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000893 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000894 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
895 VResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000896
Chris Lattner66fb9d22010-03-24 00:01:16 +0000897 // Filter vector types out of VecOperand that don't have the right element
898 // type.
899 return VecOperand->getExtType(VResNo).
900 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000901 }
David Greene60322692011-01-24 20:53:18 +0000902 case SDTCisSubVecOfVec: {
903 unsigned VResNo = 0;
904 TreePatternNode *BigVecOperand =
905 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
906 VResNo);
907
908 // Filter vector types out of BigVecOperand that don't have the
909 // right subvector type.
910 return BigVecOperand->getExtType(VResNo).
911 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
912 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000913 }
David Blaikie58bd1512012-01-17 07:00:13 +0000914 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner6cefb772008-01-05 22:25:12 +0000915}
916
917//===----------------------------------------------------------------------===//
918// SDNodeInfo implementation
919//
920SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
921 EnumName = R->getValueAsString("Opcode");
922 SDClassName = R->getValueAsString("SDClass");
923 Record *TypeProfile = R->getValueAsDef("TypeProfile");
924 NumResults = TypeProfile->getValueAsInt("NumResults");
925 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000926
Chris Lattner6cefb772008-01-05 22:25:12 +0000927 // Parse the properties.
928 Properties = 0;
929 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
930 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
931 if (PropList[i]->getName() == "SDNPCommutative") {
932 Properties |= 1 << SDNPCommutative;
933 } else if (PropList[i]->getName() == "SDNPAssociative") {
934 Properties |= 1 << SDNPAssociative;
935 } else if (PropList[i]->getName() == "SDNPHasChain") {
936 Properties |= 1 << SDNPHasChain;
Chris Lattner036609b2010-12-23 18:28:41 +0000937 } else if (PropList[i]->getName() == "SDNPOutGlue") {
938 Properties |= 1 << SDNPOutGlue;
939 } else if (PropList[i]->getName() == "SDNPInGlue") {
940 Properties |= 1 << SDNPInGlue;
941 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
942 Properties |= 1 << SDNPOptInGlue;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000943 } else if (PropList[i]->getName() == "SDNPMayStore") {
944 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000945 } else if (PropList[i]->getName() == "SDNPMayLoad") {
946 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000947 } else if (PropList[i]->getName() == "SDNPSideEffect") {
948 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000949 } else if (PropList[i]->getName() == "SDNPMemOperand") {
950 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000951 } else if (PropList[i]->getName() == "SDNPVariadic") {
952 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000953 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000954 errs() << "Unknown SD Node property '" << PropList[i]->getName()
955 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000956 exit(1);
957 }
958 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000959
960
Chris Lattner6cefb772008-01-05 22:25:12 +0000961 // Parse the type constraints.
962 std::vector<Record*> ConstraintList =
963 TypeProfile->getValueAsListOfDefs("Constraints");
964 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
965}
966
Chris Lattner22579812010-02-28 00:22:30 +0000967/// getKnownType - If the type constraints on this node imply a fixed type
968/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000969/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000970MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +0000971 unsigned NumResults = getNumResults();
972 assert(NumResults <= 1 &&
973 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +0000974 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000975
Chris Lattner22579812010-02-28 00:22:30 +0000976 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
977 // Make sure that this applies to the correct node result.
978 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
979 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000980
Chris Lattner22579812010-02-28 00:22:30 +0000981 switch (TypeConstraints[i].ConstraintType) {
982 default: break;
983 case SDTypeConstraint::SDTCisVT:
984 return TypeConstraints[i].x.SDTCisVT_Info.VT;
985 case SDTypeConstraint::SDTCisPtrTy:
986 return MVT::iPTR;
987 }
988 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000989 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000990}
991
Chris Lattner6cefb772008-01-05 22:25:12 +0000992//===----------------------------------------------------------------------===//
993// TreePatternNode implementation
994//
995
996TreePatternNode::~TreePatternNode() {
997#if 0 // FIXME: implement refcounted tree nodes!
998 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
999 delete getChild(i);
1000#endif
1001}
1002
Chris Lattnerd7349192010-03-19 21:37:09 +00001003static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1004 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +00001005 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +00001006 return 0; // All return nothing.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001007
Chris Lattner93dc92e2010-03-22 20:56:36 +00001008 if (Operator->isSubClassOf("Intrinsic"))
1009 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001010
Chris Lattnerd7349192010-03-19 21:37:09 +00001011 if (Operator->isSubClassOf("SDNode"))
1012 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001013
Chris Lattnerd7349192010-03-19 21:37:09 +00001014 if (Operator->isSubClassOf("PatFrag")) {
1015 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1016 // the forward reference case where one pattern fragment references another
1017 // before it is processed.
1018 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1019 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001020
Chris Lattnerd7349192010-03-19 21:37:09 +00001021 // Get the result tree.
David Greene05bce0b2011-07-29 22:43:06 +00001022 DagInit *Tree = Operator->getValueAsDag("Fragment");
Chris Lattnerd7349192010-03-19 21:37:09 +00001023 Record *Op = 0;
David Greene05bce0b2011-07-29 22:43:06 +00001024 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
1025 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
Chris Lattnerd7349192010-03-19 21:37:09 +00001026 assert(Op && "Invalid Fragment");
1027 return GetNumNodeResults(Op, CDP);
1028 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001029
Chris Lattnerd7349192010-03-19 21:37:09 +00001030 if (Operator->isSubClassOf("Instruction")) {
1031 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001032
1033 // FIXME: Should allow access to all the results here.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001034 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001035
Chris Lattner9414ae52010-03-27 20:09:24 +00001036 // Add on one implicit def if it has a resolvable type.
1037 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1038 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001039 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +00001040 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001041
Chris Lattnerd7349192010-03-19 21:37:09 +00001042 if (Operator->isSubClassOf("SDNodeXForm"))
1043 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001044
Chris Lattnerd7349192010-03-19 21:37:09 +00001045 Operator->dump();
1046 errs() << "Unhandled node in GetNumNodeResults\n";
1047 exit(1);
1048}
1049
1050void TreePatternNode::print(raw_ostream &OS) const {
1051 if (isLeaf())
1052 OS << *getLeafValue();
1053 else
1054 OS << '(' << getOperator()->getName();
1055
1056 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1057 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +00001058
1059 if (!isLeaf()) {
1060 if (getNumChildren() != 0) {
1061 OS << " ";
1062 getChild(0)->print(OS);
1063 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1064 OS << ", ";
1065 getChild(i)->print(OS);
1066 }
1067 }
1068 OS << ")";
1069 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001070
Dan Gohman0540e172008-10-15 06:17:21 +00001071 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner54379062011-04-17 21:38:24 +00001072 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +00001073 if (TransformFn)
1074 OS << "<<X:" << TransformFn->getName() << ">>";
1075 if (!getName().empty())
1076 OS << ":$" << getName();
1077
1078}
1079void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001080 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +00001081}
1082
Scott Michel327d0652008-03-05 17:49:05 +00001083/// isIsomorphicTo - Return true if this node is recursively
1084/// isomorphic to the specified node. For this comparison, the node's
1085/// entire state is considered. The assigned name is ignored, since
1086/// nodes with differing names are considered isomorphic. However, if
1087/// the assigned name is present in the dependent variable set, then
1088/// the assigned name is considered significant and the node is
1089/// isomorphic if the names match.
1090bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1091 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001092 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +00001093 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +00001094 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00001095 getTransformFn() != N->getTransformFn())
1096 return false;
1097
1098 if (isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001099 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1100 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +00001101 return ((DI->getDef() == NDI->getDef())
1102 && (DepVars.find(getName()) == DepVars.end()
1103 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +00001104 }
1105 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001106 return getLeafValue() == N->getLeafValue();
1107 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001108
Chris Lattner6cefb772008-01-05 22:25:12 +00001109 if (N->getOperator() != getOperator() ||
1110 N->getNumChildren() != getNumChildren()) return false;
1111 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00001112 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +00001113 return false;
1114 return true;
1115}
1116
1117/// clone - Make a copy of this tree and all of its children.
1118///
1119TreePatternNode *TreePatternNode::clone() const {
1120 TreePatternNode *New;
1121 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001122 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001123 } else {
1124 std::vector<TreePatternNode*> CChildren;
1125 CChildren.reserve(Children.size());
1126 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1127 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +00001128 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001129 }
1130 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001131 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +00001132 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00001133 New->setTransformFn(getTransformFn());
1134 return New;
1135}
1136
Chris Lattner47661322010-02-14 22:22:58 +00001137/// RemoveAllTypes - Recursively strip all the types of this tree.
1138void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +00001139 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1140 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +00001141 if (isLeaf()) return;
1142 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1143 getChild(i)->RemoveAllTypes();
1144}
1145
1146
Chris Lattner6cefb772008-01-05 22:25:12 +00001147/// SubstituteFormalArguments - Replace the formal arguments in this tree
1148/// with actual values specified by ArgMap.
1149void TreePatternNode::
1150SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1151 if (isLeaf()) return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001152
Chris Lattner6cefb772008-01-05 22:25:12 +00001153 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1154 TreePatternNode *Child = getChild(i);
1155 if (Child->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001156 Init *Val = Child->getLeafValue();
1157 if (dynamic_cast<DefInit*>(Val) &&
1158 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001159 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +00001160 TreePatternNode *NewChild = ArgMap[Child->getName()];
1161 assert(NewChild && "Couldn't find formal argument!");
1162 assert((Child->getPredicateFns().empty() ||
1163 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1164 "Non-empty child predicate clobbered!");
1165 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +00001166 }
1167 } else {
1168 getChild(i)->SubstituteFormalArguments(ArgMap);
1169 }
1170 }
1171}
1172
1173
1174/// InlinePatternFragments - If this pattern refers to any pattern
1175/// fragments, inline them into place, giving us a pattern without any
1176/// PatFrag references.
1177TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1178 if (isLeaf()) return this; // nothing to do.
1179 Record *Op = getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001180
Chris Lattner6cefb772008-01-05 22:25:12 +00001181 if (!Op->isSubClassOf("PatFrag")) {
1182 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00001183 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1184 TreePatternNode *Child = getChild(i);
1185 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1186
1187 assert((Child->getPredicateFns().empty() ||
1188 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1189 "Non-empty child predicate clobbered!");
1190
1191 setChild(i, NewChild);
1192 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001193 return this;
1194 }
1195
1196 // Otherwise, we found a reference to a fragment. First, look up its
1197 // TreePattern record.
1198 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001199
Chris Lattner6cefb772008-01-05 22:25:12 +00001200 // Verify that we are passing the right number of operands.
1201 if (Frag->getNumArgs() != Children.size())
1202 TP.error("'" + Op->getName() + "' fragment requires " +
1203 utostr(Frag->getNumArgs()) + " operands!");
1204
1205 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1206
Chris Lattner54379062011-04-17 21:38:24 +00001207 TreePredicateFn PredFn(Frag);
1208 if (!PredFn.isAlwaysTrue())
1209 FragTree->addPredicateFn(PredFn);
Dan Gohman0540e172008-10-15 06:17:21 +00001210
Chris Lattner6cefb772008-01-05 22:25:12 +00001211 // Resolve formal arguments to their actual value.
1212 if (Frag->getNumArgs()) {
1213 // Compute the map of formal to actual arguments.
1214 std::map<std::string, TreePatternNode*> ArgMap;
1215 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1216 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001217
Chris Lattner6cefb772008-01-05 22:25:12 +00001218 FragTree->SubstituteFormalArguments(ArgMap);
1219 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001220
Chris Lattner6cefb772008-01-05 22:25:12 +00001221 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001222 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1223 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +00001224
1225 // Transfer in the old predicates.
1226 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1227 FragTree->addPredicateFn(getPredicateFns()[i]);
1228
Chris Lattner6cefb772008-01-05 22:25:12 +00001229 // Get a new copy of this fragment to stitch into here.
1230 //delete this; // FIXME: implement refcounting!
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001231
Chris Lattner2ca698d2008-06-30 03:02:03 +00001232 // The fragment we inlined could have recursive inlining that is needed. See
1233 // if there are any pattern fragments in it and inline them as needed.
1234 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001235}
1236
1237/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +00001238/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +00001239/// references from the register file information, for example.
1240///
Chris Lattnerd7349192010-03-19 21:37:09 +00001241static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1242 bool NotRegisters, TreePattern &TP) {
Owen Andersonbea6f612011-06-27 21:06:21 +00001243 // Check to see if this is a register operand.
1244 if (R->isSubClassOf("RegisterOperand")) {
1245 assert(ResNo == 0 && "Regoperand ref only has one result!");
1246 if (NotRegisters)
1247 return EEVT::TypeSet(); // Unknown.
1248 Record *RegClass = R->getValueAsDef("RegClass");
1249 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1250 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1251 }
1252
Chris Lattner2cacec52010-03-15 06:00:16 +00001253 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00001254 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001255 assert(ResNo == 0 && "Regclass ref only has one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001256 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001257 return EEVT::TypeSet(); // Unknown.
1258 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1259 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001260 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001261
Chris Lattner640a3f52010-03-23 23:50:31 +00001262 if (R->isSubClassOf("PatFrag")) {
1263 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001264 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001265 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001266 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001267
Chris Lattner640a3f52010-03-23 23:50:31 +00001268 if (R->isSubClassOf("Register")) {
1269 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001270 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001271 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001272 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001273 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001274 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00001275
1276 if (R->isSubClassOf("SubRegIndex")) {
1277 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1278 return EEVT::TypeSet();
1279 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001280
Chris Lattner640a3f52010-03-23 23:50:31 +00001281 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1282 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001283 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001284 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001285 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001286
Chris Lattner640a3f52010-03-23 23:50:31 +00001287 if (R->isSubClassOf("ComplexPattern")) {
1288 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001289 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001290 return EEVT::TypeSet(); // Unknown.
1291 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1292 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001293 }
1294 if (R->isSubClassOf("PointerLikeRegClass")) {
1295 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001296 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001297 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001298
Chris Lattner640a3f52010-03-23 23:50:31 +00001299 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1300 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001301 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001302 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001303 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001304
Chris Lattner6cefb772008-01-05 22:25:12 +00001305 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001306 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001307}
1308
Chris Lattnere67bde52008-01-06 05:36:50 +00001309
1310/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1311/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1312const CodeGenIntrinsic *TreePatternNode::
1313getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1314 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1315 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1316 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1317 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001318
1319 unsigned IID =
David Greene05bce0b2011-07-29 22:43:06 +00001320 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
Chris Lattnere67bde52008-01-06 05:36:50 +00001321 return &CDP.getIntrinsicInfo(IID);
1322}
1323
Chris Lattner47661322010-02-14 22:22:58 +00001324/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1325/// return the ComplexPattern information, otherwise return null.
1326const ComplexPattern *
1327TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1328 if (!isLeaf()) return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001329
David Greene05bce0b2011-07-29 22:43:06 +00001330 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
Chris Lattner47661322010-02-14 22:22:58 +00001331 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1332 return &CGP.getComplexPattern(DI->getDef());
1333 return 0;
1334}
1335
1336/// NodeHasProperty - Return true if this node has the specified property.
1337bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001338 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001339 if (isLeaf()) {
1340 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1341 return CP->hasProperty(Property);
1342 return false;
1343 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001344
Chris Lattner47661322010-02-14 22:22:58 +00001345 Record *Operator = getOperator();
1346 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001347
Chris Lattner47661322010-02-14 22:22:58 +00001348 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1349}
1350
1351
1352
1353
1354/// TreeHasProperty - Return true if any node in this tree has the specified
1355/// property.
1356bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001357 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001358 if (NodeHasProperty(Property, CGP))
1359 return true;
1360 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1361 if (getChild(i)->TreeHasProperty(Property, CGP))
1362 return true;
1363 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001364}
Chris Lattner47661322010-02-14 22:22:58 +00001365
Evan Cheng6bd95672008-06-16 20:29:38 +00001366/// isCommutativeIntrinsic - Return true if the node corresponds to a
1367/// commutative intrinsic.
1368bool
1369TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1370 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1371 return Int->isCommutative;
1372 return false;
1373}
1374
Chris Lattnere67bde52008-01-06 05:36:50 +00001375
Bob Wilson6c01ca92009-01-05 17:23:09 +00001376/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001377/// this node and its children in the tree. This returns true if it makes a
1378/// change, false otherwise. If a type contradiction is found, throw an
1379/// exception.
1380bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001381 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001382 if (isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001383 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001384 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001385 bool MadeChange = false;
1386 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1387 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1388 NotRegisters, TP), TP);
1389 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001390 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001391
David Greene05bce0b2011-07-29 22:43:06 +00001392 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001393 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001394
Chris Lattnerd7349192010-03-19 21:37:09 +00001395 // Int inits are always integers. :)
1396 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001397
Chris Lattnerd7349192010-03-19 21:37:09 +00001398 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001399 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001400
Chris Lattnerd7349192010-03-19 21:37:09 +00001401 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001402 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1403 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001404
Chris Lattner2cacec52010-03-15 06:00:16 +00001405 unsigned Size = EVT(VT).getSizeInBits();
1406 // Make sure that the value is representable for this type.
1407 if (Size >= 32) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001408
Richard Smith1144af32012-08-24 23:29:28 +00001409 // Check that the value doesn't use more bits than we have. It must either
1410 // be a sign- or zero-extended equivalent of the original.
1411 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1412 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattner2cacec52010-03-15 06:00:16 +00001413 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001414
Richard Smith1144af32012-08-24 23:29:28 +00001415 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerd7349192010-03-19 21:37:09 +00001416 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001417 return MadeChange;
1418 }
1419 return false;
1420 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001421
Chris Lattner6cefb772008-01-05 22:25:12 +00001422 // special handling for set, which isn't really an SDNode.
1423 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001424 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1425 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001426 unsigned NC = getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001427
Chris Lattnerd7349192010-03-19 21:37:09 +00001428 TreePatternNode *SetVal = getChild(NC-1);
1429 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1430
Chris Lattner6cefb772008-01-05 22:25:12 +00001431 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001432 TreePatternNode *Child = getChild(i);
1433 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001434
Chris Lattner6cefb772008-01-05 22:25:12 +00001435 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001436 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1437 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001438 }
1439 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001440 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001441
Chris Lattner310adf12010-03-27 02:53:27 +00001442 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001443 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1444
Chris Lattner6cefb772008-01-05 22:25:12 +00001445 bool MadeChange = false;
1446 for (unsigned i = 0; i < getNumChildren(); ++i)
1447 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001448 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001449 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001450
Chris Lattner6eb30122010-02-23 05:51:07 +00001451 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001452 bool MadeChange = false;
1453 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1454 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001455
Chris Lattnerd7349192010-03-19 21:37:09 +00001456 assert(getChild(0)->getNumTypes() == 1 &&
1457 getChild(1)->getNumTypes() == 1 && "Unhandled case");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001458
Chris Lattner2cacec52010-03-15 06:00:16 +00001459 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1460 // what type it gets, so if it didn't get a concrete type just give it the
1461 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001462 if (!getChild(1)->hasTypeSet(0) &&
1463 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1464 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1465 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001466 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001467 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001468 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001469
Chris Lattner6eb30122010-02-23 05:51:07 +00001470 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001471 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001472
Chris Lattner6cefb772008-01-05 22:25:12 +00001473 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001474 unsigned NumRetVTs = Int->IS.RetVTs.size();
1475 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001476
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001477 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001478 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001479
Chris Lattnerd7349192010-03-19 21:37:09 +00001480 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001481 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001482 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001483 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001484
1485 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001486 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001487
Chris Lattnerd7349192010-03-19 21:37:09 +00001488 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1489 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001490
Chris Lattnerd7349192010-03-19 21:37:09 +00001491 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1492 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1493 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001494 }
1495 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001496 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001497
Chris Lattner6eb30122010-02-23 05:51:07 +00001498 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001499 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001500
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001501 // Check that the number of operands is sane. Negative operands -> varargs.
1502 if (NI.getNumOperands() >= 0 &&
1503 getNumChildren() != (unsigned)NI.getNumOperands())
1504 TP.error(getOperator()->getName() + " node requires exactly " +
1505 itostr(NI.getNumOperands()) + " operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001506
Chris Lattner6cefb772008-01-05 22:25:12 +00001507 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1508 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1509 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001510 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001511 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001512
Chris Lattner6eb30122010-02-23 05:51:07 +00001513 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001514 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001515 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001516 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001517
Chris Lattner0be6fe72010-03-27 19:15:02 +00001518 bool MadeChange = false;
1519
1520 // Apply the result types to the node, these come from the things in the
1521 // (outs) list of the instruction.
1522 // FIXME: Cap at one result so far.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001523 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001524 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1525 Record *ResultNode = Inst.getResult(ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001526
Chris Lattnera938ac62009-07-29 20:43:05 +00001527 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001528 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
Owen Andersonbea6f612011-06-27 21:06:21 +00001529 } else if (ResultNode->isSubClassOf("RegisterOperand")) {
1530 Record *RegClass = ResultNode->getValueAsDef("RegClass");
1531 const CodeGenRegisterClass &RC =
1532 CDP.getTargetInfo().getRegisterClass(RegClass);
1533 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Owen Anderson83c0eef2012-09-11 23:47:08 +00001534 } else if (ResultNode->isSubClassOf("unknown_class")) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001535 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001536 } else {
1537 assert(ResultNode->isSubClassOf("RegisterClass") &&
1538 "Operands should be register classes!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001539 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001540 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001541 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001542 }
Chris Lattner0be6fe72010-03-27 19:15:02 +00001543 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001544
Chris Lattner0be6fe72010-03-27 19:15:02 +00001545 // If the instruction has implicit defs, we apply the first one as a result.
1546 // FIXME: This sucks, it should apply all implicit defs.
1547 if (!InstInfo.ImplicitDefs.empty()) {
1548 unsigned ResNo = NumResultsToAdd;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001549
Chris Lattner9414ae52010-03-27 20:09:24 +00001550 // FIXME: Generalize to multiple possible types and multiple possible
1551 // ImplicitDefs.
1552 MVT::SimpleValueType VT =
1553 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001554
Chris Lattner9414ae52010-03-27 20:09:24 +00001555 if (VT != MVT::Other)
1556 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001557 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001558
Chris Lattner2cacec52010-03-15 06:00:16 +00001559 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1560 // be the same.
1561 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001562 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1563 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1564 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001565 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001566
1567 unsigned ChildNo = 0;
1568 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1569 Record *OperandNode = Inst.getOperand(i);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001570
Chris Lattner6cefb772008-01-05 22:25:12 +00001571 // If the instruction expects a predicate or optional def operand, we
1572 // codegen this by setting the operand to it's default value if it has a
1573 // non-empty DefaultOps field.
Tom Stellard6d3d7652012-09-06 14:15:52 +00001574 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001575 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1576 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001577
Chris Lattner6cefb772008-01-05 22:25:12 +00001578 // Verify that we didn't run out of provided operands.
1579 if (ChildNo >= getNumChildren())
1580 TP.error("Instruction '" + getOperator()->getName() +
1581 "' expects more operands than were provided.");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001582
Owen Anderson825b72b2009-08-11 20:47:22 +00001583 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001584 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001585 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001586
Chris Lattner6cefb772008-01-05 22:25:12 +00001587 if (OperandNode->isSubClassOf("RegisterClass")) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001588 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001589 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001590 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Owen Andersonbea6f612011-06-27 21:06:21 +00001591 } else if (OperandNode->isSubClassOf("RegisterOperand")) {
1592 Record *RegClass = OperandNode->getValueAsDef("RegClass");
1593 const CodeGenRegisterClass &RC =
1594 CDP.getTargetInfo().getRegisterClass(RegClass);
1595 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001596 } else if (OperandNode->isSubClassOf("Operand")) {
1597 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattner0be6fe72010-03-27 19:15:02 +00001598 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001599 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001600 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
Owen Anderson83c0eef2012-09-11 23:47:08 +00001601 } else if (OperandNode->isSubClassOf("unknown_class")) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001602 // Nothing to do.
Craig Topper655b8de2012-02-05 07:21:30 +00001603 } else
1604 llvm_unreachable("Unknown operand type!");
1605
Chris Lattner6cefb772008-01-05 22:25:12 +00001606 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1607 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001608
Christopher Lamb02f69372008-03-10 04:16:09 +00001609 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001610 TP.error("Instruction '" + getOperator()->getName() +
1611 "' was provided too many operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001612
Chris Lattner6cefb772008-01-05 22:25:12 +00001613 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001614 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001615
Chris Lattner6eb30122010-02-23 05:51:07 +00001616 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001617
Chris Lattner6eb30122010-02-23 05:51:07 +00001618 // Node transforms always take one operand.
1619 if (getNumChildren() != 1)
1620 TP.error("Node transform '" + getOperator()->getName() +
1621 "' requires one operand!");
1622
Chris Lattner2cacec52010-03-15 06:00:16 +00001623 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1624
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001625
Chris Lattner6eb30122010-02-23 05:51:07 +00001626 // If either the output or input of the xform does not have exact
1627 // type info. We assume they must be the same. Otherwise, it is perfectly
1628 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001629#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001630 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001631 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1632 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001633 return MadeChange;
1634 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001635#endif
1636 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001637}
1638
1639/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1640/// RHS of a commutative operation, not the on LHS.
1641static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1642 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1643 return true;
David Greene05bce0b2011-07-29 22:43:06 +00001644 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
Chris Lattner6cefb772008-01-05 22:25:12 +00001645 return true;
1646 return false;
1647}
1648
1649
1650/// canPatternMatch - If it is impossible for this pattern to match on this
1651/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001652/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001653/// that can never possibly work), and to prevent the pattern permuter from
1654/// generating stuff that is useless.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001655bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001656 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001657 if (isLeaf()) return true;
1658
1659 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1660 if (!getChild(i)->canPatternMatch(Reason, CDP))
1661 return false;
1662
1663 // If this is an intrinsic, handle cases that would make it not match. For
1664 // example, if an operand is required to be an immediate.
1665 if (getOperator()->isSubClassOf("Intrinsic")) {
1666 // TODO:
1667 return true;
1668 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001669
Chris Lattner6cefb772008-01-05 22:25:12 +00001670 // If this node is a commutative operator, check that the LHS isn't an
1671 // immediate.
1672 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001673 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1674 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001675 // Scan all of the operands of the node and make sure that only the last one
1676 // is a constant node, unless the RHS also is.
1677 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001678 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1679 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001680 if (OnlyOnRHSOfCommutative(getChild(i))) {
1681 Reason="Immediate value must be on the RHS of commutative operators!";
1682 return false;
1683 }
1684 }
1685 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001686
Chris Lattner6cefb772008-01-05 22:25:12 +00001687 return true;
1688}
1689
1690//===----------------------------------------------------------------------===//
1691// TreePattern implementation
1692//
1693
David Greene05bce0b2011-07-29 22:43:06 +00001694TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001695 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001696 isInputPattern = isInput;
1697 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattnerc2173052010-03-28 06:50:34 +00001698 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001699}
1700
David Greene05bce0b2011-07-29 22:43:06 +00001701TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001702 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001703 isInputPattern = isInput;
Chris Lattnerc2173052010-03-28 06:50:34 +00001704 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001705}
1706
1707TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001708 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001709 isInputPattern = isInput;
1710 Trees.push_back(Pat);
1711}
1712
Chris Lattner6cefb772008-01-05 22:25:12 +00001713void TreePattern::error(const std::string &Msg) const {
1714 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001715 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001716}
1717
Chris Lattner2cacec52010-03-15 06:00:16 +00001718void TreePattern::ComputeNamedNodes() {
1719 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1720 ComputeNamedNodes(Trees[i]);
1721}
1722
1723void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1724 if (!N->getName().empty())
1725 NamedNodes[N->getName()].push_back(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001726
Chris Lattner2cacec52010-03-15 06:00:16 +00001727 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1728 ComputeNamedNodes(N->getChild(i));
1729}
1730
Chris Lattnerd7349192010-03-19 21:37:09 +00001731
David Greene05bce0b2011-07-29 22:43:06 +00001732TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1733 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001734 Record *R = DI->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001735
Chris Lattnerc2173052010-03-28 06:50:34 +00001736 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbach66c9ee72011-07-06 23:38:13 +00001737 // TreePatternNode of its own. For example:
Chris Lattnerc2173052010-03-28 06:50:34 +00001738 /// (foo GPR, imm) -> (foo GPR, (imm))
1739 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenedcd35c72011-07-29 19:07:07 +00001740 return ParseTreePattern(
1741 DagInit::get(DI, "",
David Greene05bce0b2011-07-29 22:43:06 +00001742 std::vector<std::pair<Init*, std::string> >()),
David Greenedcd35c72011-07-29 19:07:07 +00001743 OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001744
Chris Lattnerc2173052010-03-28 06:50:34 +00001745 // Input argument?
1746 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001747 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001748 if (OpName.empty())
1749 error("'node' argument requires a name to match with operand list");
1750 Args.push_back(OpName);
1751 }
1752
1753 Res->setName(OpName);
1754 return Res;
1755 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001756
David Greene05bce0b2011-07-29 22:43:06 +00001757 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001758 if (!OpName.empty())
1759 error("Constant int argument should not have a name!");
1760 return new TreePatternNode(II, 1);
1761 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001762
David Greene05bce0b2011-07-29 22:43:06 +00001763 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001764 // Turn this into an IntInit.
David Greene05bce0b2011-07-29 22:43:06 +00001765 Init *II = BI->convertInitializerTo(IntRecTy::get());
1766 if (II == 0 || !dynamic_cast<IntInit*>(II))
Chris Lattnerc2173052010-03-28 06:50:34 +00001767 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001768 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00001769 }
1770
David Greene05bce0b2011-07-29 22:43:06 +00001771 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
Chris Lattnerc2173052010-03-28 06:50:34 +00001772 if (!Dag) {
1773 TheInit->dump();
1774 error("Pattern has unexpected init kind!");
1775 }
David Greene05bce0b2011-07-29 22:43:06 +00001776 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001777 if (!OpDef) error("Pattern has unexpected operator type!");
1778 Record *Operator = OpDef->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001779
Chris Lattner6cefb772008-01-05 22:25:12 +00001780 if (Operator->isSubClassOf("ValueType")) {
1781 // If the operator is a ValueType, then this must be "type cast" of a leaf
1782 // node.
1783 if (Dag->getNumArgs() != 1)
1784 error("Type cast only takes one operand!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001785
Chris Lattnerc2173052010-03-28 06:50:34 +00001786 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001787
Chris Lattner6cefb772008-01-05 22:25:12 +00001788 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001789 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1790 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001791
Chris Lattnerc2173052010-03-28 06:50:34 +00001792 if (!OpName.empty())
1793 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001794 return New;
1795 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001796
Chris Lattner6cefb772008-01-05 22:25:12 +00001797 // Verify that this is something that makes sense for an operator.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001798 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begeman7cee8172009-03-19 05:21:56 +00001799 !Operator->isSubClassOf("SDNode") &&
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001800 !Operator->isSubClassOf("Instruction") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001801 !Operator->isSubClassOf("SDNodeXForm") &&
1802 !Operator->isSubClassOf("Intrinsic") &&
1803 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001804 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001805 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001806
Chris Lattner6cefb772008-01-05 22:25:12 +00001807 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001808 if (isInputPattern) {
1809 if (Operator->isSubClassOf("Instruction") ||
1810 Operator->isSubClassOf("SDNodeXForm"))
1811 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1812 } else {
1813 if (Operator->isSubClassOf("Intrinsic"))
1814 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001815
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001816 if (Operator->isSubClassOf("SDNode") &&
1817 Operator->getName() != "imm" &&
1818 Operator->getName() != "fpimm" &&
1819 Operator->getName() != "tglobaltlsaddr" &&
1820 Operator->getName() != "tconstpool" &&
1821 Operator->getName() != "tjumptable" &&
1822 Operator->getName() != "tframeindex" &&
1823 Operator->getName() != "texternalsym" &&
1824 Operator->getName() != "tblockaddress" &&
1825 Operator->getName() != "tglobaladdr" &&
1826 Operator->getName() != "bb" &&
1827 Operator->getName() != "vt")
1828 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1829 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001830
Chris Lattner6cefb772008-01-05 22:25:12 +00001831 std::vector<TreePatternNode*> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00001832
1833 // Parse all the operands.
1834 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1835 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001836
Chris Lattner6cefb772008-01-05 22:25:12 +00001837 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001838 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner6cefb772008-01-05 22:25:12 +00001839 // convert the intrinsic name to a number.
1840 if (Operator->isSubClassOf("Intrinsic")) {
1841 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1842 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1843
1844 // If this intrinsic returns void, it must have side-effects and thus a
1845 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00001846 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001847 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001848 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00001849 // Has side-effects, requires chain.
1850 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001851 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00001852 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001853
David Greenedcd35c72011-07-29 19:07:07 +00001854 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001855 Children.insert(Children.begin(), IIDNode);
1856 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001857
Chris Lattnerd7349192010-03-19 21:37:09 +00001858 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1859 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00001860 Result->setName(OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001861
Chris Lattnerc2173052010-03-28 06:50:34 +00001862 if (!Dag->getName().empty()) {
1863 assert(Result->getName().empty());
1864 Result->setName(Dag->getName());
1865 }
Nate Begeman7cee8172009-03-19 05:21:56 +00001866 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001867}
1868
Chris Lattner7a0eb912010-03-28 08:38:32 +00001869/// SimplifyTree - See if we can simplify this tree to eliminate something that
1870/// will never match in favor of something obvious that will. This is here
1871/// strictly as a convenience to target authors because it allows them to write
1872/// more type generic things and have useless type casts fold away.
1873///
1874/// This returns true if any change is made.
1875static bool SimplifyTree(TreePatternNode *&N) {
1876 if (N->isLeaf())
1877 return false;
1878
1879 // If we have a bitconvert with a resolved type and if the source and
1880 // destination types are the same, then the bitconvert is useless, remove it.
1881 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattner7a0eb912010-03-28 08:38:32 +00001882 N->getExtType(0).isConcrete() &&
1883 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1884 N->getName().empty()) {
1885 N = N->getChild(0);
1886 SimplifyTree(N);
1887 return true;
1888 }
1889
1890 // Walk all children.
1891 bool MadeChange = false;
1892 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1893 TreePatternNode *Child = N->getChild(i);
1894 MadeChange |= SimplifyTree(Child);
1895 N->setChild(i, Child);
1896 }
1897 return MadeChange;
1898}
1899
1900
1901
Chris Lattner6cefb772008-01-05 22:25:12 +00001902/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001903/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001904/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001905bool TreePattern::
1906InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1907 if (NamedNodes.empty())
1908 ComputeNamedNodes();
1909
Chris Lattner6cefb772008-01-05 22:25:12 +00001910 bool MadeChange = true;
1911 while (MadeChange) {
1912 MadeChange = false;
Chris Lattner7a0eb912010-03-28 08:38:32 +00001913 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001914 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner7a0eb912010-03-28 08:38:32 +00001915 MadeChange |= SimplifyTree(Trees[i]);
1916 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001917
1918 // If there are constraints on our named nodes, apply them.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001919 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattner2cacec52010-03-15 06:00:16 +00001920 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1921 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001922
Chris Lattner2cacec52010-03-15 06:00:16 +00001923 // If we have input named node types, propagate their types to the named
1924 // values here.
1925 if (InNamedTypes) {
1926 // FIXME: Should be error?
1927 assert(InNamedTypes->count(I->getKey()) &&
1928 "Named node in output pattern but not input pattern?");
1929
1930 const SmallVectorImpl<TreePatternNode*> &InNodes =
1931 InNamedTypes->find(I->getKey())->second;
1932
1933 // The input types should be fully resolved by now.
1934 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1935 // If this node is a register class, and it is the root of the pattern
1936 // then we're mapping something onto an input register. We allow
1937 // changing the type of the input register in this case. This allows
1938 // us to match things like:
1939 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1940 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001941 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00001942 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
1943 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner2cacec52010-03-15 06:00:16 +00001944 continue;
1945 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001946
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001947 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001948 InNodes[0]->getNumTypes() == 1 &&
1949 "FIXME: cannot name multiple result nodes yet");
1950 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1951 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001952 }
1953 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001954
Chris Lattner2cacec52010-03-15 06:00:16 +00001955 // If there are multiple nodes with the same name, they must all have the
1956 // same type.
1957 if (I->second.size() > 1) {
1958 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001959 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001960 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001961 "FIXME: cannot name multiple result nodes yet");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001962
Chris Lattnerd7349192010-03-19 21:37:09 +00001963 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1964 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001965 }
1966 }
1967 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001968 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001969
Chris Lattner6cefb772008-01-05 22:25:12 +00001970 bool HasUnresolvedTypes = false;
1971 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1972 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1973 return !HasUnresolvedTypes;
1974}
1975
Daniel Dunbar1a551802009-07-03 00:10:29 +00001976void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001977 OS << getRecord()->getName();
1978 if (!Args.empty()) {
1979 OS << "(" << Args[0];
1980 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1981 OS << ", " << Args[i];
1982 OS << ")";
1983 }
1984 OS << ": ";
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001985
Chris Lattner6cefb772008-01-05 22:25:12 +00001986 if (Trees.size() > 1)
1987 OS << "[\n";
1988 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1989 OS << "\t";
1990 Trees[i]->print(OS);
1991 OS << "\n";
1992 }
1993
1994 if (Trees.size() > 1)
1995 OS << "]\n";
1996}
1997
Daniel Dunbar1a551802009-07-03 00:10:29 +00001998void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001999
2000//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00002001// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00002002//
2003
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002004CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner67db8832010-12-13 00:23:57 +00002005 Records(R), Target(R) {
2006
Dale Johannesen49de9822009-02-05 01:49:45 +00002007 Intrinsics = LoadIntrinsics(Records, false);
2008 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00002009 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00002010 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00002011 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002012 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00002013 ParseDefaultOperands();
2014 ParseInstructions();
2015 ParsePatterns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002016
Chris Lattner6cefb772008-01-05 22:25:12 +00002017 // Generate variants. For example, commutative patterns can match
2018 // multiple ways. Add them to PatternsToMatch as well.
2019 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00002020
2021 // Infer instruction flags. For example, we can detect loads,
2022 // stores, and side effects in many cases by examining an
2023 // instruction's pattern.
2024 InferInstructionFlags();
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00002025
2026 // Verify that instruction flags match the patterns.
2027 VerifyInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00002028}
2029
Chris Lattnerfe718932008-01-06 01:10:31 +00002030CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002031 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002032 E = PatternFragments.end(); I != E; ++I)
2033 delete I->second;
2034}
2035
2036
Chris Lattnerfe718932008-01-06 01:10:31 +00002037Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00002038 Record *N = Records.getDef(Name);
2039 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002040 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00002041 exit(1);
2042 }
2043 return N;
2044}
2045
2046// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00002047void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002048 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2049 while (!Nodes.empty()) {
2050 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2051 Nodes.pop_back();
2052 }
2053
Jim Grosbachda4231f2009-03-26 16:17:51 +00002054 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00002055 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2056 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2057 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2058}
2059
2060/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2061/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002062void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002063 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2064 while (!Xforms.empty()) {
2065 Record *XFormNode = Xforms.back();
2066 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +00002067 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00002068 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002069
2070 Xforms.pop_back();
2071 }
2072}
2073
Chris Lattnerfe718932008-01-06 01:10:31 +00002074void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002075 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2076 while (!AMs.empty()) {
2077 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2078 AMs.pop_back();
2079 }
2080}
2081
2082
2083/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2084/// file, building up the PatternFragments map. After we've collected them all,
2085/// inline fragments together as necessary, so that there are no references left
2086/// inside a pattern fragment to a pattern fragment.
2087///
Chris Lattnerfe718932008-01-06 01:10:31 +00002088void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002089 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002090
Chris Lattnerdc32f982008-01-05 22:43:57 +00002091 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002092 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00002093 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattner6cefb772008-01-05 22:25:12 +00002094 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2095 PatternFragments[Fragments[i]] = P;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002096
Chris Lattnerdc32f982008-01-05 22:43:57 +00002097 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00002098 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002099 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002100
Chris Lattnerdc32f982008-01-05 22:43:57 +00002101 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00002102 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002103
Chris Lattner6cefb772008-01-05 22:25:12 +00002104 // Parse the operands list.
David Greene05bce0b2011-07-29 22:43:06 +00002105 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2106 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00002107 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00002108 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00002109 if (!OpsOp ||
2110 (OpsOp->getDef()->getName() != "ops" &&
2111 OpsOp->getDef()->getName() != "outs" &&
2112 OpsOp->getDef()->getName() != "ins"))
2113 P->error("Operands list should start with '(ops ... '!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002114
2115 // Copy over the arguments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002116 Args.clear();
2117 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
David Greene05bce0b2011-07-29 22:43:06 +00002118 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
2119 static_cast<DefInit*>(OpsList->getArg(j))->
Chris Lattner6cefb772008-01-05 22:25:12 +00002120 getDef()->getName() != "node")
2121 P->error("Operands list should all be 'node' values.");
2122 if (OpsList->getArgName(j).empty())
2123 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002124 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00002125 P->error("'" + OpsList->getArgName(j) +
2126 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002127 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00002128 Args.push_back(OpsList->getArgName(j));
2129 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002130
Chris Lattnerdc32f982008-01-05 22:43:57 +00002131 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00002132 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00002133 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002134
Chris Lattnerdc32f982008-01-05 22:43:57 +00002135 // If there is a code init for this fragment, keep track of the fact that
2136 // this fragment uses it.
Chris Lattner54379062011-04-17 21:38:24 +00002137 TreePredicateFn PredFn(P);
2138 if (!PredFn.isAlwaysTrue())
2139 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002140
Chris Lattner6cefb772008-01-05 22:25:12 +00002141 // If there is a node transformation corresponding to this, keep track of
2142 // it.
2143 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2144 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2145 P->getOnlyTree()->setTransformFn(Transform);
2146 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002147
Chris Lattner6cefb772008-01-05 22:25:12 +00002148 // Now that we've parsed all of the tree fragments, do a closure on them so
2149 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00002150 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2151 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00002152 ThePat->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002153
Chris Lattner6cefb772008-01-05 22:25:12 +00002154 // Infer as many types as possible. Don't worry about it if we don't infer
2155 // all of them, some may depend on the inputs of the pattern.
2156 try {
2157 ThePat->InferAllTypes();
2158 } catch (...) {
2159 // If this pattern fragment is not supported by this target (no types can
2160 // satisfy its constraints), just ignore it. If the bogus pattern is
2161 // actually used by instructions, the type consistency error will be
2162 // reported there.
2163 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002164
Chris Lattner6cefb772008-01-05 22:25:12 +00002165 // If debugging, print out the pattern fragment result.
2166 DEBUG(ThePat->dump());
2167 }
2168}
2169
Chris Lattnerfe718932008-01-06 01:10:31 +00002170void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellard6d3d7652012-09-06 14:15:52 +00002171 std::vector<Record*> DefaultOps;
2172 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner6cefb772008-01-05 22:25:12 +00002173
2174 // Find some SDNode.
2175 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greene05bce0b2011-07-29 22:43:06 +00002176 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002177
Tom Stellard6d3d7652012-09-06 14:15:52 +00002178 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2179 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002180
Tom Stellard6d3d7652012-09-06 14:15:52 +00002181 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2182 // SomeSDnode so that we can parse this.
2183 std::vector<std::pair<Init*, std::string> > Ops;
2184 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2185 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2186 DefaultInfo->getArgName(op)));
2187 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002188
Tom Stellard6d3d7652012-09-06 14:15:52 +00002189 // Create a TreePattern to parse this.
2190 TreePattern P(DefaultOps[i], DI, false, *this);
2191 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002192
Tom Stellard6d3d7652012-09-06 14:15:52 +00002193 // Copy the operands over into a DAGDefaultOperand.
2194 DAGDefaultOperand DefaultOpInfo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002195
Tom Stellard6d3d7652012-09-06 14:15:52 +00002196 TreePatternNode *T = P.getTree(0);
2197 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2198 TreePatternNode *TPN = T->getChild(op);
2199 while (TPN->ApplyTypeConstraints(P, false))
2200 /* Resolve all types */;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002201
Tom Stellard6d3d7652012-09-06 14:15:52 +00002202 if (TPN->ContainsUnresolvedType()) {
2203 throw "Value #" + utostr(i) + " of OperandWithDefaultOps '" +
2204 DefaultOps[i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00002205 }
Tom Stellard6d3d7652012-09-06 14:15:52 +00002206 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner6cefb772008-01-05 22:25:12 +00002207 }
Tom Stellard6d3d7652012-09-06 14:15:52 +00002208
2209 // Insert it into the DefaultOperands map so we can find it later.
2210 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner6cefb772008-01-05 22:25:12 +00002211 }
2212}
2213
2214/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2215/// instruction input. Return true if this is a real use.
2216static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002217 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002218 // No name -> not interesting.
2219 if (Pat->getName().empty()) {
2220 if (Pat->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002221 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00002222 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2223 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002224 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002225 }
2226 return false;
2227 }
2228
2229 Record *Rec;
2230 if (Pat->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002231 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002232 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2233 Rec = DI->getDef();
2234 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00002235 Rec = Pat->getOperator();
2236 }
2237
2238 // SRCVALUE nodes are ignored.
2239 if (Rec->getName() == "srcvalue")
2240 return false;
2241
2242 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2243 if (!Slot) {
2244 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00002245 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00002246 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00002247 Record *SlotRec;
2248 if (Slot->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002249 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattner53d09bd2010-02-23 05:59:10 +00002250 } else {
2251 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2252 SlotRec = Slot->getOperator();
2253 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002254
Chris Lattner53d09bd2010-02-23 05:59:10 +00002255 // Ensure that the inputs agree if we've already seen this input.
2256 if (Rec != SlotRec)
2257 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00002258 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00002259 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00002260 return true;
2261}
2262
2263/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2264/// part of "I", the instruction), computing the set of inputs and outputs of
2265/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00002266void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00002267FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2268 std::map<std::string, TreePatternNode*> &InstInputs,
2269 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner6cefb772008-01-05 22:25:12 +00002270 std::vector<Record*> &InstImpResults) {
2271 if (Pat->isLeaf()) {
Chris Lattneracfb70f2010-04-20 06:30:25 +00002272 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002273 if (!isUse && Pat->getTransformFn())
2274 I->error("Cannot specify a transform function for a non-input value!");
2275 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002276 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002277
Chris Lattner84aa60b2010-02-17 06:53:36 +00002278 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002279 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2280 TreePatternNode *Dest = Pat->getChild(i);
2281 if (!Dest->isLeaf())
2282 I->error("implicitly defined value should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002283
David Greene05bce0b2011-07-29 22:43:06 +00002284 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002285 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2286 I->error("implicitly defined value should be a register!");
2287 InstImpResults.push_back(Val->getDef());
2288 }
2289 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002290 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002291
Chris Lattner84aa60b2010-02-17 06:53:36 +00002292 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002293 // If this is not a set, verify that the children nodes are not void typed,
2294 // and recurse.
2295 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002296 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002297 I->error("Cannot have void nodes inside of patterns!");
2298 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002299 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002300 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002301
Chris Lattner6cefb772008-01-05 22:25:12 +00002302 // If this is a non-leaf node with no children, treat it basically as if
2303 // it were a leaf. This handles nodes like (imm).
Chris Lattneracfb70f2010-04-20 06:30:25 +00002304 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002305
Chris Lattner6cefb772008-01-05 22:25:12 +00002306 if (!isUse && Pat->getTransformFn())
2307 I->error("Cannot specify a transform function for a non-input value!");
2308 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002309 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002310
Chris Lattner6cefb772008-01-05 22:25:12 +00002311 // Otherwise, this is a set, validate and collect instruction results.
2312 if (Pat->getNumChildren() == 0)
2313 I->error("set requires operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002314
Chris Lattner6cefb772008-01-05 22:25:12 +00002315 if (Pat->getTransformFn())
2316 I->error("Cannot specify a transform function on a set node!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002317
Chris Lattner6cefb772008-01-05 22:25:12 +00002318 // Check the set destinations.
2319 unsigned NumDests = Pat->getNumChildren()-1;
2320 for (unsigned i = 0; i != NumDests; ++i) {
2321 TreePatternNode *Dest = Pat->getChild(i);
2322 if (!Dest->isLeaf())
2323 I->error("set destination should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002324
David Greene05bce0b2011-07-29 22:43:06 +00002325 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002326 if (!Val)
2327 I->error("set destination should be a register!");
2328
2329 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Owen Andersonbea6f612011-06-27 21:06:21 +00002330 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002331 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002332 if (Dest->getName().empty())
2333 I->error("set destination must have a name!");
2334 if (InstResults.count(Dest->getName()))
2335 I->error("cannot set '" + Dest->getName() +"' multiple times");
2336 InstResults[Dest->getName()] = Dest;
2337 } else if (Val->getDef()->isSubClassOf("Register")) {
2338 InstImpResults.push_back(Val->getDef());
2339 } else {
2340 I->error("set destination should be a register!");
2341 }
2342 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002343
Chris Lattner6cefb772008-01-05 22:25:12 +00002344 // Verify and collect info from the computation.
2345 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattneracfb70f2010-04-20 06:30:25 +00002346 InstInputs, InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002347}
2348
Dan Gohmanee4fa192008-04-03 00:02:49 +00002349//===----------------------------------------------------------------------===//
2350// Instruction Analysis
2351//===----------------------------------------------------------------------===//
2352
2353class InstAnalyzer {
2354 const CodeGenDAGPatterns &CDP;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002355public:
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002356 bool hasSideEffects;
2357 bool mayStore;
2358 bool mayLoad;
2359 bool isBitcast;
2360 bool isVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002361
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002362 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2363 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2364 isBitcast(false), isVariadic(false) {}
Dan Gohmanee4fa192008-04-03 00:02:49 +00002365
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002366 void Analyze(const TreePattern *Pat) {
2367 // Assume only the first tree is the pattern. The others are clobber nodes.
2368 AnalyzeNode(Pat->getTree(0));
Dan Gohmanee4fa192008-04-03 00:02:49 +00002369 }
2370
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00002371 void Analyze(const PatternToMatch *Pat) {
2372 AnalyzeNode(Pat->getSrcPattern());
2373 }
2374
Dan Gohmanee4fa192008-04-03 00:02:49 +00002375private:
Evan Cheng0f040a22011-03-15 05:09:26 +00002376 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002377 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng0f040a22011-03-15 05:09:26 +00002378 return false;
2379
2380 if (N->getNumChildren() != 2)
2381 return false;
2382
2383 const TreePatternNode *N0 = N->getChild(0);
David Greene05bce0b2011-07-29 22:43:06 +00002384 if (!N0->isLeaf() || !dynamic_cast<DefInit*>(N0->getLeafValue()))
Evan Cheng0f040a22011-03-15 05:09:26 +00002385 return false;
2386
2387 const TreePatternNode *N1 = N->getChild(1);
2388 if (N1->isLeaf())
2389 return false;
2390 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2391 return false;
2392
2393 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2394 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2395 return false;
2396 return OpInfo.getEnumName() == "ISD::BITCAST";
2397 }
2398
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00002399public:
Dan Gohmanee4fa192008-04-03 00:02:49 +00002400 void AnalyzeNode(const TreePatternNode *N) {
2401 if (N->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002402 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002403 Record *LeafRec = DI->getDef();
2404 // Handle ComplexPattern leaves.
2405 if (LeafRec->isSubClassOf("ComplexPattern")) {
2406 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2407 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2408 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002409 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002410 }
2411 }
2412 return;
2413 }
2414
2415 // Analyze children.
2416 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2417 AnalyzeNode(N->getChild(i));
2418
2419 // Ignore set nodes, which are not SDNodes.
Evan Cheng0f040a22011-03-15 05:09:26 +00002420 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002421 isBitcast = IsNodeBitcast(N);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002422 return;
Evan Cheng0f040a22011-03-15 05:09:26 +00002423 }
Dan Gohmanee4fa192008-04-03 00:02:49 +00002424
2425 // Get information about the SDNode for the operator.
2426 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2427
2428 // Notice properties of the node.
2429 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2430 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002431 if (OpInfo.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2432 if (OpInfo.hasProperty(SDNPVariadic)) isVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002433
2434 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2435 // If this is an intrinsic, analyze it.
2436 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2437 mayLoad = true;// These may load memory.
2438
Dan Gohman7365c092010-08-05 23:36:21 +00002439 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002440 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2441
Dan Gohman7365c092010-08-05 23:36:21 +00002442 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002443 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002444 hasSideEffects = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002445 }
2446 }
2447
2448};
2449
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002450static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002451 const InstAnalyzer &PatInfo,
2452 Record *PatDef) {
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002453 bool Error = false;
2454
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002455 // Remember where InstInfo got its flags.
2456 if (InstInfo.hasUndefFlags())
2457 InstInfo.InferredFrom = PatDef;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002458
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002459 // Check explicitly set flags for consistency.
2460 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2461 !InstInfo.hasSideEffects_Unset) {
2462 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2463 // the pattern has no side effects. That could be useful for div/rem
2464 // instructions that may trap.
2465 if (!InstInfo.hasSideEffects) {
2466 Error = true;
2467 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2468 Twine(InstInfo.hasSideEffects));
2469 }
2470 }
2471
2472 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2473 Error = true;
2474 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2475 Twine(InstInfo.mayStore));
2476 }
2477
2478 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2479 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2480 // Some targets translate imediates to loads.
2481 if (!InstInfo.mayLoad) {
2482 Error = true;
2483 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2484 Twine(InstInfo.mayLoad));
2485 }
2486 }
2487
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002488 // Transfer inferred flags.
2489 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2490 InstInfo.mayStore |= PatInfo.mayStore;
2491 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002492
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002493 // These flags are silently added without any verification.
2494 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenaaaecfc2012-08-24 21:08:09 +00002495
2496 // Don't infer isVariadic. This flag means something different on SDNodes and
2497 // instructions. For example, a CALL SDNode is variadic because it has the
2498 // call arguments as operands, but a CALL instruction is not variadic - it
2499 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002500
2501 return Error;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002502}
2503
Jim Grosbachac915b42012-07-17 00:47:06 +00002504/// hasNullFragReference - Return true if the DAG has any reference to the
2505/// null_frag operator.
2506static bool hasNullFragReference(DagInit *DI) {
2507 DefInit *OpDef = dynamic_cast<DefInit*>(DI->getOperator());
2508 if (!OpDef) return false;
2509 Record *Operator = OpDef->getDef();
2510
2511 // If this is the null fragment, return true.
2512 if (Operator->getName() == "null_frag") return true;
2513 // If any of the arguments reference the null fragment, return true.
2514 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2515 DagInit *Arg = dynamic_cast<DagInit*>(DI->getArg(i));
2516 if (Arg && hasNullFragReference(Arg))
2517 return true;
2518 }
2519
2520 return false;
2521}
2522
2523/// hasNullFragReference - Return true if any DAG in the list references
2524/// the null_frag operator.
2525static bool hasNullFragReference(ListInit *LI) {
2526 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
2527 DagInit *DI = dynamic_cast<DagInit*>(LI->getElement(i));
2528 assert(DI && "non-dag in an instruction Pattern list?!");
2529 if (hasNullFragReference(DI))
2530 return true;
2531 }
2532 return false;
2533}
2534
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00002535/// Get all the instructions in a tree.
2536static void
2537getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2538 if (Tree->isLeaf())
2539 return;
2540 if (Tree->getOperator()->isSubClassOf("Instruction"))
2541 Instrs.push_back(Tree->getOperator());
2542 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2543 getInstructionsInTree(Tree->getChild(i), Instrs);
2544}
2545
Chris Lattner6cefb772008-01-05 22:25:12 +00002546/// ParseInstructions - Parse all of the instructions, inlining and resolving
2547/// any fragments involved. This populates the Instructions list with fully
2548/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002549void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002550 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002551
Chris Lattner6cefb772008-01-05 22:25:12 +00002552 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00002553 ListInit *LI = 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002554
David Greene05bce0b2011-07-29 22:43:06 +00002555 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002556 LI = Instrs[i]->getValueAsListInit("Pattern");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002557
Chris Lattner6cefb772008-01-05 22:25:12 +00002558 // If there is no pattern, only collect minimal information about the
2559 // instruction for its operand list. We have to assume that there is one
Jim Grosbachac915b42012-07-17 00:47:06 +00002560 // result, as we have no detailed info. A pattern which references the
2561 // null_frag operator is as-if no pattern were specified. Normally this
2562 // is from a multiclass expansion w/ a SDPatternOperator passed in as
2563 // null_frag.
2564 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002565 std::vector<Record*> Results;
2566 std::vector<Record*> Operands;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002567
Chris Lattnerf30187a2010-03-19 00:07:20 +00002568 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002569
Chris Lattnerc240bb02010-11-01 04:03:32 +00002570 if (InstInfo.Operands.size() != 0) {
2571 if (InstInfo.Operands.NumDefs == 0) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002572 // These produce no results
Chris Lattnerc240bb02010-11-01 04:03:32 +00002573 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2574 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002575 } else {
2576 // Assume the first operand is the result.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002577 Results.push_back(InstInfo.Operands[0].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002578
Chris Lattner6cefb772008-01-05 22:25:12 +00002579 // The rest are inputs.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002580 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2581 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002582 }
2583 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002584
Chris Lattner6cefb772008-01-05 22:25:12 +00002585 // Create and insert the instruction.
2586 std::vector<Record*> ImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002587 Instructions.insert(std::make_pair(Instrs[i],
Chris Lattner62bcec82010-04-20 06:28:43 +00002588 DAGInstruction(0, Results, Operands, ImpResults)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002589 continue; // no pattern.
2590 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002591
Chris Lattner6cefb772008-01-05 22:25:12 +00002592 // Parse the instruction.
2593 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2594 // Inline pattern fragments into it.
2595 I->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002596
Chris Lattner6cefb772008-01-05 22:25:12 +00002597 // Infer as many types as possible. If we cannot infer all of them, we can
2598 // never do anything with this instruction pattern: report it to the user.
2599 if (!I->InferAllTypes())
2600 I->error("Could not infer all types in pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002601
2602 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner6cefb772008-01-05 22:25:12 +00002603 // with the record they are declared as.
2604 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002605
Chris Lattner6cefb772008-01-05 22:25:12 +00002606 // InstResults - Keep track of all the virtual registers that are 'set'
2607 // in the instruction, including what reg class they are.
2608 std::map<std::string, TreePatternNode*> InstResults;
2609
Chris Lattner6cefb772008-01-05 22:25:12 +00002610 std::vector<Record*> InstImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002611
Chris Lattner6cefb772008-01-05 22:25:12 +00002612 // Verify that the top-level forms in the instruction are of void type, and
2613 // fill in the InstResults map.
2614 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2615 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002616 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002617 I->error("Top-level forms in instruction pattern should have"
2618 " void types");
2619
2620 // Find inputs and outputs, and verify the structure of the uses/defs.
2621 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002622 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002623 }
2624
2625 // Now that we have inputs and outputs of the pattern, inspect the operands
2626 // list for the instruction. This determines the order that operands are
2627 // added to the machine instruction the node corresponds to.
2628 unsigned NumResults = InstResults.size();
2629
2630 // Parse the operands list from the (ops) list, validating it.
2631 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002632 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002633
2634 // Check that all of the results occur first in the list.
2635 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002636 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002637 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00002638 if (i == CGI.Operands.size())
Chris Lattner6cefb772008-01-05 22:25:12 +00002639 I->error("'" + InstResults.begin()->first +
2640 "' set but does not appear in operand list!");
Chris Lattnerc240bb02010-11-01 04:03:32 +00002641 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002642
Chris Lattner6cefb772008-01-05 22:25:12 +00002643 // Check that it exists in InstResults.
2644 TreePatternNode *RNode = InstResults[OpName];
2645 if (RNode == 0)
2646 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002647
Chris Lattner6cefb772008-01-05 22:25:12 +00002648 if (i == 0)
2649 Res0Node = RNode;
David Greene05bce0b2011-07-29 22:43:06 +00002650 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner6cefb772008-01-05 22:25:12 +00002651 if (R == 0)
2652 I->error("Operand $" + OpName + " should be a set destination: all "
2653 "outputs must occur before inputs in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002654
Chris Lattnerc240bb02010-11-01 04:03:32 +00002655 if (CGI.Operands[i].Rec != R)
Chris Lattner6cefb772008-01-05 22:25:12 +00002656 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002657
Chris Lattner6cefb772008-01-05 22:25:12 +00002658 // Remember the return type.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002659 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002660
Chris Lattner6cefb772008-01-05 22:25:12 +00002661 // Okay, this one checks out.
2662 InstResults.erase(OpName);
2663 }
2664
2665 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2666 // the copy while we're checking the inputs.
2667 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2668
2669 std::vector<TreePatternNode*> ResultNodeOperands;
2670 std::vector<Record*> Operands;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002671 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2672 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner6cefb772008-01-05 22:25:12 +00002673 const std::string &OpName = Op.Name;
2674 if (OpName.empty())
2675 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2676
2677 if (!InstInputsCheck.count(OpName)) {
Tom Stellard6d3d7652012-09-06 14:15:52 +00002678 // If this is an operand with a DefaultOps set filled in, we can ignore
2679 // this. When we codegen it, we will do so as always executed.
2680 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002681 // Does it have a non-empty DefaultOps field? If so, ignore this
2682 // operand.
2683 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2684 continue;
2685 }
2686 I->error("Operand $" + OpName +
2687 " does not appear in the instruction pattern");
2688 }
2689 TreePatternNode *InVal = InstInputsCheck[OpName];
2690 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002691
Chris Lattner6cefb772008-01-05 22:25:12 +00002692 if (InVal->isLeaf() &&
David Greene05bce0b2011-07-29 22:43:06 +00002693 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2694 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Chris Lattner6cefb772008-01-05 22:25:12 +00002695 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2696 I->error("Operand $" + OpName + "'s register class disagrees"
2697 " between the operand and pattern");
2698 }
2699 Operands.push_back(Op.Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002700
Chris Lattner6cefb772008-01-05 22:25:12 +00002701 // Construct the result for the dest-pattern operand list.
2702 TreePatternNode *OpNode = InVal->clone();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002703
Chris Lattner6cefb772008-01-05 22:25:12 +00002704 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002705 OpNode->clearPredicateFns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002706
Chris Lattner6cefb772008-01-05 22:25:12 +00002707 // Promote the xform function to be an explicit node if set.
2708 if (Record *Xform = OpNode->getTransformFn()) {
2709 OpNode->setTransformFn(0);
2710 std::vector<TreePatternNode*> Children;
2711 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002712 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002713 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002714
Chris Lattner6cefb772008-01-05 22:25:12 +00002715 ResultNodeOperands.push_back(OpNode);
2716 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002717
Chris Lattner6cefb772008-01-05 22:25:12 +00002718 if (!InstInputsCheck.empty())
2719 I->error("Input operand $" + InstInputsCheck.begin()->first +
2720 " occurs in pattern but not in operands list!");
2721
2722 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002723 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2724 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002725 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002726 for (unsigned i = 0; i != NumResults; ++i)
2727 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002728
2729 // Create and insert the instruction.
Chris Lattneracfb70f2010-04-20 06:30:25 +00002730 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner62bcec82010-04-20 06:28:43 +00002731 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002732 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2733
2734 // Use a temporary tree pattern to infer all types and make sure that the
2735 // constructed result is correct. This depends on the instruction already
2736 // being inserted into the Instructions map.
2737 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002738 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002739
2740 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2741 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002742
Chris Lattner6cefb772008-01-05 22:25:12 +00002743 DEBUG(I->dump());
2744 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002745
Chris Lattner6cefb772008-01-05 22:25:12 +00002746 // If we can, convert the instructions to be patterns that are matched!
Sean Silva90fee072012-09-19 01:47:00 +00002747 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002748 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002749 E = Instructions.end(); II != E; ++II) {
2750 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002751 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002752 if (I == 0) continue; // No pattern.
2753
2754 // FIXME: Assume only the first tree is the pattern. The others are clobber
2755 // nodes.
2756 TreePatternNode *Pattern = I->getTree(0);
2757 TreePatternNode *SrcPattern;
2758 if (Pattern->getOperator()->getName() == "set") {
2759 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2760 } else{
2761 // Not a set (store or something?)
2762 SrcPattern = Pattern;
2763 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002764
Chris Lattner6cefb772008-01-05 22:25:12 +00002765 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002766 AddPatternToMatch(I,
Jim Grosbach997759a2010-12-07 23:05:49 +00002767 PatternToMatch(Instr,
2768 Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002769 SrcPattern,
2770 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002771 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002772 Instr->getValueAsInt("AddedComplexity"),
2773 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002774 }
2775}
2776
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002777
2778typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2779
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002780static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002781 std::map<std::string, NameRecord> &Names,
2782 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002783 if (!P->getName().empty()) {
2784 NameRecord &Rec = Names[P->getName()];
2785 // If this is the first instance of the name, remember the node.
2786 if (Rec.second++ == 0)
2787 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002788 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002789 PatternTop->error("repetition of value: $" + P->getName() +
2790 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002791 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002792
Chris Lattner967d54a2010-02-23 06:35:45 +00002793 if (!P->isLeaf()) {
2794 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002795 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002796 }
2797}
2798
Chris Lattner25b6f912010-02-23 06:16:51 +00002799void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2800 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002801 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002802 std::string Reason;
2803 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002804 Pattern->error("Pattern can never match: " + Reason);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002805
Chris Lattner405f1252010-03-01 22:29:19 +00002806 // If the source pattern's root is a complex pattern, that complex pattern
2807 // must specify the nodes it can potentially match.
2808 if (const ComplexPattern *CP =
2809 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2810 if (CP->getRootNodes().empty())
2811 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2812 " could match");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002813
2814
Chris Lattner967d54a2010-02-23 06:35:45 +00002815 // Find all of the named values in the input and output, ensure they have the
2816 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002817 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002818 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2819 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002820
2821 // Scan all of the named values in the destination pattern, rejecting them if
2822 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002823 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002824 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002825 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002826 Pattern->error("Pattern has input without matching name in output: $" +
2827 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002828 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002829
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002830 // Scan all of the named values in the source pattern, rejecting them if the
2831 // name isn't used in the dest, and isn't used to tie two values together.
2832 for (std::map<std::string, NameRecord>::iterator
2833 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2834 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2835 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002836
Chris Lattner25b6f912010-02-23 06:16:51 +00002837 PatternsToMatch.push_back(PTM);
2838}
2839
2840
Dan Gohmanee4fa192008-04-03 00:02:49 +00002841
2842void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002843 const std::vector<const CodeGenInstruction*> &Instructions =
2844 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002845
2846 // First try to infer flags from the primary instruction pattern, if any.
2847 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002848 unsigned Errors = 0;
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002849 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2850 CodeGenInstruction &InstInfo =
2851 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesenccbe6032011-10-14 01:00:49 +00002852
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002853 // Treat neverHasSideEffects = 1 as the equivalent of hasSideEffects = 0.
2854 // This flag is obsolete and will be removed.
2855 if (InstInfo.neverHasSideEffects) {
2856 assert(!InstInfo.hasSideEffects);
2857 InstInfo.hasSideEffects_Unset = false;
2858 }
2859
2860 // Get the primary instruction pattern.
2861 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
2862 if (!Pattern) {
2863 if (InstInfo.hasUndefFlags())
2864 Revisit.push_back(&InstInfo);
2865 continue;
2866 }
2867 InstAnalyzer PatInfo(*this);
2868 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002869 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002870 }
2871
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00002872 // Second, look for single-instruction patterns defined outside the
2873 // instruction.
2874 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
2875 const PatternToMatch &PTM = *I;
2876
2877 // We can only infer from single-instruction patterns, otherwise we won't
2878 // know which instruction should get the flags.
2879 SmallVector<Record*, 8> PatInstrs;
2880 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
2881 if (PatInstrs.size() != 1)
2882 continue;
2883
2884 // Get the single instruction.
2885 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
2886
2887 // Only infer properties from the first pattern. We'll verify the others.
2888 if (InstInfo.InferredFrom)
2889 continue;
2890
2891 InstAnalyzer PatInfo(*this);
2892 PatInfo.Analyze(&PTM);
2893 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
2894 }
2895
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002896 if (Errors)
2897 throw "pattern conflicts";
2898
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002899 // Revisit instructions with undefined flags and no pattern.
2900 if (Target.guessInstructionProperties()) {
2901 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
2902 CodeGenInstruction &InstInfo = *Revisit[i];
2903 if (InstInfo.InferredFrom)
2904 continue;
2905 // The mayLoad and mayStore flags default to false.
2906 // Conservatively assume hasSideEffects if it wasn't explicit.
2907 if (InstInfo.hasSideEffects_Unset)
2908 InstInfo.hasSideEffects = true;
2909 }
2910 return;
2911 }
2912
2913 // Complain about any flags that are still undefined.
2914 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
2915 CodeGenInstruction &InstInfo = *Revisit[i];
2916 if (InstInfo.InferredFrom)
2917 continue;
2918 if (InstInfo.hasSideEffects_Unset)
2919 PrintError(InstInfo.TheDef->getLoc(),
2920 "Can't infer hasSideEffects from patterns");
2921 if (InstInfo.mayStore_Unset)
2922 PrintError(InstInfo.TheDef->getLoc(),
2923 "Can't infer mayStore from patterns");
2924 if (InstInfo.mayLoad_Unset)
2925 PrintError(InstInfo.TheDef->getLoc(),
2926 "Can't infer mayLoad from patterns");
Dan Gohmanee4fa192008-04-03 00:02:49 +00002927 }
2928}
2929
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00002930
2931/// Verify instruction flags against pattern node properties.
2932void CodeGenDAGPatterns::VerifyInstructionFlags() {
2933 unsigned Errors = 0;
2934 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
2935 const PatternToMatch &PTM = *I;
2936 SmallVector<Record*, 8> Instrs;
2937 getInstructionsInTree(PTM.getDstPattern(), Instrs);
2938 if (Instrs.empty())
2939 continue;
2940
2941 // Count the number of instructions with each flag set.
2942 unsigned NumSideEffects = 0;
2943 unsigned NumStores = 0;
2944 unsigned NumLoads = 0;
2945 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2946 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2947 NumSideEffects += InstInfo.hasSideEffects;
2948 NumStores += InstInfo.mayStore;
2949 NumLoads += InstInfo.mayLoad;
2950 }
2951
2952 // Analyze the source pattern.
2953 InstAnalyzer PatInfo(*this);
2954 PatInfo.Analyze(&PTM);
2955
2956 // Collect error messages.
2957 SmallVector<std::string, 4> Msgs;
2958
2959 // Check for missing flags in the output.
2960 // Permit extra flags for now at least.
2961 if (PatInfo.hasSideEffects && !NumSideEffects)
2962 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
2963
2964 // Don't verify store flags on instructions with side effects. At least for
2965 // intrinsics, side effects implies mayStore.
2966 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
2967 Msgs.push_back("pattern may store, but mayStore isn't set");
2968
2969 // Similarly, mayStore implies mayLoad on intrinsics.
2970 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
2971 Msgs.push_back("pattern may load, but mayLoad isn't set");
2972
2973 // Print error messages.
2974 if (Msgs.empty())
2975 continue;
2976 ++Errors;
2977
2978 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
2979 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
2980 (Instrs.size() == 1 ?
2981 "instruction" : "output instructions"));
2982 // Provide the location of the relevant instruction definitions.
2983 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2984 if (Instrs[i] != PTM.getSrcRecord())
2985 PrintError(Instrs[i]->getLoc(), "defined here");
2986 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2987 if (InstInfo.InferredFrom &&
2988 InstInfo.InferredFrom != InstInfo.TheDef &&
2989 InstInfo.InferredFrom != PTM.getSrcRecord())
2990 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
2991 }
2992 }
2993 if (Errors)
2994 throw "Errors in DAG patterns";
2995}
2996
Chris Lattner2cacec52010-03-15 06:00:16 +00002997/// Given a pattern result with an unresolved type, see if we can find one
2998/// instruction with an unresolved result type. Force this result type to an
2999/// arbitrary element if it's possible types to converge results.
3000static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3001 if (N->isLeaf())
3002 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003003
Chris Lattner2cacec52010-03-15 06:00:16 +00003004 // Analyze children.
3005 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3006 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3007 return true;
3008
3009 if (!N->getOperator()->isSubClassOf("Instruction"))
3010 return false;
3011
3012 // If this type is already concrete or completely unknown we can't do
3013 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00003014 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3015 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3016 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003017
Chris Lattnerd7349192010-03-19 21:37:09 +00003018 // Otherwise, force its type to the first possibility (an arbitrary choice).
3019 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3020 return true;
3021 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003022
Chris Lattnerd7349192010-03-19 21:37:09 +00003023 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00003024}
3025
Chris Lattnerfe718932008-01-06 01:10:31 +00003026void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00003027 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3028
3029 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00003030 Record *CurPattern = Patterns[i];
David Greene05bce0b2011-07-29 22:43:06 +00003031 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachd3e31212012-07-17 18:39:36 +00003032
3033 // If the pattern references the null_frag, there's nothing to do.
3034 if (hasNullFragReference(Tree))
3035 continue;
3036
Chris Lattner310adf12010-03-27 02:53:27 +00003037 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00003038
3039 // Inline pattern fragments into it.
3040 Pattern->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003041
David Greene05bce0b2011-07-29 22:43:06 +00003042 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00003043 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003044
Chris Lattner6cefb772008-01-05 22:25:12 +00003045 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00003046 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003047
Chris Lattner6cefb772008-01-05 22:25:12 +00003048 // Inline pattern fragments into it.
3049 Result->InlinePatternFragments();
3050
3051 if (Result->getNumTrees() != 1)
3052 Result->error("Cannot handle instructions producing instructions "
3053 "with temporaries yet!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003054
Chris Lattner6cefb772008-01-05 22:25:12 +00003055 bool IterateInference;
3056 bool InferredAllPatternTypes, InferredAllResultTypes;
3057 do {
3058 // Infer as many types as possible. If we cannot infer all of them, we
3059 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00003060 InferredAllPatternTypes =
3061 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003062
Chris Lattner6cefb772008-01-05 22:25:12 +00003063 // Infer as many types as possible. If we cannot infer all of them, we
3064 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00003065 InferredAllResultTypes =
3066 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00003067
Chris Lattner6c6ba362010-03-18 23:15:10 +00003068 IterateInference = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003069
Chris Lattner6cefb772008-01-05 22:25:12 +00003070 // Apply the type of the result to the source pattern. This helps us
3071 // resolve cases where the input type is known to be a pointer type (which
3072 // is considered resolved), but the result knows it needs to be 32- or
3073 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00003074 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
3075 Pattern->getTree(0)->getNumTypes());
3076 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00003077 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00003078 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00003079 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00003080 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00003081 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003082
Chris Lattner2cacec52010-03-15 06:00:16 +00003083 // If our iteration has converged and the input pattern's types are fully
3084 // resolved but the result pattern is not fully resolved, we may have a
3085 // situation where we have two instructions in the result pattern and
3086 // the instructions require a common register class, but don't care about
3087 // what actual MVT is used. This is actually a bug in our modelling:
3088 // output patterns should have register classes, not MVTs.
3089 //
3090 // In any case, to handle this, we just go through and disambiguate some
3091 // arbitrary types to the result pattern's nodes.
3092 if (!IterateInference && InferredAllPatternTypes &&
3093 !InferredAllResultTypes)
3094 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
3095 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00003096 } while (IterateInference);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003097
Chris Lattner6cefb772008-01-05 22:25:12 +00003098 // Verify that we inferred enough types that we can do something with the
3099 // pattern and result. If these fire the user has to add type casts.
3100 if (!InferredAllPatternTypes)
3101 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00003102 if (!InferredAllResultTypes) {
3103 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00003104 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00003105 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003106
Chris Lattner6cefb772008-01-05 22:25:12 +00003107 // Validate that the input pattern is correct.
3108 std::map<std::string, TreePatternNode*> InstInputs;
3109 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00003110 std::vector<Record*> InstImpResults;
3111 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3112 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3113 InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00003114 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00003115
3116 // Promote the xform function to be an explicit node if set.
3117 TreePatternNode *DstPattern = Result->getOnlyTree();
3118 std::vector<TreePatternNode*> ResultNodeOperands;
3119 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3120 TreePatternNode *OpNode = DstPattern->getChild(ii);
3121 if (Record *Xform = OpNode->getTransformFn()) {
3122 OpNode->setTransformFn(0);
3123 std::vector<TreePatternNode*> Children;
3124 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00003125 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00003126 }
3127 ResultNodeOperands.push_back(OpNode);
3128 }
3129 DstPattern = Result->getOnlyTree();
3130 if (!DstPattern->isLeaf())
3131 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00003132 ResultNodeOperands,
3133 DstPattern->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003134
Chris Lattnerd7349192010-03-19 21:37:09 +00003135 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
3136 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003137
Chris Lattner6cefb772008-01-05 22:25:12 +00003138 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
3139 Temp.InferAllTypes();
3140
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003141
Chris Lattner25b6f912010-02-23 06:16:51 +00003142 AddPatternToMatch(Pattern,
Jim Grosbach997759a2010-12-07 23:05:49 +00003143 PatternToMatch(CurPattern,
3144 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerd7349192010-03-19 21:37:09 +00003145 Pattern->getTree(0),
3146 Temp.getOnlyTree(), InstImpResults,
3147 CurPattern->getValueAsInt("AddedComplexity"),
3148 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003149 }
3150}
3151
3152/// CombineChildVariants - Given a bunch of permutations of each child of the
3153/// 'operator' node, put them together in all possible ways.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003154static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00003155 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3156 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003157 CodeGenDAGPatterns &CDP,
3158 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003159 // Make sure that each operand has at least one variant to choose from.
3160 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3161 if (ChildVariants[i].empty())
3162 return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003163
Chris Lattner6cefb772008-01-05 22:25:12 +00003164 // The end result is an all-pairs construction of the resultant pattern.
3165 std::vector<unsigned> Idxs;
3166 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00003167 bool NotDone;
3168 do {
3169#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00003170 DEBUG(if (!Idxs.empty()) {
3171 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3172 for (unsigned i = 0; i < Idxs.size(); ++i) {
3173 errs() << Idxs[i] << " ";
3174 }
3175 errs() << "]\n";
3176 });
Scott Michel327d0652008-03-05 17:49:05 +00003177#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00003178 // Create the variant and add it to the output list.
3179 std::vector<TreePatternNode*> NewChildren;
3180 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3181 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00003182 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3183 Orig->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003184
Chris Lattner6cefb772008-01-05 22:25:12 +00003185 // Copy over properties.
3186 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00003187 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00003188 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00003189 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3190 R->setType(i, Orig->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003191
Scott Michel327d0652008-03-05 17:49:05 +00003192 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00003193 std::string ErrString;
3194 if (!R->canPatternMatch(ErrString, CDP)) {
3195 delete R;
3196 } else {
3197 bool AlreadyExists = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003198
Chris Lattner6cefb772008-01-05 22:25:12 +00003199 // Scan to see if this pattern has already been emitted. We can get
3200 // duplication due to things like commuting:
3201 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3202 // which are the same pattern. Ignore the dups.
3203 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003204 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003205 AlreadyExists = true;
3206 break;
3207 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003208
Chris Lattner6cefb772008-01-05 22:25:12 +00003209 if (AlreadyExists)
3210 delete R;
3211 else
3212 OutVariants.push_back(R);
3213 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003214
Scott Michel327d0652008-03-05 17:49:05 +00003215 // Increment indices to the next permutation by incrementing the
3216 // indicies from last index backward, e.g., generate the sequence
3217 // [0, 0], [0, 1], [1, 0], [1, 1].
3218 int IdxsIdx;
3219 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3220 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3221 Idxs[IdxsIdx] = 0;
3222 else
Chris Lattner6cefb772008-01-05 22:25:12 +00003223 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00003224 }
Scott Michel327d0652008-03-05 17:49:05 +00003225 NotDone = (IdxsIdx >= 0);
3226 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00003227}
3228
3229/// CombineChildVariants - A helper function for binary operators.
3230///
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003231static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00003232 const std::vector<TreePatternNode*> &LHS,
3233 const std::vector<TreePatternNode*> &RHS,
3234 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003235 CodeGenDAGPatterns &CDP,
3236 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003237 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3238 ChildVariants.push_back(LHS);
3239 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00003240 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003241}
Chris Lattner6cefb772008-01-05 22:25:12 +00003242
3243
3244static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3245 std::vector<TreePatternNode *> &Children) {
3246 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3247 Record *Operator = N->getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003248
Chris Lattner6cefb772008-01-05 22:25:12 +00003249 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00003250 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00003251 N->getTransformFn()) {
3252 Children.push_back(N);
3253 return;
3254 }
3255
3256 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3257 Children.push_back(N->getChild(0));
3258 else
3259 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3260
3261 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3262 Children.push_back(N->getChild(1));
3263 else
3264 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3265}
3266
3267/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3268/// the (potentially recursive) pattern by using algebraic laws.
3269///
3270static void GenerateVariantsOf(TreePatternNode *N,
3271 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003272 CodeGenDAGPatterns &CDP,
3273 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003274 // We cannot permute leaves.
3275 if (N->isLeaf()) {
3276 OutVariants.push_back(N);
3277 return;
3278 }
3279
3280 // Look up interesting info about the node.
3281 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3282
Jim Grosbachda4231f2009-03-26 16:17:51 +00003283 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00003284 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003285 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00003286 std::vector<TreePatternNode*> MaximalChildren;
3287 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3288
3289 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3290 // permutations.
3291 if (MaximalChildren.size() == 3) {
3292 // Find the variants of all of our maximal children.
3293 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003294 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3295 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3296 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003297
Chris Lattner6cefb772008-01-05 22:25:12 +00003298 // There are only two ways we can permute the tree:
3299 // (A op B) op C and A op (B op C)
3300 // Within these forms, we can also permute A/B/C.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003301
Chris Lattner6cefb772008-01-05 22:25:12 +00003302 // Generate legal pair permutations of A/B/C.
3303 std::vector<TreePatternNode*> ABVariants;
3304 std::vector<TreePatternNode*> BAVariants;
3305 std::vector<TreePatternNode*> ACVariants;
3306 std::vector<TreePatternNode*> CAVariants;
3307 std::vector<TreePatternNode*> BCVariants;
3308 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003309 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3310 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3311 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3312 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3313 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3314 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003315
3316 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00003317 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3318 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3319 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3320 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3321 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3322 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003323
3324 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00003325 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3326 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3327 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3328 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3329 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3330 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003331 return;
3332 }
3333 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003334
Chris Lattner6cefb772008-01-05 22:25:12 +00003335 // Compute permutations of all children.
3336 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3337 ChildVariants.resize(N->getNumChildren());
3338 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003339 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003340
3341 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00003342 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003343
3344 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003345 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3346 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3347 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3348 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003349 // Don't count children which are actually register references.
3350 unsigned NC = 0;
3351 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3352 TreePatternNode *Child = N->getChild(i);
3353 if (Child->isLeaf())
David Greene05bce0b2011-07-29 22:43:06 +00003354 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003355 Record *RR = DI->getDef();
3356 if (RR->isSubClassOf("Register"))
3357 continue;
3358 }
3359 NC++;
3360 }
3361 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003362 if (isCommIntrinsic) {
3363 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3364 // operands are the commutative operands, and there might be more operands
3365 // after those.
3366 assert(NC >= 3 &&
3367 "Commutative intrinsic should have at least 3 childrean!");
3368 std::vector<std::vector<TreePatternNode*> > Variants;
3369 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3370 Variants.push_back(ChildVariants[2]);
3371 Variants.push_back(ChildVariants[1]);
3372 for (unsigned i = 3; i != NC; ++i)
3373 Variants.push_back(ChildVariants[i]);
3374 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3375 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00003376 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00003377 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003378 }
3379}
3380
3381
3382// GenerateVariants - Generate variants. For example, commutative patterns can
3383// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00003384void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00003385 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003386
Chris Lattner6cefb772008-01-05 22:25:12 +00003387 // Loop over all of the patterns we've collected, checking to see if we can
3388 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00003389 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00003390 // the .td file having to contain tons of variants of instructions.
3391 //
3392 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3393 // intentionally do not reconsider these. Any variants of added patterns have
3394 // already been added.
3395 //
3396 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00003397 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00003398 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00003399 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00003400 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00003401 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00003402 DEBUG(errs() << "\n");
Jim Grosbachbb168242010-10-08 18:13:57 +00003403 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3404 DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003405
3406 assert(!Variants.empty() && "Must create at least original variant!");
3407 Variants.erase(Variants.begin()); // Remove the original pattern.
3408
3409 if (Variants.empty()) // No variants for this pattern.
3410 continue;
3411
Chris Lattner569f1212009-08-23 04:44:11 +00003412 DEBUG(errs() << "FOUND VARIANTS OF: ";
3413 PatternsToMatch[i].getSrcPattern()->dump();
3414 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003415
3416 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3417 TreePatternNode *Variant = Variants[v];
3418
Chris Lattner569f1212009-08-23 04:44:11 +00003419 DEBUG(errs() << " VAR#" << v << ": ";
3420 Variant->dump();
3421 errs() << "\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003422
Chris Lattner6cefb772008-01-05 22:25:12 +00003423 // Scan to see if an instruction or explicit pattern already matches this.
3424 bool AlreadyExists = false;
3425 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00003426 // Skip if the top level predicates do not match.
3427 if (PatternsToMatch[i].getPredicates() !=
3428 PatternsToMatch[p].getPredicates())
3429 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00003430 // Check to see if this variant already exists.
Jim Grosbachbb168242010-10-08 18:13:57 +00003431 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3432 DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00003433 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003434 AlreadyExists = true;
3435 break;
3436 }
3437 }
3438 // If we already have it, ignore the variant.
3439 if (AlreadyExists) continue;
3440
3441 // Otherwise, add it to the list of patterns we have.
3442 PatternsToMatch.
Jim Grosbach997759a2010-12-07 23:05:49 +00003443 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3444 PatternsToMatch[i].getPredicates(),
Chris Lattner6cefb772008-01-05 22:25:12 +00003445 Variant, PatternsToMatch[i].getDstPattern(),
3446 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00003447 PatternsToMatch[i].getAddedComplexity(),
3448 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003449 }
3450
Chris Lattner569f1212009-08-23 04:44:11 +00003451 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003452 }
3453}