blob: 0dcb4eed4e581c0109b0f454f4bcd9f941698582 [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
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000577bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
578 return LHS->getID() < RHS->getID();
579}
Scott Michel327d0652008-03-05 17:49:05 +0000580
581/// Dependent variable map for CodeGenDAGPattern variant generation
582typedef std::map<std::string, int> DepVarMap;
583
584/// Const iterator shorthand for DepVarMap
585typedef DepVarMap::const_iterator DepVarMap_citer;
586
Chris Lattner54379062011-04-17 21:38:24 +0000587static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel327d0652008-03-05 17:49:05 +0000588 if (N->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +0000589 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL)
Scott Michel327d0652008-03-05 17:49:05 +0000590 DepMap[N->getName()]++;
Scott Michel327d0652008-03-05 17:49:05 +0000591 } else {
592 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
593 FindDepVarsOf(N->getChild(i), DepMap);
594 }
595}
Chris Lattner54379062011-04-17 21:38:24 +0000596
597/// Find dependent variables within child patterns
598static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000599 DepVarMap depcounts;
600 FindDepVarsOf(N, depcounts);
601 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner54379062011-04-17 21:38:24 +0000602 if (i->second > 1) // std::pair<std::string, int>
Scott Michel327d0652008-03-05 17:49:05 +0000603 DepVars.insert(i->first);
Scott Michel327d0652008-03-05 17:49:05 +0000604 }
605}
606
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000607#ifndef NDEBUG
Chris Lattner54379062011-04-17 21:38:24 +0000608/// Dump the dependent variable set:
609static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000610 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000611 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000612 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000613 DEBUG(errs() << "[ ");
Jim Grosbachbb168242010-10-08 18:13:57 +0000614 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
615 e = DepVars.end(); i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000616 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000617 }
Chris Lattner569f1212009-08-23 04:44:11 +0000618 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000619 }
620}
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000621#endif
622
Chris Lattner54379062011-04-17 21:38:24 +0000623
624//===----------------------------------------------------------------------===//
625// TreePredicateFn Implementation
626//===----------------------------------------------------------------------===//
627
Chris Lattner7ed13912011-04-17 22:05:17 +0000628/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
629TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
630 assert((getPredCode().empty() || getImmCode().empty()) &&
631 ".td file corrupt: can't have a node predicate *and* an imm predicate");
632}
633
Chris Lattner54379062011-04-17 21:38:24 +0000634std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +0000635 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner54379062011-04-17 21:38:24 +0000636}
637
Chris Lattner7ed13912011-04-17 22:05:17 +0000638std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +0000639 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner7ed13912011-04-17 22:05:17 +0000640}
641
Chris Lattner54379062011-04-17 21:38:24 +0000642
643/// isAlwaysTrue - Return true if this is a noop predicate.
644bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000645 return getPredCode().empty() && getImmCode().empty();
Chris Lattner54379062011-04-17 21:38:24 +0000646}
647
648/// Return the name to use in the generated code to reference this, this is
649/// "Predicate_foo" if from a pattern fragment "foo".
650std::string TreePredicateFn::getFnName() const {
651 return "Predicate_" + PatFragRec->getRecord()->getName();
652}
653
654/// getCodeToRunOnSDNode - Return the code for the function body that
655/// evaluates this predicate. The argument is expected to be in "Node",
656/// not N. This handles casting and conversion to a concrete node type as
657/// appropriate.
658std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000659 // Handle immediate predicates first.
660 std::string ImmCode = getImmCode();
661 if (!ImmCode.empty()) {
662 std::string Result =
663 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner7ed13912011-04-17 22:05:17 +0000664 return Result + ImmCode;
665 }
666
667 // Handle arbitrary node predicates.
668 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner54379062011-04-17 21:38:24 +0000669 std::string ClassName;
670 if (PatFragRec->getOnlyTree()->isLeaf())
671 ClassName = "SDNode";
672 else {
673 Record *Op = PatFragRec->getOnlyTree()->getOperator();
674 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
675 }
676 std::string Result;
677 if (ClassName == "SDNode")
678 Result = " SDNode *N = Node;\n";
679 else
680 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
681
682 return Result + getPredCode();
Scott Michel327d0652008-03-05 17:49:05 +0000683}
684
Chris Lattner6cefb772008-01-05 22:25:12 +0000685//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000686// PatternToMatch implementation
687//
688
Chris Lattner48e86db2010-03-29 01:40:38 +0000689
690/// getPatternSize - Return the 'size' of this pattern. We want to match large
691/// patterns before small ones. This is used to determine the size of a
692/// pattern.
693static unsigned getPatternSize(const TreePatternNode *P,
694 const CodeGenDAGPatterns &CGP) {
695 unsigned Size = 3; // The node itself.
696 // If the root node is a ConstantSDNode, increases its size.
697 // e.g. (set R32:$dst, 0).
David Greene05bce0b2011-07-29 22:43:06 +0000698 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000699 Size += 2;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000700
Chris Lattner48e86db2010-03-29 01:40:38 +0000701 // FIXME: This is a hack to statically increase the priority of patterns
702 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
703 // Later we can allow complexity / cost for each pattern to be (optionally)
704 // specified. To get best possible pattern match we'll need to dynamically
705 // calculate the complexity of all patterns a dag can potentially map to.
706 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
707 if (AM)
708 Size += AM->getNumOperands() * 3;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000709
Chris Lattner48e86db2010-03-29 01:40:38 +0000710 // If this node has some predicate function that must match, it adds to the
711 // complexity of this node.
712 if (!P->getPredicateFns().empty())
713 ++Size;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000714
Chris Lattner48e86db2010-03-29 01:40:38 +0000715 // Count children in the count if they are also nodes.
716 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
717 TreePatternNode *Child = P->getChild(i);
718 if (!Child->isLeaf() && Child->getNumTypes() &&
719 Child->getType(0) != MVT::Other)
720 Size += getPatternSize(Child, CGP);
721 else if (Child->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +0000722 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000723 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
724 else if (Child->getComplexPatternInfo(CGP))
725 Size += getPatternSize(Child, CGP);
726 else if (!Child->getPredicateFns().empty())
727 ++Size;
728 }
729 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000730
Chris Lattner48e86db2010-03-29 01:40:38 +0000731 return Size;
732}
733
734/// Compute the complexity metric for the input pattern. This roughly
735/// corresponds to the number of nodes that are covered.
736unsigned PatternToMatch::
737getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
738 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
739}
740
741
Dan Gohman22bb3112008-08-22 00:20:26 +0000742/// getPredicateCheck - Return a single string containing all of this
743/// pattern's predicates concatenated with "&&" operators.
744///
745std::string PatternToMatch::getPredicateCheck() const {
746 std::string PredicateCheck;
747 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +0000748 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
Dan Gohman22bb3112008-08-22 00:20:26 +0000749 Record *Def = Pred->getDef();
750 if (!Def->isSubClassOf("Predicate")) {
751#ifndef NDEBUG
752 Def->dump();
753#endif
Craig Topper655b8de2012-02-05 07:21:30 +0000754 llvm_unreachable("Unknown predicate type!");
Dan Gohman22bb3112008-08-22 00:20:26 +0000755 }
756 if (!PredicateCheck.empty())
757 PredicateCheck += " && ";
758 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
759 }
760 }
761
762 return PredicateCheck;
763}
764
765//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000766// SDTypeConstraint implementation
767//
768
769SDTypeConstraint::SDTypeConstraint(Record *R) {
770 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000771
Chris Lattner6cefb772008-01-05 22:25:12 +0000772 if (R->isSubClassOf("SDTCisVT")) {
773 ConstraintType = SDTCisVT;
774 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerc8122612010-03-28 06:04:39 +0000775 if (x.SDTCisVT_Info.VT == MVT::isVoid)
776 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000777
Chris Lattner6cefb772008-01-05 22:25:12 +0000778 } else if (R->isSubClassOf("SDTCisPtrTy")) {
779 ConstraintType = SDTCisPtrTy;
780 } else if (R->isSubClassOf("SDTCisInt")) {
781 ConstraintType = SDTCisInt;
782 } else if (R->isSubClassOf("SDTCisFP")) {
783 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000784 } else if (R->isSubClassOf("SDTCisVec")) {
785 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000786 } else if (R->isSubClassOf("SDTCisSameAs")) {
787 ConstraintType = SDTCisSameAs;
788 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
789 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
790 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000791 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000792 R->getValueAsInt("OtherOperandNum");
793 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
794 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000795 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000796 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000797 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
798 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000799 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene60322692011-01-24 20:53:18 +0000800 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
801 ConstraintType = SDTCisSubVecOfVec;
802 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
803 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000804 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000805 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000806 exit(1);
807 }
808}
809
810/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000811/// N, and the result number in ResNo.
812static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
813 const SDNodeInfo &NodeInfo,
814 unsigned &ResNo) {
815 unsigned NumResults = NodeInfo.getNumResults();
816 if (OpNo < NumResults) {
817 ResNo = OpNo;
818 return N;
819 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000820
Chris Lattner2e68a022010-03-19 21:56:21 +0000821 OpNo -= NumResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000822
Chris Lattner2e68a022010-03-19 21:56:21 +0000823 if (OpNo >= N->getNumChildren()) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000824 errs() << "Invalid operand number in type constraint "
Chris Lattner2e68a022010-03-19 21:56:21 +0000825 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000826 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000827 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000828 exit(1);
829 }
830
Chris Lattner2e68a022010-03-19 21:56:21 +0000831 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000832}
833
834/// ApplyTypeConstraint - Given a node in a pattern, apply this type
835/// constraint to the nodes operands. This returns true if it makes a
836/// change, false otherwise. If a type contradiction is found, throw an
837/// exception.
838bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
839 const SDNodeInfo &NodeInfo,
840 TreePattern &TP) const {
Chris Lattner2e68a022010-03-19 21:56:21 +0000841 unsigned ResNo = 0; // The result number being referenced.
842 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000843
Chris Lattner6cefb772008-01-05 22:25:12 +0000844 switch (ConstraintType) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000845 case SDTCisVT:
846 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000847 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000848 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000849 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000850 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000851 case SDTCisInt:
852 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000853 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000854 case SDTCisFP:
855 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000856 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000857 case SDTCisVec:
858 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000859 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000860 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000861 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000862 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000863 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000864 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
865 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000866 }
867 case SDTCisVTSmallerThanOp: {
868 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
869 // have an integer type that is smaller than the VT.
870 if (!NodeToApply->isLeaf() ||
David Greene05bce0b2011-07-29 22:43:06 +0000871 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
872 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Chris Lattner6cefb772008-01-05 22:25:12 +0000873 ->isSubClassOf("ValueType"))
874 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000875 MVT::SimpleValueType VT =
David Greene05bce0b2011-07-29 22:43:06 +0000876 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000877
Chris Lattnercc878302010-03-24 00:06:46 +0000878 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000879
Chris Lattner2e68a022010-03-19 21:56:21 +0000880 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000881 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000882 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
883 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000884
Chris Lattnercc878302010-03-24 00:06:46 +0000885 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000886 }
887 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000888 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000889 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000890 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
891 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000892 return NodeToApply->getExtType(ResNo).
893 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000894 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000895 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000896 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000897 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000898 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
899 VResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000900
Chris Lattner66fb9d22010-03-24 00:01:16 +0000901 // Filter vector types out of VecOperand that don't have the right element
902 // type.
903 return VecOperand->getExtType(VResNo).
904 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000905 }
David Greene60322692011-01-24 20:53:18 +0000906 case SDTCisSubVecOfVec: {
907 unsigned VResNo = 0;
908 TreePatternNode *BigVecOperand =
909 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
910 VResNo);
911
912 // Filter vector types out of BigVecOperand that don't have the
913 // right subvector type.
914 return BigVecOperand->getExtType(VResNo).
915 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
916 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000917 }
David Blaikie58bd1512012-01-17 07:00:13 +0000918 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner6cefb772008-01-05 22:25:12 +0000919}
920
921//===----------------------------------------------------------------------===//
922// SDNodeInfo implementation
923//
924SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
925 EnumName = R->getValueAsString("Opcode");
926 SDClassName = R->getValueAsString("SDClass");
927 Record *TypeProfile = R->getValueAsDef("TypeProfile");
928 NumResults = TypeProfile->getValueAsInt("NumResults");
929 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000930
Chris Lattner6cefb772008-01-05 22:25:12 +0000931 // Parse the properties.
932 Properties = 0;
933 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
934 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
935 if (PropList[i]->getName() == "SDNPCommutative") {
936 Properties |= 1 << SDNPCommutative;
937 } else if (PropList[i]->getName() == "SDNPAssociative") {
938 Properties |= 1 << SDNPAssociative;
939 } else if (PropList[i]->getName() == "SDNPHasChain") {
940 Properties |= 1 << SDNPHasChain;
Chris Lattner036609b2010-12-23 18:28:41 +0000941 } else if (PropList[i]->getName() == "SDNPOutGlue") {
942 Properties |= 1 << SDNPOutGlue;
943 } else if (PropList[i]->getName() == "SDNPInGlue") {
944 Properties |= 1 << SDNPInGlue;
945 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
946 Properties |= 1 << SDNPOptInGlue;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000947 } else if (PropList[i]->getName() == "SDNPMayStore") {
948 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000949 } else if (PropList[i]->getName() == "SDNPMayLoad") {
950 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000951 } else if (PropList[i]->getName() == "SDNPSideEffect") {
952 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000953 } else if (PropList[i]->getName() == "SDNPMemOperand") {
954 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000955 } else if (PropList[i]->getName() == "SDNPVariadic") {
956 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000957 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000958 errs() << "Unknown SD Node property '" << PropList[i]->getName()
959 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000960 exit(1);
961 }
962 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000963
964
Chris Lattner6cefb772008-01-05 22:25:12 +0000965 // Parse the type constraints.
966 std::vector<Record*> ConstraintList =
967 TypeProfile->getValueAsListOfDefs("Constraints");
968 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
969}
970
Chris Lattner22579812010-02-28 00:22:30 +0000971/// getKnownType - If the type constraints on this node imply a fixed type
972/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000973/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000974MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +0000975 unsigned NumResults = getNumResults();
976 assert(NumResults <= 1 &&
977 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +0000978 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000979
Chris Lattner22579812010-02-28 00:22:30 +0000980 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
981 // Make sure that this applies to the correct node result.
982 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
983 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000984
Chris Lattner22579812010-02-28 00:22:30 +0000985 switch (TypeConstraints[i].ConstraintType) {
986 default: break;
987 case SDTypeConstraint::SDTCisVT:
988 return TypeConstraints[i].x.SDTCisVT_Info.VT;
989 case SDTypeConstraint::SDTCisPtrTy:
990 return MVT::iPTR;
991 }
992 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000993 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000994}
995
Chris Lattner6cefb772008-01-05 22:25:12 +0000996//===----------------------------------------------------------------------===//
997// TreePatternNode implementation
998//
999
1000TreePatternNode::~TreePatternNode() {
1001#if 0 // FIXME: implement refcounted tree nodes!
1002 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1003 delete getChild(i);
1004#endif
1005}
1006
Chris Lattnerd7349192010-03-19 21:37:09 +00001007static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1008 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +00001009 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +00001010 return 0; // All return nothing.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001011
Chris Lattner93dc92e2010-03-22 20:56:36 +00001012 if (Operator->isSubClassOf("Intrinsic"))
1013 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001014
Chris Lattnerd7349192010-03-19 21:37:09 +00001015 if (Operator->isSubClassOf("SDNode"))
1016 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001017
Chris Lattnerd7349192010-03-19 21:37:09 +00001018 if (Operator->isSubClassOf("PatFrag")) {
1019 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1020 // the forward reference case where one pattern fragment references another
1021 // before it is processed.
1022 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1023 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001024
Chris Lattnerd7349192010-03-19 21:37:09 +00001025 // Get the result tree.
David Greene05bce0b2011-07-29 22:43:06 +00001026 DagInit *Tree = Operator->getValueAsDag("Fragment");
Chris Lattnerd7349192010-03-19 21:37:09 +00001027 Record *Op = 0;
David Greene05bce0b2011-07-29 22:43:06 +00001028 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
1029 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
Chris Lattnerd7349192010-03-19 21:37:09 +00001030 assert(Op && "Invalid Fragment");
1031 return GetNumNodeResults(Op, CDP);
1032 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001033
Chris Lattnerd7349192010-03-19 21:37:09 +00001034 if (Operator->isSubClassOf("Instruction")) {
1035 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001036
1037 // FIXME: Should allow access to all the results here.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001038 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001039
Chris Lattner9414ae52010-03-27 20:09:24 +00001040 // Add on one implicit def if it has a resolvable type.
1041 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1042 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001043 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +00001044 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001045
Chris Lattnerd7349192010-03-19 21:37:09 +00001046 if (Operator->isSubClassOf("SDNodeXForm"))
1047 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001048
Chris Lattnerd7349192010-03-19 21:37:09 +00001049 Operator->dump();
1050 errs() << "Unhandled node in GetNumNodeResults\n";
1051 exit(1);
1052}
1053
1054void TreePatternNode::print(raw_ostream &OS) const {
1055 if (isLeaf())
1056 OS << *getLeafValue();
1057 else
1058 OS << '(' << getOperator()->getName();
1059
1060 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1061 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +00001062
1063 if (!isLeaf()) {
1064 if (getNumChildren() != 0) {
1065 OS << " ";
1066 getChild(0)->print(OS);
1067 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1068 OS << ", ";
1069 getChild(i)->print(OS);
1070 }
1071 }
1072 OS << ")";
1073 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001074
Dan Gohman0540e172008-10-15 06:17:21 +00001075 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner54379062011-04-17 21:38:24 +00001076 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +00001077 if (TransformFn)
1078 OS << "<<X:" << TransformFn->getName() << ">>";
1079 if (!getName().empty())
1080 OS << ":$" << getName();
1081
1082}
1083void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001084 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +00001085}
1086
Scott Michel327d0652008-03-05 17:49:05 +00001087/// isIsomorphicTo - Return true if this node is recursively
1088/// isomorphic to the specified node. For this comparison, the node's
1089/// entire state is considered. The assigned name is ignored, since
1090/// nodes with differing names are considered isomorphic. However, if
1091/// the assigned name is present in the dependent variable set, then
1092/// the assigned name is considered significant and the node is
1093/// isomorphic if the names match.
1094bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1095 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001096 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +00001097 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +00001098 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00001099 getTransformFn() != N->getTransformFn())
1100 return false;
1101
1102 if (isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001103 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1104 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +00001105 return ((DI->getDef() == NDI->getDef())
1106 && (DepVars.find(getName()) == DepVars.end()
1107 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +00001108 }
1109 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001110 return getLeafValue() == N->getLeafValue();
1111 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001112
Chris Lattner6cefb772008-01-05 22:25:12 +00001113 if (N->getOperator() != getOperator() ||
1114 N->getNumChildren() != getNumChildren()) return false;
1115 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00001116 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +00001117 return false;
1118 return true;
1119}
1120
1121/// clone - Make a copy of this tree and all of its children.
1122///
1123TreePatternNode *TreePatternNode::clone() const {
1124 TreePatternNode *New;
1125 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001126 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001127 } else {
1128 std::vector<TreePatternNode*> CChildren;
1129 CChildren.reserve(Children.size());
1130 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1131 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +00001132 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001133 }
1134 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001135 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +00001136 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00001137 New->setTransformFn(getTransformFn());
1138 return New;
1139}
1140
Chris Lattner47661322010-02-14 22:22:58 +00001141/// RemoveAllTypes - Recursively strip all the types of this tree.
1142void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +00001143 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1144 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +00001145 if (isLeaf()) return;
1146 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1147 getChild(i)->RemoveAllTypes();
1148}
1149
1150
Chris Lattner6cefb772008-01-05 22:25:12 +00001151/// SubstituteFormalArguments - Replace the formal arguments in this tree
1152/// with actual values specified by ArgMap.
1153void TreePatternNode::
1154SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1155 if (isLeaf()) return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001156
Chris Lattner6cefb772008-01-05 22:25:12 +00001157 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1158 TreePatternNode *Child = getChild(i);
1159 if (Child->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001160 Init *Val = Child->getLeafValue();
1161 if (dynamic_cast<DefInit*>(Val) &&
1162 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001163 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +00001164 TreePatternNode *NewChild = ArgMap[Child->getName()];
1165 assert(NewChild && "Couldn't find formal argument!");
1166 assert((Child->getPredicateFns().empty() ||
1167 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1168 "Non-empty child predicate clobbered!");
1169 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +00001170 }
1171 } else {
1172 getChild(i)->SubstituteFormalArguments(ArgMap);
1173 }
1174 }
1175}
1176
1177
1178/// InlinePatternFragments - If this pattern refers to any pattern
1179/// fragments, inline them into place, giving us a pattern without any
1180/// PatFrag references.
1181TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1182 if (isLeaf()) return this; // nothing to do.
1183 Record *Op = getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001184
Chris Lattner6cefb772008-01-05 22:25:12 +00001185 if (!Op->isSubClassOf("PatFrag")) {
1186 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00001187 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1188 TreePatternNode *Child = getChild(i);
1189 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1190
1191 assert((Child->getPredicateFns().empty() ||
1192 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1193 "Non-empty child predicate clobbered!");
1194
1195 setChild(i, NewChild);
1196 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001197 return this;
1198 }
1199
1200 // Otherwise, we found a reference to a fragment. First, look up its
1201 // TreePattern record.
1202 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001203
Chris Lattner6cefb772008-01-05 22:25:12 +00001204 // Verify that we are passing the right number of operands.
1205 if (Frag->getNumArgs() != Children.size())
1206 TP.error("'" + Op->getName() + "' fragment requires " +
1207 utostr(Frag->getNumArgs()) + " operands!");
1208
1209 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1210
Chris Lattner54379062011-04-17 21:38:24 +00001211 TreePredicateFn PredFn(Frag);
1212 if (!PredFn.isAlwaysTrue())
1213 FragTree->addPredicateFn(PredFn);
Dan Gohman0540e172008-10-15 06:17:21 +00001214
Chris Lattner6cefb772008-01-05 22:25:12 +00001215 // Resolve formal arguments to their actual value.
1216 if (Frag->getNumArgs()) {
1217 // Compute the map of formal to actual arguments.
1218 std::map<std::string, TreePatternNode*> ArgMap;
1219 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1220 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001221
Chris Lattner6cefb772008-01-05 22:25:12 +00001222 FragTree->SubstituteFormalArguments(ArgMap);
1223 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001224
Chris Lattner6cefb772008-01-05 22:25:12 +00001225 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001226 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1227 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +00001228
1229 // Transfer in the old predicates.
1230 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1231 FragTree->addPredicateFn(getPredicateFns()[i]);
1232
Chris Lattner6cefb772008-01-05 22:25:12 +00001233 // Get a new copy of this fragment to stitch into here.
1234 //delete this; // FIXME: implement refcounting!
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001235
Chris Lattner2ca698d2008-06-30 03:02:03 +00001236 // The fragment we inlined could have recursive inlining that is needed. See
1237 // if there are any pattern fragments in it and inline them as needed.
1238 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001239}
1240
1241/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +00001242/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +00001243/// references from the register file information, for example.
1244///
Chris Lattnerd7349192010-03-19 21:37:09 +00001245static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1246 bool NotRegisters, TreePattern &TP) {
Owen Andersonbea6f612011-06-27 21:06:21 +00001247 // Check to see if this is a register operand.
1248 if (R->isSubClassOf("RegisterOperand")) {
1249 assert(ResNo == 0 && "Regoperand ref only has one result!");
1250 if (NotRegisters)
1251 return EEVT::TypeSet(); // Unknown.
1252 Record *RegClass = R->getValueAsDef("RegClass");
1253 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1254 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1255 }
1256
Chris Lattner2cacec52010-03-15 06:00:16 +00001257 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00001258 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001259 assert(ResNo == 0 && "Regclass ref only has one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001260 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001261 return EEVT::TypeSet(); // Unknown.
1262 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1263 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001264 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001265
Chris Lattner640a3f52010-03-23 23:50:31 +00001266 if (R->isSubClassOf("PatFrag")) {
1267 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001268 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001269 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001270 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001271
Chris Lattner640a3f52010-03-23 23:50:31 +00001272 if (R->isSubClassOf("Register")) {
1273 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001274 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001275 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001276 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001277 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001278 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00001279
1280 if (R->isSubClassOf("SubRegIndex")) {
1281 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1282 return EEVT::TypeSet();
1283 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001284
Chris Lattner640a3f52010-03-23 23:50:31 +00001285 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1286 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001287 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001288 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001289 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001290
Chris Lattner640a3f52010-03-23 23:50:31 +00001291 if (R->isSubClassOf("ComplexPattern")) {
1292 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001293 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001294 return EEVT::TypeSet(); // Unknown.
1295 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1296 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001297 }
1298 if (R->isSubClassOf("PointerLikeRegClass")) {
1299 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001300 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001301 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001302
Chris Lattner640a3f52010-03-23 23:50:31 +00001303 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1304 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001305 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001306 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001307 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001308
Chris Lattner6cefb772008-01-05 22:25:12 +00001309 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001310 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001311}
1312
Chris Lattnere67bde52008-01-06 05:36:50 +00001313
1314/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1315/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1316const CodeGenIntrinsic *TreePatternNode::
1317getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1318 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1319 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1320 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1321 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001322
1323 unsigned IID =
David Greene05bce0b2011-07-29 22:43:06 +00001324 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
Chris Lattnere67bde52008-01-06 05:36:50 +00001325 return &CDP.getIntrinsicInfo(IID);
1326}
1327
Chris Lattner47661322010-02-14 22:22:58 +00001328/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1329/// return the ComplexPattern information, otherwise return null.
1330const ComplexPattern *
1331TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1332 if (!isLeaf()) return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001333
David Greene05bce0b2011-07-29 22:43:06 +00001334 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
Chris Lattner47661322010-02-14 22:22:58 +00001335 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1336 return &CGP.getComplexPattern(DI->getDef());
1337 return 0;
1338}
1339
1340/// NodeHasProperty - Return true if this node has the specified property.
1341bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001342 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001343 if (isLeaf()) {
1344 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1345 return CP->hasProperty(Property);
1346 return false;
1347 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001348
Chris Lattner47661322010-02-14 22:22:58 +00001349 Record *Operator = getOperator();
1350 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001351
Chris Lattner47661322010-02-14 22:22:58 +00001352 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1353}
1354
1355
1356
1357
1358/// TreeHasProperty - Return true if any node in this tree has the specified
1359/// property.
1360bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001361 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001362 if (NodeHasProperty(Property, CGP))
1363 return true;
1364 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1365 if (getChild(i)->TreeHasProperty(Property, CGP))
1366 return true;
1367 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001368}
Chris Lattner47661322010-02-14 22:22:58 +00001369
Evan Cheng6bd95672008-06-16 20:29:38 +00001370/// isCommutativeIntrinsic - Return true if the node corresponds to a
1371/// commutative intrinsic.
1372bool
1373TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1374 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1375 return Int->isCommutative;
1376 return false;
1377}
1378
Chris Lattnere67bde52008-01-06 05:36:50 +00001379
Bob Wilson6c01ca92009-01-05 17:23:09 +00001380/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001381/// this node and its children in the tree. This returns true if it makes a
1382/// change, false otherwise. If a type contradiction is found, throw an
1383/// exception.
1384bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001385 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001386 if (isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001387 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001388 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001389 bool MadeChange = false;
1390 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1391 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1392 NotRegisters, TP), TP);
1393 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001394 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001395
David Greene05bce0b2011-07-29 22:43:06 +00001396 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001397 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001398
Chris Lattnerd7349192010-03-19 21:37:09 +00001399 // Int inits are always integers. :)
1400 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001401
Chris Lattnerd7349192010-03-19 21:37:09 +00001402 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001403 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001404
Chris Lattnerd7349192010-03-19 21:37:09 +00001405 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001406 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1407 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001408
Chris Lattner2cacec52010-03-15 06:00:16 +00001409 unsigned Size = EVT(VT).getSizeInBits();
1410 // Make sure that the value is representable for this type.
1411 if (Size >= 32) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001412
Richard Smith1144af32012-08-24 23:29:28 +00001413 // Check that the value doesn't use more bits than we have. It must either
1414 // be a sign- or zero-extended equivalent of the original.
1415 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1416 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattner2cacec52010-03-15 06:00:16 +00001417 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001418
Richard Smith1144af32012-08-24 23:29:28 +00001419 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerd7349192010-03-19 21:37:09 +00001420 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001421 return MadeChange;
1422 }
1423 return false;
1424 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001425
Chris Lattner6cefb772008-01-05 22:25:12 +00001426 // special handling for set, which isn't really an SDNode.
1427 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001428 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1429 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001430 unsigned NC = getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001431
Chris Lattnerd7349192010-03-19 21:37:09 +00001432 TreePatternNode *SetVal = getChild(NC-1);
1433 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1434
Chris Lattner6cefb772008-01-05 22:25:12 +00001435 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001436 TreePatternNode *Child = getChild(i);
1437 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001438
Chris Lattner6cefb772008-01-05 22:25:12 +00001439 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001440 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1441 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001442 }
1443 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001444 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001445
Chris Lattner310adf12010-03-27 02:53:27 +00001446 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001447 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1448
Chris Lattner6cefb772008-01-05 22:25:12 +00001449 bool MadeChange = false;
1450 for (unsigned i = 0; i < getNumChildren(); ++i)
1451 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001452 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001453 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001454
Chris Lattner6eb30122010-02-23 05:51:07 +00001455 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001456 bool MadeChange = false;
1457 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1458 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001459
Chris Lattnerd7349192010-03-19 21:37:09 +00001460 assert(getChild(0)->getNumTypes() == 1 &&
1461 getChild(1)->getNumTypes() == 1 && "Unhandled case");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001462
Chris Lattner2cacec52010-03-15 06:00:16 +00001463 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1464 // what type it gets, so if it didn't get a concrete type just give it the
1465 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001466 if (!getChild(1)->hasTypeSet(0) &&
1467 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1468 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1469 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001470 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001471 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001472 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001473
Chris Lattner6eb30122010-02-23 05:51:07 +00001474 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001475 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001476
Chris Lattner6cefb772008-01-05 22:25:12 +00001477 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001478 unsigned NumRetVTs = Int->IS.RetVTs.size();
1479 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001480
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001481 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001482 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001483
Chris Lattnerd7349192010-03-19 21:37:09 +00001484 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001485 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001486 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001487 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001488
1489 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001490 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001491
Chris Lattnerd7349192010-03-19 21:37:09 +00001492 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1493 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001494
Chris Lattnerd7349192010-03-19 21:37:09 +00001495 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1496 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1497 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001498 }
1499 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001500 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001501
Chris Lattner6eb30122010-02-23 05:51:07 +00001502 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001503 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001504
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001505 // Check that the number of operands is sane. Negative operands -> varargs.
1506 if (NI.getNumOperands() >= 0 &&
1507 getNumChildren() != (unsigned)NI.getNumOperands())
1508 TP.error(getOperator()->getName() + " node requires exactly " +
1509 itostr(NI.getNumOperands()) + " operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001510
Chris Lattner6cefb772008-01-05 22:25:12 +00001511 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1512 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1513 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001514 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001515 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001516
Chris Lattner6eb30122010-02-23 05:51:07 +00001517 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001518 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001519 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001520 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001521
Chris Lattner0be6fe72010-03-27 19:15:02 +00001522 bool MadeChange = false;
1523
1524 // Apply the result types to the node, these come from the things in the
1525 // (outs) list of the instruction.
1526 // FIXME: Cap at one result so far.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001527 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001528 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1529 Record *ResultNode = Inst.getResult(ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001530
Chris Lattnera938ac62009-07-29 20:43:05 +00001531 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001532 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
Owen Andersonbea6f612011-06-27 21:06:21 +00001533 } else if (ResultNode->isSubClassOf("RegisterOperand")) {
1534 Record *RegClass = ResultNode->getValueAsDef("RegClass");
1535 const CodeGenRegisterClass &RC =
1536 CDP.getTargetInfo().getRegisterClass(RegClass);
1537 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Owen Anderson83c0eef2012-09-11 23:47:08 +00001538 } else if (ResultNode->isSubClassOf("unknown_class")) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001539 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001540 } else {
1541 assert(ResultNode->isSubClassOf("RegisterClass") &&
1542 "Operands should be register classes!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001543 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001544 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001545 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001546 }
Chris Lattner0be6fe72010-03-27 19:15:02 +00001547 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001548
Chris Lattner0be6fe72010-03-27 19:15:02 +00001549 // If the instruction has implicit defs, we apply the first one as a result.
1550 // FIXME: This sucks, it should apply all implicit defs.
1551 if (!InstInfo.ImplicitDefs.empty()) {
1552 unsigned ResNo = NumResultsToAdd;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001553
Chris Lattner9414ae52010-03-27 20:09:24 +00001554 // FIXME: Generalize to multiple possible types and multiple possible
1555 // ImplicitDefs.
1556 MVT::SimpleValueType VT =
1557 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001558
Chris Lattner9414ae52010-03-27 20:09:24 +00001559 if (VT != MVT::Other)
1560 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001561 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001562
Chris Lattner2cacec52010-03-15 06:00:16 +00001563 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1564 // be the same.
1565 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001566 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1567 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1568 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001569 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001570
1571 unsigned ChildNo = 0;
1572 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1573 Record *OperandNode = Inst.getOperand(i);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001574
Chris Lattner6cefb772008-01-05 22:25:12 +00001575 // If the instruction expects a predicate or optional def operand, we
1576 // codegen this by setting the operand to it's default value if it has a
1577 // non-empty DefaultOps field.
Tom Stellard6d3d7652012-09-06 14:15:52 +00001578 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001579 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1580 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001581
Chris Lattner6cefb772008-01-05 22:25:12 +00001582 // Verify that we didn't run out of provided operands.
1583 if (ChildNo >= getNumChildren())
1584 TP.error("Instruction '" + getOperator()->getName() +
1585 "' expects more operands than were provided.");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001586
Owen Anderson825b72b2009-08-11 20:47:22 +00001587 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001588 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001589 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001590
Chris Lattner6cefb772008-01-05 22:25:12 +00001591 if (OperandNode->isSubClassOf("RegisterClass")) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001592 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001593 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001594 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Owen Andersonbea6f612011-06-27 21:06:21 +00001595 } else if (OperandNode->isSubClassOf("RegisterOperand")) {
1596 Record *RegClass = OperandNode->getValueAsDef("RegClass");
1597 const CodeGenRegisterClass &RC =
1598 CDP.getTargetInfo().getRegisterClass(RegClass);
1599 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001600 } else if (OperandNode->isSubClassOf("Operand")) {
1601 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattner0be6fe72010-03-27 19:15:02 +00001602 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001603 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001604 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
Owen Anderson83c0eef2012-09-11 23:47:08 +00001605 } else if (OperandNode->isSubClassOf("unknown_class")) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001606 // Nothing to do.
Craig Topper655b8de2012-02-05 07:21:30 +00001607 } else
1608 llvm_unreachable("Unknown operand type!");
1609
Chris Lattner6cefb772008-01-05 22:25:12 +00001610 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1611 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001612
Christopher Lamb02f69372008-03-10 04:16:09 +00001613 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001614 TP.error("Instruction '" + getOperator()->getName() +
1615 "' was provided too many operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001616
Chris Lattner6cefb772008-01-05 22:25:12 +00001617 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001618 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001619
Chris Lattner6eb30122010-02-23 05:51:07 +00001620 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001621
Chris Lattner6eb30122010-02-23 05:51:07 +00001622 // Node transforms always take one operand.
1623 if (getNumChildren() != 1)
1624 TP.error("Node transform '" + getOperator()->getName() +
1625 "' requires one operand!");
1626
Chris Lattner2cacec52010-03-15 06:00:16 +00001627 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1628
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001629
Chris Lattner6eb30122010-02-23 05:51:07 +00001630 // If either the output or input of the xform does not have exact
1631 // type info. We assume they must be the same. Otherwise, it is perfectly
1632 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001633#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001634 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001635 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1636 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001637 return MadeChange;
1638 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001639#endif
1640 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001641}
1642
1643/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1644/// RHS of a commutative operation, not the on LHS.
1645static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1646 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1647 return true;
David Greene05bce0b2011-07-29 22:43:06 +00001648 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
Chris Lattner6cefb772008-01-05 22:25:12 +00001649 return true;
1650 return false;
1651}
1652
1653
1654/// canPatternMatch - If it is impossible for this pattern to match on this
1655/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001656/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001657/// that can never possibly work), and to prevent the pattern permuter from
1658/// generating stuff that is useless.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001659bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001660 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001661 if (isLeaf()) return true;
1662
1663 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1664 if (!getChild(i)->canPatternMatch(Reason, CDP))
1665 return false;
1666
1667 // If this is an intrinsic, handle cases that would make it not match. For
1668 // example, if an operand is required to be an immediate.
1669 if (getOperator()->isSubClassOf("Intrinsic")) {
1670 // TODO:
1671 return true;
1672 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001673
Chris Lattner6cefb772008-01-05 22:25:12 +00001674 // If this node is a commutative operator, check that the LHS isn't an
1675 // immediate.
1676 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001677 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1678 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001679 // Scan all of the operands of the node and make sure that only the last one
1680 // is a constant node, unless the RHS also is.
1681 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001682 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1683 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001684 if (OnlyOnRHSOfCommutative(getChild(i))) {
1685 Reason="Immediate value must be on the RHS of commutative operators!";
1686 return false;
1687 }
1688 }
1689 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001690
Chris Lattner6cefb772008-01-05 22:25:12 +00001691 return true;
1692}
1693
1694//===----------------------------------------------------------------------===//
1695// TreePattern implementation
1696//
1697
David Greene05bce0b2011-07-29 22:43:06 +00001698TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001699 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001700 isInputPattern = isInput;
1701 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattnerc2173052010-03-28 06:50:34 +00001702 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001703}
1704
David Greene05bce0b2011-07-29 22:43:06 +00001705TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001706 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001707 isInputPattern = isInput;
Chris Lattnerc2173052010-03-28 06:50:34 +00001708 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001709}
1710
1711TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001712 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001713 isInputPattern = isInput;
1714 Trees.push_back(Pat);
1715}
1716
Chris Lattner6cefb772008-01-05 22:25:12 +00001717void TreePattern::error(const std::string &Msg) const {
1718 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001719 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001720}
1721
Chris Lattner2cacec52010-03-15 06:00:16 +00001722void TreePattern::ComputeNamedNodes() {
1723 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1724 ComputeNamedNodes(Trees[i]);
1725}
1726
1727void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1728 if (!N->getName().empty())
1729 NamedNodes[N->getName()].push_back(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001730
Chris Lattner2cacec52010-03-15 06:00:16 +00001731 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1732 ComputeNamedNodes(N->getChild(i));
1733}
1734
Chris Lattnerd7349192010-03-19 21:37:09 +00001735
David Greene05bce0b2011-07-29 22:43:06 +00001736TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1737 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001738 Record *R = DI->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001739
Chris Lattnerc2173052010-03-28 06:50:34 +00001740 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbach66c9ee72011-07-06 23:38:13 +00001741 // TreePatternNode of its own. For example:
Chris Lattnerc2173052010-03-28 06:50:34 +00001742 /// (foo GPR, imm) -> (foo GPR, (imm))
1743 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenedcd35c72011-07-29 19:07:07 +00001744 return ParseTreePattern(
1745 DagInit::get(DI, "",
David Greene05bce0b2011-07-29 22:43:06 +00001746 std::vector<std::pair<Init*, std::string> >()),
David Greenedcd35c72011-07-29 19:07:07 +00001747 OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001748
Chris Lattnerc2173052010-03-28 06:50:34 +00001749 // Input argument?
1750 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001751 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001752 if (OpName.empty())
1753 error("'node' argument requires a name to match with operand list");
1754 Args.push_back(OpName);
1755 }
1756
1757 Res->setName(OpName);
1758 return Res;
1759 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001760
David Greene05bce0b2011-07-29 22:43:06 +00001761 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001762 if (!OpName.empty())
1763 error("Constant int argument should not have a name!");
1764 return new TreePatternNode(II, 1);
1765 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001766
David Greene05bce0b2011-07-29 22:43:06 +00001767 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001768 // Turn this into an IntInit.
David Greene05bce0b2011-07-29 22:43:06 +00001769 Init *II = BI->convertInitializerTo(IntRecTy::get());
1770 if (II == 0 || !dynamic_cast<IntInit*>(II))
Chris Lattnerc2173052010-03-28 06:50:34 +00001771 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001772 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00001773 }
1774
David Greene05bce0b2011-07-29 22:43:06 +00001775 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
Chris Lattnerc2173052010-03-28 06:50:34 +00001776 if (!Dag) {
1777 TheInit->dump();
1778 error("Pattern has unexpected init kind!");
1779 }
David Greene05bce0b2011-07-29 22:43:06 +00001780 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001781 if (!OpDef) error("Pattern has unexpected operator type!");
1782 Record *Operator = OpDef->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001783
Chris Lattner6cefb772008-01-05 22:25:12 +00001784 if (Operator->isSubClassOf("ValueType")) {
1785 // If the operator is a ValueType, then this must be "type cast" of a leaf
1786 // node.
1787 if (Dag->getNumArgs() != 1)
1788 error("Type cast only takes one operand!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001789
Chris Lattnerc2173052010-03-28 06:50:34 +00001790 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001791
Chris Lattner6cefb772008-01-05 22:25:12 +00001792 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001793 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1794 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001795
Chris Lattnerc2173052010-03-28 06:50:34 +00001796 if (!OpName.empty())
1797 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001798 return New;
1799 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001800
Chris Lattner6cefb772008-01-05 22:25:12 +00001801 // Verify that this is something that makes sense for an operator.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001802 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begeman7cee8172009-03-19 05:21:56 +00001803 !Operator->isSubClassOf("SDNode") &&
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001804 !Operator->isSubClassOf("Instruction") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001805 !Operator->isSubClassOf("SDNodeXForm") &&
1806 !Operator->isSubClassOf("Intrinsic") &&
1807 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001808 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001809 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001810
Chris Lattner6cefb772008-01-05 22:25:12 +00001811 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001812 if (isInputPattern) {
1813 if (Operator->isSubClassOf("Instruction") ||
1814 Operator->isSubClassOf("SDNodeXForm"))
1815 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1816 } else {
1817 if (Operator->isSubClassOf("Intrinsic"))
1818 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001819
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001820 if (Operator->isSubClassOf("SDNode") &&
1821 Operator->getName() != "imm" &&
1822 Operator->getName() != "fpimm" &&
1823 Operator->getName() != "tglobaltlsaddr" &&
1824 Operator->getName() != "tconstpool" &&
1825 Operator->getName() != "tjumptable" &&
1826 Operator->getName() != "tframeindex" &&
1827 Operator->getName() != "texternalsym" &&
1828 Operator->getName() != "tblockaddress" &&
1829 Operator->getName() != "tglobaladdr" &&
1830 Operator->getName() != "bb" &&
1831 Operator->getName() != "vt")
1832 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1833 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001834
Chris Lattner6cefb772008-01-05 22:25:12 +00001835 std::vector<TreePatternNode*> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00001836
1837 // Parse all the operands.
1838 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1839 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001840
Chris Lattner6cefb772008-01-05 22:25:12 +00001841 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001842 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner6cefb772008-01-05 22:25:12 +00001843 // convert the intrinsic name to a number.
1844 if (Operator->isSubClassOf("Intrinsic")) {
1845 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1846 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1847
1848 // If this intrinsic returns void, it must have side-effects and thus a
1849 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00001850 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001851 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001852 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00001853 // Has side-effects, requires chain.
1854 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001855 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00001856 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001857
David Greenedcd35c72011-07-29 19:07:07 +00001858 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001859 Children.insert(Children.begin(), IIDNode);
1860 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001861
Chris Lattnerd7349192010-03-19 21:37:09 +00001862 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1863 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00001864 Result->setName(OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001865
Chris Lattnerc2173052010-03-28 06:50:34 +00001866 if (!Dag->getName().empty()) {
1867 assert(Result->getName().empty());
1868 Result->setName(Dag->getName());
1869 }
Nate Begeman7cee8172009-03-19 05:21:56 +00001870 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001871}
1872
Chris Lattner7a0eb912010-03-28 08:38:32 +00001873/// SimplifyTree - See if we can simplify this tree to eliminate something that
1874/// will never match in favor of something obvious that will. This is here
1875/// strictly as a convenience to target authors because it allows them to write
1876/// more type generic things and have useless type casts fold away.
1877///
1878/// This returns true if any change is made.
1879static bool SimplifyTree(TreePatternNode *&N) {
1880 if (N->isLeaf())
1881 return false;
1882
1883 // If we have a bitconvert with a resolved type and if the source and
1884 // destination types are the same, then the bitconvert is useless, remove it.
1885 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattner7a0eb912010-03-28 08:38:32 +00001886 N->getExtType(0).isConcrete() &&
1887 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1888 N->getName().empty()) {
1889 N = N->getChild(0);
1890 SimplifyTree(N);
1891 return true;
1892 }
1893
1894 // Walk all children.
1895 bool MadeChange = false;
1896 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1897 TreePatternNode *Child = N->getChild(i);
1898 MadeChange |= SimplifyTree(Child);
1899 N->setChild(i, Child);
1900 }
1901 return MadeChange;
1902}
1903
1904
1905
Chris Lattner6cefb772008-01-05 22:25:12 +00001906/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001907/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001908/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001909bool TreePattern::
1910InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1911 if (NamedNodes.empty())
1912 ComputeNamedNodes();
1913
Chris Lattner6cefb772008-01-05 22:25:12 +00001914 bool MadeChange = true;
1915 while (MadeChange) {
1916 MadeChange = false;
Chris Lattner7a0eb912010-03-28 08:38:32 +00001917 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001918 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner7a0eb912010-03-28 08:38:32 +00001919 MadeChange |= SimplifyTree(Trees[i]);
1920 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001921
1922 // If there are constraints on our named nodes, apply them.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001923 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattner2cacec52010-03-15 06:00:16 +00001924 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1925 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001926
Chris Lattner2cacec52010-03-15 06:00:16 +00001927 // If we have input named node types, propagate their types to the named
1928 // values here.
1929 if (InNamedTypes) {
1930 // FIXME: Should be error?
1931 assert(InNamedTypes->count(I->getKey()) &&
1932 "Named node in output pattern but not input pattern?");
1933
1934 const SmallVectorImpl<TreePatternNode*> &InNodes =
1935 InNamedTypes->find(I->getKey())->second;
1936
1937 // The input types should be fully resolved by now.
1938 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1939 // If this node is a register class, and it is the root of the pattern
1940 // then we're mapping something onto an input register. We allow
1941 // changing the type of the input register in this case. This allows
1942 // us to match things like:
1943 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1944 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001945 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00001946 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
1947 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner2cacec52010-03-15 06:00:16 +00001948 continue;
1949 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001950
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001951 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001952 InNodes[0]->getNumTypes() == 1 &&
1953 "FIXME: cannot name multiple result nodes yet");
1954 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1955 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001956 }
1957 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001958
Chris Lattner2cacec52010-03-15 06:00:16 +00001959 // If there are multiple nodes with the same name, they must all have the
1960 // same type.
1961 if (I->second.size() > 1) {
1962 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001963 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001964 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001965 "FIXME: cannot name multiple result nodes yet");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001966
Chris Lattnerd7349192010-03-19 21:37:09 +00001967 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1968 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001969 }
1970 }
1971 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001972 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001973
Chris Lattner6cefb772008-01-05 22:25:12 +00001974 bool HasUnresolvedTypes = false;
1975 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1976 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1977 return !HasUnresolvedTypes;
1978}
1979
Daniel Dunbar1a551802009-07-03 00:10:29 +00001980void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001981 OS << getRecord()->getName();
1982 if (!Args.empty()) {
1983 OS << "(" << Args[0];
1984 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1985 OS << ", " << Args[i];
1986 OS << ")";
1987 }
1988 OS << ": ";
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001989
Chris Lattner6cefb772008-01-05 22:25:12 +00001990 if (Trees.size() > 1)
1991 OS << "[\n";
1992 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1993 OS << "\t";
1994 Trees[i]->print(OS);
1995 OS << "\n";
1996 }
1997
1998 if (Trees.size() > 1)
1999 OS << "]\n";
2000}
2001
Daniel Dunbar1a551802009-07-03 00:10:29 +00002002void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00002003
2004//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00002005// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00002006//
2007
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002008CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner67db8832010-12-13 00:23:57 +00002009 Records(R), Target(R) {
2010
Dale Johannesen49de9822009-02-05 01:49:45 +00002011 Intrinsics = LoadIntrinsics(Records, false);
2012 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00002013 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00002014 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00002015 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002016 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00002017 ParseDefaultOperands();
2018 ParseInstructions();
2019 ParsePatterns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002020
Chris Lattner6cefb772008-01-05 22:25:12 +00002021 // Generate variants. For example, commutative patterns can match
2022 // multiple ways. Add them to PatternsToMatch as well.
2023 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00002024
2025 // Infer instruction flags. For example, we can detect loads,
2026 // stores, and side effects in many cases by examining an
2027 // instruction's pattern.
2028 InferInstructionFlags();
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00002029
2030 // Verify that instruction flags match the patterns.
2031 VerifyInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00002032}
2033
Chris Lattnerfe718932008-01-06 01:10:31 +00002034CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002035 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002036 E = PatternFragments.end(); I != E; ++I)
2037 delete I->second;
2038}
2039
2040
Chris Lattnerfe718932008-01-06 01:10:31 +00002041Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00002042 Record *N = Records.getDef(Name);
2043 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002044 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00002045 exit(1);
2046 }
2047 return N;
2048}
2049
2050// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00002051void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002052 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2053 while (!Nodes.empty()) {
2054 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2055 Nodes.pop_back();
2056 }
2057
Jim Grosbachda4231f2009-03-26 16:17:51 +00002058 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00002059 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2060 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2061 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2062}
2063
2064/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2065/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002066void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002067 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2068 while (!Xforms.empty()) {
2069 Record *XFormNode = Xforms.back();
2070 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +00002071 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00002072 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002073
2074 Xforms.pop_back();
2075 }
2076}
2077
Chris Lattnerfe718932008-01-06 01:10:31 +00002078void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002079 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2080 while (!AMs.empty()) {
2081 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2082 AMs.pop_back();
2083 }
2084}
2085
2086
2087/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2088/// file, building up the PatternFragments map. After we've collected them all,
2089/// inline fragments together as necessary, so that there are no references left
2090/// inside a pattern fragment to a pattern fragment.
2091///
Chris Lattnerfe718932008-01-06 01:10:31 +00002092void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002093 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002094
Chris Lattnerdc32f982008-01-05 22:43:57 +00002095 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002096 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00002097 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattner6cefb772008-01-05 22:25:12 +00002098 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2099 PatternFragments[Fragments[i]] = P;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002100
Chris Lattnerdc32f982008-01-05 22:43:57 +00002101 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00002102 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002103 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002104
Chris Lattnerdc32f982008-01-05 22:43:57 +00002105 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00002106 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002107
Chris Lattner6cefb772008-01-05 22:25:12 +00002108 // Parse the operands list.
David Greene05bce0b2011-07-29 22:43:06 +00002109 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2110 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00002111 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00002112 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00002113 if (!OpsOp ||
2114 (OpsOp->getDef()->getName() != "ops" &&
2115 OpsOp->getDef()->getName() != "outs" &&
2116 OpsOp->getDef()->getName() != "ins"))
2117 P->error("Operands list should start with '(ops ... '!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002118
2119 // Copy over the arguments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002120 Args.clear();
2121 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
David Greene05bce0b2011-07-29 22:43:06 +00002122 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
2123 static_cast<DefInit*>(OpsList->getArg(j))->
Chris Lattner6cefb772008-01-05 22:25:12 +00002124 getDef()->getName() != "node")
2125 P->error("Operands list should all be 'node' values.");
2126 if (OpsList->getArgName(j).empty())
2127 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002128 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00002129 P->error("'" + OpsList->getArgName(j) +
2130 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002131 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00002132 Args.push_back(OpsList->getArgName(j));
2133 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002134
Chris Lattnerdc32f982008-01-05 22:43:57 +00002135 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00002136 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00002137 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002138
Chris Lattnerdc32f982008-01-05 22:43:57 +00002139 // If there is a code init for this fragment, keep track of the fact that
2140 // this fragment uses it.
Chris Lattner54379062011-04-17 21:38:24 +00002141 TreePredicateFn PredFn(P);
2142 if (!PredFn.isAlwaysTrue())
2143 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002144
Chris Lattner6cefb772008-01-05 22:25:12 +00002145 // If there is a node transformation corresponding to this, keep track of
2146 // it.
2147 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2148 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2149 P->getOnlyTree()->setTransformFn(Transform);
2150 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002151
Chris Lattner6cefb772008-01-05 22:25:12 +00002152 // Now that we've parsed all of the tree fragments, do a closure on them so
2153 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00002154 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2155 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00002156 ThePat->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002157
Chris Lattner6cefb772008-01-05 22:25:12 +00002158 // Infer as many types as possible. Don't worry about it if we don't infer
2159 // all of them, some may depend on the inputs of the pattern.
2160 try {
2161 ThePat->InferAllTypes();
2162 } catch (...) {
2163 // If this pattern fragment is not supported by this target (no types can
2164 // satisfy its constraints), just ignore it. If the bogus pattern is
2165 // actually used by instructions, the type consistency error will be
2166 // reported there.
2167 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002168
Chris Lattner6cefb772008-01-05 22:25:12 +00002169 // If debugging, print out the pattern fragment result.
2170 DEBUG(ThePat->dump());
2171 }
2172}
2173
Chris Lattnerfe718932008-01-06 01:10:31 +00002174void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellard6d3d7652012-09-06 14:15:52 +00002175 std::vector<Record*> DefaultOps;
2176 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner6cefb772008-01-05 22:25:12 +00002177
2178 // Find some SDNode.
2179 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greene05bce0b2011-07-29 22:43:06 +00002180 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002181
Tom Stellard6d3d7652012-09-06 14:15:52 +00002182 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2183 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002184
Tom Stellard6d3d7652012-09-06 14:15:52 +00002185 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2186 // SomeSDnode so that we can parse this.
2187 std::vector<std::pair<Init*, std::string> > Ops;
2188 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2189 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2190 DefaultInfo->getArgName(op)));
2191 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002192
Tom Stellard6d3d7652012-09-06 14:15:52 +00002193 // Create a TreePattern to parse this.
2194 TreePattern P(DefaultOps[i], DI, false, *this);
2195 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002196
Tom Stellard6d3d7652012-09-06 14:15:52 +00002197 // Copy the operands over into a DAGDefaultOperand.
2198 DAGDefaultOperand DefaultOpInfo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002199
Tom Stellard6d3d7652012-09-06 14:15:52 +00002200 TreePatternNode *T = P.getTree(0);
2201 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2202 TreePatternNode *TPN = T->getChild(op);
2203 while (TPN->ApplyTypeConstraints(P, false))
2204 /* Resolve all types */;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002205
Tom Stellard6d3d7652012-09-06 14:15:52 +00002206 if (TPN->ContainsUnresolvedType()) {
2207 throw "Value #" + utostr(i) + " of OperandWithDefaultOps '" +
2208 DefaultOps[i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00002209 }
Tom Stellard6d3d7652012-09-06 14:15:52 +00002210 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner6cefb772008-01-05 22:25:12 +00002211 }
Tom Stellard6d3d7652012-09-06 14:15:52 +00002212
2213 // Insert it into the DefaultOperands map so we can find it later.
2214 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner6cefb772008-01-05 22:25:12 +00002215 }
2216}
2217
2218/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2219/// instruction input. Return true if this is a real use.
2220static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002221 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002222 // No name -> not interesting.
2223 if (Pat->getName().empty()) {
2224 if (Pat->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002225 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00002226 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2227 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002228 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002229 }
2230 return false;
2231 }
2232
2233 Record *Rec;
2234 if (Pat->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002235 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002236 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2237 Rec = DI->getDef();
2238 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00002239 Rec = Pat->getOperator();
2240 }
2241
2242 // SRCVALUE nodes are ignored.
2243 if (Rec->getName() == "srcvalue")
2244 return false;
2245
2246 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2247 if (!Slot) {
2248 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00002249 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00002250 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00002251 Record *SlotRec;
2252 if (Slot->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002253 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattner53d09bd2010-02-23 05:59:10 +00002254 } else {
2255 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2256 SlotRec = Slot->getOperator();
2257 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002258
Chris Lattner53d09bd2010-02-23 05:59:10 +00002259 // Ensure that the inputs agree if we've already seen this input.
2260 if (Rec != SlotRec)
2261 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00002262 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00002263 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00002264 return true;
2265}
2266
2267/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2268/// part of "I", the instruction), computing the set of inputs and outputs of
2269/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00002270void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00002271FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2272 std::map<std::string, TreePatternNode*> &InstInputs,
2273 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner6cefb772008-01-05 22:25:12 +00002274 std::vector<Record*> &InstImpResults) {
2275 if (Pat->isLeaf()) {
Chris Lattneracfb70f2010-04-20 06:30:25 +00002276 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002277 if (!isUse && Pat->getTransformFn())
2278 I->error("Cannot specify a transform function for a non-input value!");
2279 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002280 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002281
Chris Lattner84aa60b2010-02-17 06:53:36 +00002282 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002283 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2284 TreePatternNode *Dest = Pat->getChild(i);
2285 if (!Dest->isLeaf())
2286 I->error("implicitly defined value should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002287
David Greene05bce0b2011-07-29 22:43:06 +00002288 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002289 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2290 I->error("implicitly defined value should be a register!");
2291 InstImpResults.push_back(Val->getDef());
2292 }
2293 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002294 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002295
Chris Lattner84aa60b2010-02-17 06:53:36 +00002296 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002297 // If this is not a set, verify that the children nodes are not void typed,
2298 // and recurse.
2299 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002300 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002301 I->error("Cannot have void nodes inside of patterns!");
2302 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002303 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002304 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002305
Chris Lattner6cefb772008-01-05 22:25:12 +00002306 // If this is a non-leaf node with no children, treat it basically as if
2307 // it were a leaf. This handles nodes like (imm).
Chris Lattneracfb70f2010-04-20 06:30:25 +00002308 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002309
Chris Lattner6cefb772008-01-05 22:25:12 +00002310 if (!isUse && Pat->getTransformFn())
2311 I->error("Cannot specify a transform function for a non-input value!");
2312 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002313 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002314
Chris Lattner6cefb772008-01-05 22:25:12 +00002315 // Otherwise, this is a set, validate and collect instruction results.
2316 if (Pat->getNumChildren() == 0)
2317 I->error("set requires operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002318
Chris Lattner6cefb772008-01-05 22:25:12 +00002319 if (Pat->getTransformFn())
2320 I->error("Cannot specify a transform function on a set node!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002321
Chris Lattner6cefb772008-01-05 22:25:12 +00002322 // Check the set destinations.
2323 unsigned NumDests = Pat->getNumChildren()-1;
2324 for (unsigned i = 0; i != NumDests; ++i) {
2325 TreePatternNode *Dest = Pat->getChild(i);
2326 if (!Dest->isLeaf())
2327 I->error("set destination should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002328
David Greene05bce0b2011-07-29 22:43:06 +00002329 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002330 if (!Val)
2331 I->error("set destination should be a register!");
2332
2333 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Owen Andersonbea6f612011-06-27 21:06:21 +00002334 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002335 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002336 if (Dest->getName().empty())
2337 I->error("set destination must have a name!");
2338 if (InstResults.count(Dest->getName()))
2339 I->error("cannot set '" + Dest->getName() +"' multiple times");
2340 InstResults[Dest->getName()] = Dest;
2341 } else if (Val->getDef()->isSubClassOf("Register")) {
2342 InstImpResults.push_back(Val->getDef());
2343 } else {
2344 I->error("set destination should be a register!");
2345 }
2346 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002347
Chris Lattner6cefb772008-01-05 22:25:12 +00002348 // Verify and collect info from the computation.
2349 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattneracfb70f2010-04-20 06:30:25 +00002350 InstInputs, InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002351}
2352
Dan Gohmanee4fa192008-04-03 00:02:49 +00002353//===----------------------------------------------------------------------===//
2354// Instruction Analysis
2355//===----------------------------------------------------------------------===//
2356
2357class InstAnalyzer {
2358 const CodeGenDAGPatterns &CDP;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002359public:
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002360 bool hasSideEffects;
2361 bool mayStore;
2362 bool mayLoad;
2363 bool isBitcast;
2364 bool isVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002365
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002366 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2367 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2368 isBitcast(false), isVariadic(false) {}
Dan Gohmanee4fa192008-04-03 00:02:49 +00002369
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002370 void Analyze(const TreePattern *Pat) {
2371 // Assume only the first tree is the pattern. The others are clobber nodes.
2372 AnalyzeNode(Pat->getTree(0));
Dan Gohmanee4fa192008-04-03 00:02:49 +00002373 }
2374
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00002375 void Analyze(const PatternToMatch *Pat) {
2376 AnalyzeNode(Pat->getSrcPattern());
2377 }
2378
Dan Gohmanee4fa192008-04-03 00:02:49 +00002379private:
Evan Cheng0f040a22011-03-15 05:09:26 +00002380 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002381 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng0f040a22011-03-15 05:09:26 +00002382 return false;
2383
2384 if (N->getNumChildren() != 2)
2385 return false;
2386
2387 const TreePatternNode *N0 = N->getChild(0);
David Greene05bce0b2011-07-29 22:43:06 +00002388 if (!N0->isLeaf() || !dynamic_cast<DefInit*>(N0->getLeafValue()))
Evan Cheng0f040a22011-03-15 05:09:26 +00002389 return false;
2390
2391 const TreePatternNode *N1 = N->getChild(1);
2392 if (N1->isLeaf())
2393 return false;
2394 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2395 return false;
2396
2397 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2398 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2399 return false;
2400 return OpInfo.getEnumName() == "ISD::BITCAST";
2401 }
2402
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00002403public:
Dan Gohmanee4fa192008-04-03 00:02:49 +00002404 void AnalyzeNode(const TreePatternNode *N) {
2405 if (N->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00002406 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002407 Record *LeafRec = DI->getDef();
2408 // Handle ComplexPattern leaves.
2409 if (LeafRec->isSubClassOf("ComplexPattern")) {
2410 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2411 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2412 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002413 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002414 }
2415 }
2416 return;
2417 }
2418
2419 // Analyze children.
2420 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2421 AnalyzeNode(N->getChild(i));
2422
2423 // Ignore set nodes, which are not SDNodes.
Evan Cheng0f040a22011-03-15 05:09:26 +00002424 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002425 isBitcast = IsNodeBitcast(N);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002426 return;
Evan Cheng0f040a22011-03-15 05:09:26 +00002427 }
Dan Gohmanee4fa192008-04-03 00:02:49 +00002428
2429 // Get information about the SDNode for the operator.
2430 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2431
2432 // Notice properties of the node.
2433 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2434 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002435 if (OpInfo.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2436 if (OpInfo.hasProperty(SDNPVariadic)) isVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002437
2438 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2439 // If this is an intrinsic, analyze it.
2440 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2441 mayLoad = true;// These may load memory.
2442
Dan Gohman7365c092010-08-05 23:36:21 +00002443 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002444 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2445
Dan Gohman7365c092010-08-05 23:36:21 +00002446 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002447 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002448 hasSideEffects = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002449 }
2450 }
2451
2452};
2453
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002454static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002455 const InstAnalyzer &PatInfo,
2456 Record *PatDef) {
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002457 bool Error = false;
2458
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002459 // Remember where InstInfo got its flags.
2460 if (InstInfo.hasUndefFlags())
2461 InstInfo.InferredFrom = PatDef;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002462
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002463 // Check explicitly set flags for consistency.
2464 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2465 !InstInfo.hasSideEffects_Unset) {
2466 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2467 // the pattern has no side effects. That could be useful for div/rem
2468 // instructions that may trap.
2469 if (!InstInfo.hasSideEffects) {
2470 Error = true;
2471 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2472 Twine(InstInfo.hasSideEffects));
2473 }
2474 }
2475
2476 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2477 Error = true;
2478 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2479 Twine(InstInfo.mayStore));
2480 }
2481
2482 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2483 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2484 // Some targets translate imediates to loads.
2485 if (!InstInfo.mayLoad) {
2486 Error = true;
2487 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2488 Twine(InstInfo.mayLoad));
2489 }
2490 }
2491
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002492 // Transfer inferred flags.
2493 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2494 InstInfo.mayStore |= PatInfo.mayStore;
2495 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002496
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002497 // These flags are silently added without any verification.
2498 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenaaaecfc2012-08-24 21:08:09 +00002499
2500 // Don't infer isVariadic. This flag means something different on SDNodes and
2501 // instructions. For example, a CALL SDNode is variadic because it has the
2502 // call arguments as operands, but a CALL instruction is not variadic - it
2503 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002504
2505 return Error;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002506}
2507
Jim Grosbachac915b42012-07-17 00:47:06 +00002508/// hasNullFragReference - Return true if the DAG has any reference to the
2509/// null_frag operator.
2510static bool hasNullFragReference(DagInit *DI) {
2511 DefInit *OpDef = dynamic_cast<DefInit*>(DI->getOperator());
2512 if (!OpDef) return false;
2513 Record *Operator = OpDef->getDef();
2514
2515 // If this is the null fragment, return true.
2516 if (Operator->getName() == "null_frag") return true;
2517 // If any of the arguments reference the null fragment, return true.
2518 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2519 DagInit *Arg = dynamic_cast<DagInit*>(DI->getArg(i));
2520 if (Arg && hasNullFragReference(Arg))
2521 return true;
2522 }
2523
2524 return false;
2525}
2526
2527/// hasNullFragReference - Return true if any DAG in the list references
2528/// the null_frag operator.
2529static bool hasNullFragReference(ListInit *LI) {
2530 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
2531 DagInit *DI = dynamic_cast<DagInit*>(LI->getElement(i));
2532 assert(DI && "non-dag in an instruction Pattern list?!");
2533 if (hasNullFragReference(DI))
2534 return true;
2535 }
2536 return false;
2537}
2538
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00002539/// Get all the instructions in a tree.
2540static void
2541getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2542 if (Tree->isLeaf())
2543 return;
2544 if (Tree->getOperator()->isSubClassOf("Instruction"))
2545 Instrs.push_back(Tree->getOperator());
2546 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2547 getInstructionsInTree(Tree->getChild(i), Instrs);
2548}
2549
Chris Lattner6cefb772008-01-05 22:25:12 +00002550/// ParseInstructions - Parse all of the instructions, inlining and resolving
2551/// any fragments involved. This populates the Instructions list with fully
2552/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002553void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002554 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002555
Chris Lattner6cefb772008-01-05 22:25:12 +00002556 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00002557 ListInit *LI = 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002558
David Greene05bce0b2011-07-29 22:43:06 +00002559 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002560 LI = Instrs[i]->getValueAsListInit("Pattern");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002561
Chris Lattner6cefb772008-01-05 22:25:12 +00002562 // If there is no pattern, only collect minimal information about the
2563 // instruction for its operand list. We have to assume that there is one
Jim Grosbachac915b42012-07-17 00:47:06 +00002564 // result, as we have no detailed info. A pattern which references the
2565 // null_frag operator is as-if no pattern were specified. Normally this
2566 // is from a multiclass expansion w/ a SDPatternOperator passed in as
2567 // null_frag.
2568 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002569 std::vector<Record*> Results;
2570 std::vector<Record*> Operands;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002571
Chris Lattnerf30187a2010-03-19 00:07:20 +00002572 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002573
Chris Lattnerc240bb02010-11-01 04:03:32 +00002574 if (InstInfo.Operands.size() != 0) {
2575 if (InstInfo.Operands.NumDefs == 0) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002576 // These produce no results
Chris Lattnerc240bb02010-11-01 04:03:32 +00002577 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2578 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002579 } else {
2580 // Assume the first operand is the result.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002581 Results.push_back(InstInfo.Operands[0].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002582
Chris Lattner6cefb772008-01-05 22:25:12 +00002583 // The rest are inputs.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002584 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2585 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002586 }
2587 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002588
Chris Lattner6cefb772008-01-05 22:25:12 +00002589 // Create and insert the instruction.
2590 std::vector<Record*> ImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002591 Instructions.insert(std::make_pair(Instrs[i],
Chris Lattner62bcec82010-04-20 06:28:43 +00002592 DAGInstruction(0, Results, Operands, ImpResults)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002593 continue; // no pattern.
2594 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002595
Chris Lattner6cefb772008-01-05 22:25:12 +00002596 // Parse the instruction.
2597 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2598 // Inline pattern fragments into it.
2599 I->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002600
Chris Lattner6cefb772008-01-05 22:25:12 +00002601 // Infer as many types as possible. If we cannot infer all of them, we can
2602 // never do anything with this instruction pattern: report it to the user.
2603 if (!I->InferAllTypes())
2604 I->error("Could not infer all types in pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002605
2606 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner6cefb772008-01-05 22:25:12 +00002607 // with the record they are declared as.
2608 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002609
Chris Lattner6cefb772008-01-05 22:25:12 +00002610 // InstResults - Keep track of all the virtual registers that are 'set'
2611 // in the instruction, including what reg class they are.
2612 std::map<std::string, TreePatternNode*> InstResults;
2613
Chris Lattner6cefb772008-01-05 22:25:12 +00002614 std::vector<Record*> InstImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002615
Chris Lattner6cefb772008-01-05 22:25:12 +00002616 // Verify that the top-level forms in the instruction are of void type, and
2617 // fill in the InstResults map.
2618 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2619 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002620 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002621 I->error("Top-level forms in instruction pattern should have"
2622 " void types");
2623
2624 // Find inputs and outputs, and verify the structure of the uses/defs.
2625 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002626 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002627 }
2628
2629 // Now that we have inputs and outputs of the pattern, inspect the operands
2630 // list for the instruction. This determines the order that operands are
2631 // added to the machine instruction the node corresponds to.
2632 unsigned NumResults = InstResults.size();
2633
2634 // Parse the operands list from the (ops) list, validating it.
2635 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002636 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002637
2638 // Check that all of the results occur first in the list.
2639 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002640 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002641 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00002642 if (i == CGI.Operands.size())
Chris Lattner6cefb772008-01-05 22:25:12 +00002643 I->error("'" + InstResults.begin()->first +
2644 "' set but does not appear in operand list!");
Chris Lattnerc240bb02010-11-01 04:03:32 +00002645 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002646
Chris Lattner6cefb772008-01-05 22:25:12 +00002647 // Check that it exists in InstResults.
2648 TreePatternNode *RNode = InstResults[OpName];
2649 if (RNode == 0)
2650 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002651
Chris Lattner6cefb772008-01-05 22:25:12 +00002652 if (i == 0)
2653 Res0Node = RNode;
David Greene05bce0b2011-07-29 22:43:06 +00002654 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner6cefb772008-01-05 22:25:12 +00002655 if (R == 0)
2656 I->error("Operand $" + OpName + " should be a set destination: all "
2657 "outputs must occur before inputs in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002658
Chris Lattnerc240bb02010-11-01 04:03:32 +00002659 if (CGI.Operands[i].Rec != R)
Chris Lattner6cefb772008-01-05 22:25:12 +00002660 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002661
Chris Lattner6cefb772008-01-05 22:25:12 +00002662 // Remember the return type.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002663 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002664
Chris Lattner6cefb772008-01-05 22:25:12 +00002665 // Okay, this one checks out.
2666 InstResults.erase(OpName);
2667 }
2668
2669 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2670 // the copy while we're checking the inputs.
2671 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2672
2673 std::vector<TreePatternNode*> ResultNodeOperands;
2674 std::vector<Record*> Operands;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002675 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2676 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner6cefb772008-01-05 22:25:12 +00002677 const std::string &OpName = Op.Name;
2678 if (OpName.empty())
2679 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2680
2681 if (!InstInputsCheck.count(OpName)) {
Tom Stellard6d3d7652012-09-06 14:15:52 +00002682 // If this is an operand with a DefaultOps set filled in, we can ignore
2683 // this. When we codegen it, we will do so as always executed.
2684 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002685 // Does it have a non-empty DefaultOps field? If so, ignore this
2686 // operand.
2687 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2688 continue;
2689 }
2690 I->error("Operand $" + OpName +
2691 " does not appear in the instruction pattern");
2692 }
2693 TreePatternNode *InVal = InstInputsCheck[OpName];
2694 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002695
Chris Lattner6cefb772008-01-05 22:25:12 +00002696 if (InVal->isLeaf() &&
David Greene05bce0b2011-07-29 22:43:06 +00002697 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2698 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Chris Lattner6cefb772008-01-05 22:25:12 +00002699 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2700 I->error("Operand $" + OpName + "'s register class disagrees"
2701 " between the operand and pattern");
2702 }
2703 Operands.push_back(Op.Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002704
Chris Lattner6cefb772008-01-05 22:25:12 +00002705 // Construct the result for the dest-pattern operand list.
2706 TreePatternNode *OpNode = InVal->clone();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002707
Chris Lattner6cefb772008-01-05 22:25:12 +00002708 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002709 OpNode->clearPredicateFns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002710
Chris Lattner6cefb772008-01-05 22:25:12 +00002711 // Promote the xform function to be an explicit node if set.
2712 if (Record *Xform = OpNode->getTransformFn()) {
2713 OpNode->setTransformFn(0);
2714 std::vector<TreePatternNode*> Children;
2715 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002716 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002717 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002718
Chris Lattner6cefb772008-01-05 22:25:12 +00002719 ResultNodeOperands.push_back(OpNode);
2720 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002721
Chris Lattner6cefb772008-01-05 22:25:12 +00002722 if (!InstInputsCheck.empty())
2723 I->error("Input operand $" + InstInputsCheck.begin()->first +
2724 " occurs in pattern but not in operands list!");
2725
2726 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002727 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2728 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002729 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002730 for (unsigned i = 0; i != NumResults; ++i)
2731 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002732
2733 // Create and insert the instruction.
Chris Lattneracfb70f2010-04-20 06:30:25 +00002734 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner62bcec82010-04-20 06:28:43 +00002735 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002736 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2737
2738 // Use a temporary tree pattern to infer all types and make sure that the
2739 // constructed result is correct. This depends on the instruction already
2740 // being inserted into the Instructions map.
2741 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002742 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002743
2744 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2745 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002746
Chris Lattner6cefb772008-01-05 22:25:12 +00002747 DEBUG(I->dump());
2748 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002749
Chris Lattner6cefb772008-01-05 22:25:12 +00002750 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002751 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2752 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002753 E = Instructions.end(); II != E; ++II) {
2754 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002755 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002756 if (I == 0) continue; // No pattern.
2757
2758 // FIXME: Assume only the first tree is the pattern. The others are clobber
2759 // nodes.
2760 TreePatternNode *Pattern = I->getTree(0);
2761 TreePatternNode *SrcPattern;
2762 if (Pattern->getOperator()->getName() == "set") {
2763 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2764 } else{
2765 // Not a set (store or something?)
2766 SrcPattern = Pattern;
2767 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002768
Chris Lattner6cefb772008-01-05 22:25:12 +00002769 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002770 AddPatternToMatch(I,
Jim Grosbach997759a2010-12-07 23:05:49 +00002771 PatternToMatch(Instr,
2772 Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002773 SrcPattern,
2774 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002775 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002776 Instr->getValueAsInt("AddedComplexity"),
2777 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002778 }
2779}
2780
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002781
2782typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2783
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002784static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002785 std::map<std::string, NameRecord> &Names,
2786 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002787 if (!P->getName().empty()) {
2788 NameRecord &Rec = Names[P->getName()];
2789 // If this is the first instance of the name, remember the node.
2790 if (Rec.second++ == 0)
2791 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002792 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002793 PatternTop->error("repetition of value: $" + P->getName() +
2794 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002795 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002796
Chris Lattner967d54a2010-02-23 06:35:45 +00002797 if (!P->isLeaf()) {
2798 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002799 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002800 }
2801}
2802
Chris Lattner25b6f912010-02-23 06:16:51 +00002803void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2804 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002805 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002806 std::string Reason;
2807 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002808 Pattern->error("Pattern can never match: " + Reason);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002809
Chris Lattner405f1252010-03-01 22:29:19 +00002810 // If the source pattern's root is a complex pattern, that complex pattern
2811 // must specify the nodes it can potentially match.
2812 if (const ComplexPattern *CP =
2813 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2814 if (CP->getRootNodes().empty())
2815 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2816 " could match");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002817
2818
Chris Lattner967d54a2010-02-23 06:35:45 +00002819 // Find all of the named values in the input and output, ensure they have the
2820 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002821 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002822 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2823 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002824
2825 // Scan all of the named values in the destination pattern, rejecting them if
2826 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002827 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002828 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002829 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002830 Pattern->error("Pattern has input without matching name in output: $" +
2831 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002832 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002833
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002834 // Scan all of the named values in the source pattern, rejecting them if the
2835 // name isn't used in the dest, and isn't used to tie two values together.
2836 for (std::map<std::string, NameRecord>::iterator
2837 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2838 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2839 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002840
Chris Lattner25b6f912010-02-23 06:16:51 +00002841 PatternsToMatch.push_back(PTM);
2842}
2843
2844
Dan Gohmanee4fa192008-04-03 00:02:49 +00002845
2846void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002847 const std::vector<const CodeGenInstruction*> &Instructions =
2848 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002849
2850 // First try to infer flags from the primary instruction pattern, if any.
2851 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002852 unsigned Errors = 0;
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002853 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2854 CodeGenInstruction &InstInfo =
2855 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesenccbe6032011-10-14 01:00:49 +00002856
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002857 // Treat neverHasSideEffects = 1 as the equivalent of hasSideEffects = 0.
2858 // This flag is obsolete and will be removed.
2859 if (InstInfo.neverHasSideEffects) {
2860 assert(!InstInfo.hasSideEffects);
2861 InstInfo.hasSideEffects_Unset = false;
2862 }
2863
2864 // Get the primary instruction pattern.
2865 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
2866 if (!Pattern) {
2867 if (InstInfo.hasUndefFlags())
2868 Revisit.push_back(&InstInfo);
2869 continue;
2870 }
2871 InstAnalyzer PatInfo(*this);
2872 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002873 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002874 }
2875
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00002876 // Second, look for single-instruction patterns defined outside the
2877 // instruction.
2878 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
2879 const PatternToMatch &PTM = *I;
2880
2881 // We can only infer from single-instruction patterns, otherwise we won't
2882 // know which instruction should get the flags.
2883 SmallVector<Record*, 8> PatInstrs;
2884 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
2885 if (PatInstrs.size() != 1)
2886 continue;
2887
2888 // Get the single instruction.
2889 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
2890
2891 // Only infer properties from the first pattern. We'll verify the others.
2892 if (InstInfo.InferredFrom)
2893 continue;
2894
2895 InstAnalyzer PatInfo(*this);
2896 PatInfo.Analyze(&PTM);
2897 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
2898 }
2899
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002900 if (Errors)
2901 throw "pattern conflicts";
2902
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002903 // Revisit instructions with undefined flags and no pattern.
2904 if (Target.guessInstructionProperties()) {
2905 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
2906 CodeGenInstruction &InstInfo = *Revisit[i];
2907 if (InstInfo.InferredFrom)
2908 continue;
2909 // The mayLoad and mayStore flags default to false.
2910 // Conservatively assume hasSideEffects if it wasn't explicit.
2911 if (InstInfo.hasSideEffects_Unset)
2912 InstInfo.hasSideEffects = true;
2913 }
2914 return;
2915 }
2916
2917 // Complain about any flags that are still undefined.
2918 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
2919 CodeGenInstruction &InstInfo = *Revisit[i];
2920 if (InstInfo.InferredFrom)
2921 continue;
2922 if (InstInfo.hasSideEffects_Unset)
2923 PrintError(InstInfo.TheDef->getLoc(),
2924 "Can't infer hasSideEffects from patterns");
2925 if (InstInfo.mayStore_Unset)
2926 PrintError(InstInfo.TheDef->getLoc(),
2927 "Can't infer mayStore from patterns");
2928 if (InstInfo.mayLoad_Unset)
2929 PrintError(InstInfo.TheDef->getLoc(),
2930 "Can't infer mayLoad from patterns");
Dan Gohmanee4fa192008-04-03 00:02:49 +00002931 }
2932}
2933
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00002934
2935/// Verify instruction flags against pattern node properties.
2936void CodeGenDAGPatterns::VerifyInstructionFlags() {
2937 unsigned Errors = 0;
2938 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
2939 const PatternToMatch &PTM = *I;
2940 SmallVector<Record*, 8> Instrs;
2941 getInstructionsInTree(PTM.getDstPattern(), Instrs);
2942 if (Instrs.empty())
2943 continue;
2944
2945 // Count the number of instructions with each flag set.
2946 unsigned NumSideEffects = 0;
2947 unsigned NumStores = 0;
2948 unsigned NumLoads = 0;
2949 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2950 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2951 NumSideEffects += InstInfo.hasSideEffects;
2952 NumStores += InstInfo.mayStore;
2953 NumLoads += InstInfo.mayLoad;
2954 }
2955
2956 // Analyze the source pattern.
2957 InstAnalyzer PatInfo(*this);
2958 PatInfo.Analyze(&PTM);
2959
2960 // Collect error messages.
2961 SmallVector<std::string, 4> Msgs;
2962
2963 // Check for missing flags in the output.
2964 // Permit extra flags for now at least.
2965 if (PatInfo.hasSideEffects && !NumSideEffects)
2966 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
2967
2968 // Don't verify store flags on instructions with side effects. At least for
2969 // intrinsics, side effects implies mayStore.
2970 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
2971 Msgs.push_back("pattern may store, but mayStore isn't set");
2972
2973 // Similarly, mayStore implies mayLoad on intrinsics.
2974 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
2975 Msgs.push_back("pattern may load, but mayLoad isn't set");
2976
2977 // Print error messages.
2978 if (Msgs.empty())
2979 continue;
2980 ++Errors;
2981
2982 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
2983 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
2984 (Instrs.size() == 1 ?
2985 "instruction" : "output instructions"));
2986 // Provide the location of the relevant instruction definitions.
2987 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2988 if (Instrs[i] != PTM.getSrcRecord())
2989 PrintError(Instrs[i]->getLoc(), "defined here");
2990 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2991 if (InstInfo.InferredFrom &&
2992 InstInfo.InferredFrom != InstInfo.TheDef &&
2993 InstInfo.InferredFrom != PTM.getSrcRecord())
2994 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
2995 }
2996 }
2997 if (Errors)
2998 throw "Errors in DAG patterns";
2999}
3000
Chris Lattner2cacec52010-03-15 06:00:16 +00003001/// Given a pattern result with an unresolved type, see if we can find one
3002/// instruction with an unresolved result type. Force this result type to an
3003/// arbitrary element if it's possible types to converge results.
3004static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3005 if (N->isLeaf())
3006 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003007
Chris Lattner2cacec52010-03-15 06:00:16 +00003008 // Analyze children.
3009 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3010 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3011 return true;
3012
3013 if (!N->getOperator()->isSubClassOf("Instruction"))
3014 return false;
3015
3016 // If this type is already concrete or completely unknown we can't do
3017 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00003018 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3019 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3020 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003021
Chris Lattnerd7349192010-03-19 21:37:09 +00003022 // Otherwise, force its type to the first possibility (an arbitrary choice).
3023 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3024 return true;
3025 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003026
Chris Lattnerd7349192010-03-19 21:37:09 +00003027 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00003028}
3029
Chris Lattnerfe718932008-01-06 01:10:31 +00003030void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00003031 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3032
3033 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00003034 Record *CurPattern = Patterns[i];
David Greene05bce0b2011-07-29 22:43:06 +00003035 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachd3e31212012-07-17 18:39:36 +00003036
3037 // If the pattern references the null_frag, there's nothing to do.
3038 if (hasNullFragReference(Tree))
3039 continue;
3040
Chris Lattner310adf12010-03-27 02:53:27 +00003041 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00003042
3043 // Inline pattern fragments into it.
3044 Pattern->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003045
David Greene05bce0b2011-07-29 22:43:06 +00003046 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00003047 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003048
Chris Lattner6cefb772008-01-05 22:25:12 +00003049 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00003050 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003051
Chris Lattner6cefb772008-01-05 22:25:12 +00003052 // Inline pattern fragments into it.
3053 Result->InlinePatternFragments();
3054
3055 if (Result->getNumTrees() != 1)
3056 Result->error("Cannot handle instructions producing instructions "
3057 "with temporaries yet!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003058
Chris Lattner6cefb772008-01-05 22:25:12 +00003059 bool IterateInference;
3060 bool InferredAllPatternTypes, InferredAllResultTypes;
3061 do {
3062 // Infer as many types as possible. If we cannot infer all of them, we
3063 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00003064 InferredAllPatternTypes =
3065 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003066
Chris Lattner6cefb772008-01-05 22:25:12 +00003067 // Infer as many types as possible. If we cannot infer all of them, we
3068 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00003069 InferredAllResultTypes =
3070 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00003071
Chris Lattner6c6ba362010-03-18 23:15:10 +00003072 IterateInference = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003073
Chris Lattner6cefb772008-01-05 22:25:12 +00003074 // Apply the type of the result to the source pattern. This helps us
3075 // resolve cases where the input type is known to be a pointer type (which
3076 // is considered resolved), but the result knows it needs to be 32- or
3077 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00003078 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
3079 Pattern->getTree(0)->getNumTypes());
3080 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00003081 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00003082 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00003083 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00003084 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00003085 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003086
Chris Lattner2cacec52010-03-15 06:00:16 +00003087 // If our iteration has converged and the input pattern's types are fully
3088 // resolved but the result pattern is not fully resolved, we may have a
3089 // situation where we have two instructions in the result pattern and
3090 // the instructions require a common register class, but don't care about
3091 // what actual MVT is used. This is actually a bug in our modelling:
3092 // output patterns should have register classes, not MVTs.
3093 //
3094 // In any case, to handle this, we just go through and disambiguate some
3095 // arbitrary types to the result pattern's nodes.
3096 if (!IterateInference && InferredAllPatternTypes &&
3097 !InferredAllResultTypes)
3098 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
3099 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00003100 } while (IterateInference);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003101
Chris Lattner6cefb772008-01-05 22:25:12 +00003102 // Verify that we inferred enough types that we can do something with the
3103 // pattern and result. If these fire the user has to add type casts.
3104 if (!InferredAllPatternTypes)
3105 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00003106 if (!InferredAllResultTypes) {
3107 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00003108 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00003109 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003110
Chris Lattner6cefb772008-01-05 22:25:12 +00003111 // Validate that the input pattern is correct.
3112 std::map<std::string, TreePatternNode*> InstInputs;
3113 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00003114 std::vector<Record*> InstImpResults;
3115 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3116 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3117 InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00003118 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00003119
3120 // Promote the xform function to be an explicit node if set.
3121 TreePatternNode *DstPattern = Result->getOnlyTree();
3122 std::vector<TreePatternNode*> ResultNodeOperands;
3123 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3124 TreePatternNode *OpNode = DstPattern->getChild(ii);
3125 if (Record *Xform = OpNode->getTransformFn()) {
3126 OpNode->setTransformFn(0);
3127 std::vector<TreePatternNode*> Children;
3128 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00003129 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00003130 }
3131 ResultNodeOperands.push_back(OpNode);
3132 }
3133 DstPattern = Result->getOnlyTree();
3134 if (!DstPattern->isLeaf())
3135 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00003136 ResultNodeOperands,
3137 DstPattern->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003138
Chris Lattnerd7349192010-03-19 21:37:09 +00003139 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
3140 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003141
Chris Lattner6cefb772008-01-05 22:25:12 +00003142 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
3143 Temp.InferAllTypes();
3144
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003145
Chris Lattner25b6f912010-02-23 06:16:51 +00003146 AddPatternToMatch(Pattern,
Jim Grosbach997759a2010-12-07 23:05:49 +00003147 PatternToMatch(CurPattern,
3148 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerd7349192010-03-19 21:37:09 +00003149 Pattern->getTree(0),
3150 Temp.getOnlyTree(), InstImpResults,
3151 CurPattern->getValueAsInt("AddedComplexity"),
3152 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003153 }
3154}
3155
3156/// CombineChildVariants - Given a bunch of permutations of each child of the
3157/// 'operator' node, put them together in all possible ways.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003158static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00003159 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3160 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003161 CodeGenDAGPatterns &CDP,
3162 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003163 // Make sure that each operand has at least one variant to choose from.
3164 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3165 if (ChildVariants[i].empty())
3166 return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003167
Chris Lattner6cefb772008-01-05 22:25:12 +00003168 // The end result is an all-pairs construction of the resultant pattern.
3169 std::vector<unsigned> Idxs;
3170 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00003171 bool NotDone;
3172 do {
3173#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00003174 DEBUG(if (!Idxs.empty()) {
3175 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3176 for (unsigned i = 0; i < Idxs.size(); ++i) {
3177 errs() << Idxs[i] << " ";
3178 }
3179 errs() << "]\n";
3180 });
Scott Michel327d0652008-03-05 17:49:05 +00003181#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00003182 // Create the variant and add it to the output list.
3183 std::vector<TreePatternNode*> NewChildren;
3184 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3185 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00003186 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3187 Orig->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003188
Chris Lattner6cefb772008-01-05 22:25:12 +00003189 // Copy over properties.
3190 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00003191 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00003192 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00003193 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3194 R->setType(i, Orig->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003195
Scott Michel327d0652008-03-05 17:49:05 +00003196 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00003197 std::string ErrString;
3198 if (!R->canPatternMatch(ErrString, CDP)) {
3199 delete R;
3200 } else {
3201 bool AlreadyExists = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003202
Chris Lattner6cefb772008-01-05 22:25:12 +00003203 // Scan to see if this pattern has already been emitted. We can get
3204 // duplication due to things like commuting:
3205 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3206 // which are the same pattern. Ignore the dups.
3207 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003208 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003209 AlreadyExists = true;
3210 break;
3211 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003212
Chris Lattner6cefb772008-01-05 22:25:12 +00003213 if (AlreadyExists)
3214 delete R;
3215 else
3216 OutVariants.push_back(R);
3217 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003218
Scott Michel327d0652008-03-05 17:49:05 +00003219 // Increment indices to the next permutation by incrementing the
3220 // indicies from last index backward, e.g., generate the sequence
3221 // [0, 0], [0, 1], [1, 0], [1, 1].
3222 int IdxsIdx;
3223 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3224 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3225 Idxs[IdxsIdx] = 0;
3226 else
Chris Lattner6cefb772008-01-05 22:25:12 +00003227 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00003228 }
Scott Michel327d0652008-03-05 17:49:05 +00003229 NotDone = (IdxsIdx >= 0);
3230 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00003231}
3232
3233/// CombineChildVariants - A helper function for binary operators.
3234///
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003235static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00003236 const std::vector<TreePatternNode*> &LHS,
3237 const std::vector<TreePatternNode*> &RHS,
3238 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003239 CodeGenDAGPatterns &CDP,
3240 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003241 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3242 ChildVariants.push_back(LHS);
3243 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00003244 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003245}
Chris Lattner6cefb772008-01-05 22:25:12 +00003246
3247
3248static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3249 std::vector<TreePatternNode *> &Children) {
3250 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3251 Record *Operator = N->getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003252
Chris Lattner6cefb772008-01-05 22:25:12 +00003253 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00003254 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00003255 N->getTransformFn()) {
3256 Children.push_back(N);
3257 return;
3258 }
3259
3260 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3261 Children.push_back(N->getChild(0));
3262 else
3263 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3264
3265 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3266 Children.push_back(N->getChild(1));
3267 else
3268 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3269}
3270
3271/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3272/// the (potentially recursive) pattern by using algebraic laws.
3273///
3274static void GenerateVariantsOf(TreePatternNode *N,
3275 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003276 CodeGenDAGPatterns &CDP,
3277 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003278 // We cannot permute leaves.
3279 if (N->isLeaf()) {
3280 OutVariants.push_back(N);
3281 return;
3282 }
3283
3284 // Look up interesting info about the node.
3285 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3286
Jim Grosbachda4231f2009-03-26 16:17:51 +00003287 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00003288 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003289 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00003290 std::vector<TreePatternNode*> MaximalChildren;
3291 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3292
3293 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3294 // permutations.
3295 if (MaximalChildren.size() == 3) {
3296 // Find the variants of all of our maximal children.
3297 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003298 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3299 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3300 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003301
Chris Lattner6cefb772008-01-05 22:25:12 +00003302 // There are only two ways we can permute the tree:
3303 // (A op B) op C and A op (B op C)
3304 // Within these forms, we can also permute A/B/C.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003305
Chris Lattner6cefb772008-01-05 22:25:12 +00003306 // Generate legal pair permutations of A/B/C.
3307 std::vector<TreePatternNode*> ABVariants;
3308 std::vector<TreePatternNode*> BAVariants;
3309 std::vector<TreePatternNode*> ACVariants;
3310 std::vector<TreePatternNode*> CAVariants;
3311 std::vector<TreePatternNode*> BCVariants;
3312 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003313 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3314 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3315 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3316 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3317 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3318 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003319
3320 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00003321 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3322 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3323 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3324 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3325 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3326 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003327
3328 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00003329 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3330 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3331 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3332 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3333 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3334 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003335 return;
3336 }
3337 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003338
Chris Lattner6cefb772008-01-05 22:25:12 +00003339 // Compute permutations of all children.
3340 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3341 ChildVariants.resize(N->getNumChildren());
3342 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003343 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003344
3345 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00003346 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003347
3348 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003349 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3350 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3351 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3352 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003353 // Don't count children which are actually register references.
3354 unsigned NC = 0;
3355 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3356 TreePatternNode *Child = N->getChild(i);
3357 if (Child->isLeaf())
David Greene05bce0b2011-07-29 22:43:06 +00003358 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003359 Record *RR = DI->getDef();
3360 if (RR->isSubClassOf("Register"))
3361 continue;
3362 }
3363 NC++;
3364 }
3365 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003366 if (isCommIntrinsic) {
3367 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3368 // operands are the commutative operands, and there might be more operands
3369 // after those.
3370 assert(NC >= 3 &&
3371 "Commutative intrinsic should have at least 3 childrean!");
3372 std::vector<std::vector<TreePatternNode*> > Variants;
3373 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3374 Variants.push_back(ChildVariants[2]);
3375 Variants.push_back(ChildVariants[1]);
3376 for (unsigned i = 3; i != NC; ++i)
3377 Variants.push_back(ChildVariants[i]);
3378 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3379 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00003380 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00003381 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003382 }
3383}
3384
3385
3386// GenerateVariants - Generate variants. For example, commutative patterns can
3387// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00003388void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00003389 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003390
Chris Lattner6cefb772008-01-05 22:25:12 +00003391 // Loop over all of the patterns we've collected, checking to see if we can
3392 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00003393 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00003394 // the .td file having to contain tons of variants of instructions.
3395 //
3396 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3397 // intentionally do not reconsider these. Any variants of added patterns have
3398 // already been added.
3399 //
3400 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00003401 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00003402 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00003403 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00003404 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00003405 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00003406 DEBUG(errs() << "\n");
Jim Grosbachbb168242010-10-08 18:13:57 +00003407 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3408 DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003409
3410 assert(!Variants.empty() && "Must create at least original variant!");
3411 Variants.erase(Variants.begin()); // Remove the original pattern.
3412
3413 if (Variants.empty()) // No variants for this pattern.
3414 continue;
3415
Chris Lattner569f1212009-08-23 04:44:11 +00003416 DEBUG(errs() << "FOUND VARIANTS OF: ";
3417 PatternsToMatch[i].getSrcPattern()->dump();
3418 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003419
3420 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3421 TreePatternNode *Variant = Variants[v];
3422
Chris Lattner569f1212009-08-23 04:44:11 +00003423 DEBUG(errs() << " VAR#" << v << ": ";
3424 Variant->dump();
3425 errs() << "\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003426
Chris Lattner6cefb772008-01-05 22:25:12 +00003427 // Scan to see if an instruction or explicit pattern already matches this.
3428 bool AlreadyExists = false;
3429 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00003430 // Skip if the top level predicates do not match.
3431 if (PatternsToMatch[i].getPredicates() !=
3432 PatternsToMatch[p].getPredicates())
3433 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00003434 // Check to see if this variant already exists.
Jim Grosbachbb168242010-10-08 18:13:57 +00003435 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3436 DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00003437 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003438 AlreadyExists = true;
3439 break;
3440 }
3441 }
3442 // If we already have it, ignore the variant.
3443 if (AlreadyExists) continue;
3444
3445 // Otherwise, add it to the list of patterns we have.
3446 PatternsToMatch.
Jim Grosbach997759a2010-12-07 23:05:49 +00003447 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3448 PatternsToMatch[i].getPredicates(),
Chris Lattner6cefb772008-01-05 22:25:12 +00003449 Variant, PatternsToMatch[i].getDstPattern(),
3450 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00003451 PatternsToMatch[i].getAddedComplexity(),
3452 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003453 }
3454
Chris Lattner569f1212009-08-23 04:44:11 +00003455 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003456 }
3457}