blob: a08cde60fb2a9e2451ccc77634dc69a4dc3a8dd0 [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner6cefb772008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfe718932008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner93c7e412008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
Chris Lattner2cacec52010-03-15 06:00:16 +000018#include "llvm/ADT/STLExtras.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include "llvm/Support/Debug.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000020#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000021#include <algorithm>
Chris Lattner6cefb772008-01-05 22:25:12 +000022using namespace llvm;
23
24//===----------------------------------------------------------------------===//
Chris Lattner2cacec52010-03-15 06:00:16 +000025// EEVT::TypeSet Implementation
26//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +000027
Owen Anderson825b72b2009-08-11 20:47:22 +000028static inline bool isInteger(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000029 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000030}
Owen Anderson825b72b2009-08-11 20:47:22 +000031static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000032 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000033}
Owen Anderson825b72b2009-08-11 20:47:22 +000034static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000035 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000036}
Chris Lattner774ce292010-03-19 17:41:26 +000037static inline bool isScalar(MVT::SimpleValueType VT) {
38 return !EVT(VT).isVector();
39}
Duncan Sands83ec4b62008-06-06 12:08:01 +000040
Chris Lattner2cacec52010-03-15 06:00:16 +000041EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
42 if (VT == MVT::iAny)
43 EnforceInteger(TP);
44 else if (VT == MVT::fAny)
45 EnforceFloatingPoint(TP);
46 else if (VT == MVT::vAny)
47 EnforceVector(TP);
48 else {
49 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
50 VT == MVT::iPTRAny) && "Not a concrete type!");
51 TypeVec.push_back(VT);
52 }
Chris Lattner6cefb772008-01-05 22:25:12 +000053}
54
Chris Lattner2cacec52010-03-15 06:00:16 +000055
56EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
57 assert(!VTList.empty() && "empty list?");
58 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000059
Chris Lattner2cacec52010-03-15 06:00:16 +000060 if (!VTList.empty())
61 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62 VTList[0] != MVT::fAny);
Jim Grosbachfbadcd02010-12-21 16:16:00 +000063
Chris Lattner0d7952e2010-03-27 20:32:26 +000064 // Verify no duplicates.
Chris Lattner2cacec52010-03-15 06:00:16 +000065 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner0d7952e2010-03-27 20:32:26 +000066 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner6cefb772008-01-05 22:25:12 +000067}
68
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000069/// FillWithPossibleTypes - Set to all legal types and return true, only valid
70/// on completely unknown type sets.
Chris Lattner774ce292010-03-19 17:41:26 +000071bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
72 bool (*Pred)(MVT::SimpleValueType),
73 const char *PredicateName) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000074 assert(isCompletelyUnknown());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000075 const std::vector<MVT::SimpleValueType> &LegalTypes =
Chris Lattner774ce292010-03-19 17:41:26 +000076 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +000077
Chris Lattner774ce292010-03-19 17:41:26 +000078 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
79 if (Pred == 0 || Pred(LegalTypes[i]))
80 TypeVec.push_back(LegalTypes[i]);
81
82 // If we have nothing that matches the predicate, bail out.
83 if (TypeVec.empty())
84 TP.error("Type inference contradiction found, no " +
Jim Grosbachfbadcd02010-12-21 16:16:00 +000085 std::string(PredicateName) + " types found");
Chris Lattner774ce292010-03-19 17:41:26 +000086 // No need to sort with one element.
87 if (TypeVec.size() == 1) return true;
88
89 // Remove duplicates.
90 array_pod_sort(TypeVec.begin(), TypeVec.end());
91 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000092
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000093 return true;
94}
Chris Lattner2cacec52010-03-15 06:00:16 +000095
96/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
97/// integer value type.
98bool EEVT::TypeSet::hasIntegerTypes() const {
99 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
100 if (isInteger(TypeVec[i]))
101 return true;
102 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000103}
Chris Lattner2cacec52010-03-15 06:00:16 +0000104
105/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
106/// a floating point value type.
107bool EEVT::TypeSet::hasFloatingPointTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isFloatingPoint(TypeVec[i]))
110 return true;
111 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000112}
Chris Lattner2cacec52010-03-15 06:00:16 +0000113
114/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
115/// value type.
116bool EEVT::TypeSet::hasVectorTypes() const {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isVector(TypeVec[i]))
119 return true;
120 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +0000121}
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000122
Chris Lattner2cacec52010-03-15 06:00:16 +0000123
124std::string EEVT::TypeSet::getName() const {
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000125 if (TypeVec.empty()) return "<empty>";
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000126
Chris Lattner2cacec52010-03-15 06:00:16 +0000127 std::string Result;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000128
Chris Lattner2cacec52010-03-15 06:00:16 +0000129 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
130 std::string VTName = llvm::getEnumName(TypeVec[i]);
131 // Strip off MVT:: prefix if present.
132 if (VTName.substr(0,5) == "MVT::")
133 VTName = VTName.substr(5);
134 if (i) Result += ':';
135 Result += VTName;
136 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000137
Chris Lattner2cacec52010-03-15 06:00:16 +0000138 if (TypeVec.size() == 1)
139 return Result;
140 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000141}
Chris Lattner2cacec52010-03-15 06:00:16 +0000142
143/// MergeInTypeInfo - This merges in type information from the specified
144/// argument. If 'this' changes, it returns true. If the two types are
145/// contradictory (e.g. merge f32 into i32) then this throws an exception.
146bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
147 if (InVT.isCompletelyUnknown() || *this == InVT)
148 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000149
Chris Lattner2cacec52010-03-15 06:00:16 +0000150 if (isCompletelyUnknown()) {
151 *this = InVT;
152 return true;
153 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000154
Chris Lattner2cacec52010-03-15 06:00:16 +0000155 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000156
Chris Lattner2cacec52010-03-15 06:00:16 +0000157 // Handle the abstract cases, seeing if we can resolve them better.
158 switch (TypeVec[0]) {
159 default: break;
160 case MVT::iPTR:
161 case MVT::iPTRAny:
162 if (InVT.hasIntegerTypes()) {
163 EEVT::TypeSet InCopy(InVT);
164 InCopy.EnforceInteger(TP);
165 InCopy.EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000166
Chris Lattner2cacec52010-03-15 06:00:16 +0000167 if (InCopy.isConcrete()) {
168 // If the RHS has one integer type, upgrade iPTR to i32.
169 TypeVec[0] = InVT.TypeVec[0];
170 return true;
171 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000172
Chris Lattner2cacec52010-03-15 06:00:16 +0000173 // If the input has multiple scalar integers, this doesn't add any info.
174 if (!InCopy.isCompletelyUnknown())
175 return false;
176 }
177 break;
178 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000179
Chris Lattner2cacec52010-03-15 06:00:16 +0000180 // If the input constraint is iAny/iPTR and this is an integer type list,
181 // remove non-integer types from the list.
182 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
183 hasIntegerTypes()) {
184 bool MadeChange = EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000185
Chris Lattner2cacec52010-03-15 06:00:16 +0000186 // If we're merging in iPTR/iPTRAny and the node currently has a list of
187 // multiple different integer types, replace them with a single iPTR.
188 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
189 TypeVec.size() != 1) {
190 TypeVec.resize(1);
191 TypeVec[0] = InVT.TypeVec[0];
192 MadeChange = true;
193 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000194
Chris Lattner2cacec52010-03-15 06:00:16 +0000195 return MadeChange;
196 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000197
Chris Lattner2cacec52010-03-15 06:00:16 +0000198 // If this is a type list and the RHS is a typelist as well, eliminate entries
199 // from this list that aren't in the other one.
200 bool MadeChange = false;
201 TypeSet InputSet(*this);
202
203 for (unsigned i = 0; i != TypeVec.size(); ++i) {
204 bool InInVT = false;
205 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
206 if (TypeVec[i] == InVT.TypeVec[j]) {
207 InInVT = true;
208 break;
209 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000210
Chris Lattner2cacec52010-03-15 06:00:16 +0000211 if (InInVT) continue;
212 TypeVec.erase(TypeVec.begin()+i--);
213 MadeChange = true;
214 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000215
Chris Lattner2cacec52010-03-15 06:00:16 +0000216 // If we removed all of our types, we have a type contradiction.
217 if (!TypeVec.empty())
218 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000219
Chris Lattner2cacec52010-03-15 06:00:16 +0000220 // FIXME: Really want an SMLoc here!
221 TP.error("Type inference contradiction found, merging '" +
222 InVT.getName() + "' into '" + InputSet.getName() + "'");
223 return true; // unreachable
224}
225
226/// EnforceInteger - Remove all non-integer types from this set.
227bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000228 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000229 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000230 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattner2cacec52010-03-15 06:00:16 +0000231 if (!hasFloatingPointTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000232 return false;
233
234 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000235
Chris Lattner2cacec52010-03-15 06:00:16 +0000236 // Filter out all the fp types.
237 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000238 if (!isInteger(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000239 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000240
Chris Lattner2cacec52010-03-15 06:00:16 +0000241 if (TypeVec.empty())
242 TP.error("Type inference contradiction found, '" +
243 InputSet.getName() + "' needs to be integer");
Chris Lattner774ce292010-03-19 17:41:26 +0000244 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000245}
246
247/// EnforceFloatingPoint - Remove all integer types from this set.
248bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000249 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000250 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000251 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
252
Chris Lattner2cacec52010-03-15 06:00:16 +0000253 if (!hasIntegerTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000254 return false;
255
256 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000257
Chris Lattner2cacec52010-03-15 06:00:16 +0000258 // Filter out all the fp types.
259 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000260 if (!isFloatingPoint(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000261 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000262
Chris Lattner2cacec52010-03-15 06:00:16 +0000263 if (TypeVec.empty())
264 TP.error("Type inference contradiction found, '" +
265 InputSet.getName() + "' needs to be floating point");
Chris Lattner774ce292010-03-19 17:41:26 +0000266 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000267}
268
269/// EnforceScalar - Remove all vector types from this.
270bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000271 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000272 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000273 return FillWithPossibleTypes(TP, isScalar, "scalar");
274
Chris Lattner2cacec52010-03-15 06:00:16 +0000275 if (!hasVectorTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000276 return false;
277
278 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000279
Chris Lattner2cacec52010-03-15 06:00:16 +0000280 // Filter out all the vector types.
281 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000282 if (!isScalar(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000283 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000284
Chris Lattner2cacec52010-03-15 06:00:16 +0000285 if (TypeVec.empty())
286 TP.error("Type inference contradiction found, '" +
287 InputSet.getName() + "' needs to be scalar");
Chris Lattner774ce292010-03-19 17:41:26 +0000288 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000289}
290
291/// EnforceVector - Remove all vector types from this.
292bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Chris Lattner774ce292010-03-19 17:41:26 +0000293 // If we know nothing, then get the full set.
294 if (TypeVec.empty())
295 return FillWithPossibleTypes(TP, isVector, "vector");
296
Chris Lattner2cacec52010-03-15 06:00:16 +0000297 TypeSet InputSet(*this);
298 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000299
Chris Lattner2cacec52010-03-15 06:00:16 +0000300 // Filter out all the scalar types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000302 if (!isVector(TypeVec[i])) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000303 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner774ce292010-03-19 17:41:26 +0000304 MadeChange = true;
305 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000306
Chris Lattner2cacec52010-03-15 06:00:16 +0000307 if (TypeVec.empty())
308 TP.error("Type inference contradiction found, '" +
309 InputSet.getName() + "' needs to be a vector");
310 return MadeChange;
311}
312
313
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000314
Chris Lattner2cacec52010-03-15 06:00:16 +0000315/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
316/// this an other based on this information.
317bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
318 // Both operands must be integer or FP, but we don't care which.
319 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000320
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000321 if (isCompletelyUnknown())
322 MadeChange = FillWithPossibleTypes(TP);
323
324 if (Other.isCompletelyUnknown())
325 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000326
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000327 // If one side is known to be integer or known to be FP but the other side has
328 // no information, get at least the type integrality info in there.
329 if (!hasFloatingPointTypes())
330 MadeChange |= Other.EnforceInteger(TP);
331 else if (!hasIntegerTypes())
332 MadeChange |= Other.EnforceFloatingPoint(TP);
333 if (!Other.hasFloatingPointTypes())
334 MadeChange |= EnforceInteger(TP);
335 else if (!Other.hasIntegerTypes())
336 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000337
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000338 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339 "Should have a type list now");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000340
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000341 // If one contains vectors but the other doesn't pull vectors out.
342 if (!hasVectorTypes())
343 MadeChange |= Other.EnforceScalar(TP);
344 if (!hasVectorTypes())
345 MadeChange |= EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000346
David Greene9d7f0112011-02-01 19:12:32 +0000347 if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
348 // If we are down to concrete types, this code does not currently
349 // handle nodes which have multiple types, where some types are
350 // integer, and some are fp. Assert that this is not the case.
351 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
352 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
353 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
354
355 // Otherwise, if these are both vector types, either this vector
356 // must have a larger bitsize than the other, or this element type
357 // must be larger than the other.
358 EVT Type(TypeVec[0]);
359 EVT OtherType(Other.TypeVec[0]);
360
361 if (hasVectorTypes() && Other.hasVectorTypes()) {
362 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
363 if (Type.getVectorElementType().getSizeInBits()
364 >= OtherType.getVectorElementType().getSizeInBits())
365 TP.error("Type inference contradiction found, '" +
366 getName() + "' element type not smaller than '" +
367 Other.getName() +"'!");
368 }
369 else
370 // For scalar types, the bitsize of this type must be larger
371 // than that of the other.
372 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
373 TP.error("Type inference contradiction found, '" +
374 getName() + "' is not smaller than '" +
375 Other.getName() +"'!");
376
377 }
378
379
380 // Handle int and fp as disjoint sets. This won't work for patterns
381 // that have mixed fp/int types but those are likely rare and would
382 // not have been accepted by this code previously.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000383
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000384 // Okay, find the smallest type from the current set and remove it from the
385 // largest set.
David Greenec83e2032011-02-04 17:01:53 +0000386 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000387 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
388 if (isInteger(TypeVec[i])) {
389 SmallestInt = TypeVec[i];
390 break;
391 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000392 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000393 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
394 SmallestInt = TypeVec[i];
395
David Greenec83e2032011-02-04 17:01:53 +0000396 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000397 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
398 if (isFloatingPoint(TypeVec[i])) {
399 SmallestFP = TypeVec[i];
400 break;
401 }
402 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
403 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
404 SmallestFP = TypeVec[i];
405
406 int OtherIntSize = 0;
407 int OtherFPSize = 0;
408 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
409 Other.TypeVec.begin();
410 TVI != Other.TypeVec.end();
411 /* NULL */) {
412 if (isInteger(*TVI)) {
413 ++OtherIntSize;
414 if (*TVI == SmallestInt) {
415 TVI = Other.TypeVec.erase(TVI);
416 --OtherIntSize;
417 MadeChange = true;
418 continue;
419 }
420 }
421 else if (isFloatingPoint(*TVI)) {
422 ++OtherFPSize;
423 if (*TVI == SmallestFP) {
424 TVI = Other.TypeVec.erase(TVI);
425 --OtherFPSize;
426 MadeChange = true;
427 continue;
428 }
429 }
430 ++TVI;
431 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000432
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000433 // If this is the only type in the large set, the constraint can never be
434 // satisfied.
David Greene9d7f0112011-02-01 19:12:32 +0000435 if ((Other.hasIntegerTypes() && OtherIntSize == 0)
436 || (Other.hasFloatingPointTypes() && OtherFPSize == 0))
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000437 TP.error("Type inference contradiction found, '" +
438 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000439
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000440 // Okay, find the largest type in the Other set and remove it from the
441 // current set.
David Greenec83e2032011-02-04 17:01:53 +0000442 MVT::SimpleValueType LargestInt = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000443 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
444 if (isInteger(Other.TypeVec[i])) {
445 LargestInt = Other.TypeVec[i];
446 break;
447 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000448 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000449 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
450 LargestInt = Other.TypeVec[i];
451
David Greenec83e2032011-02-04 17:01:53 +0000452 MVT::SimpleValueType LargestFP = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000453 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
454 if (isFloatingPoint(Other.TypeVec[i])) {
455 LargestFP = Other.TypeVec[i];
456 break;
457 }
458 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
459 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
460 LargestFP = Other.TypeVec[i];
461
462 int IntSize = 0;
463 int FPSize = 0;
464 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
465 TypeVec.begin();
466 TVI != TypeVec.end();
467 /* NULL */) {
468 if (isInteger(*TVI)) {
469 ++IntSize;
470 if (*TVI == LargestInt) {
471 TVI = TypeVec.erase(TVI);
472 --IntSize;
473 MadeChange = true;
474 continue;
475 }
476 }
477 else if (isFloatingPoint(*TVI)) {
478 ++FPSize;
479 if (*TVI == LargestFP) {
480 TVI = TypeVec.erase(TVI);
481 --FPSize;
482 MadeChange = true;
483 continue;
484 }
485 }
486 ++TVI;
487 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000488
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000489 // If this is the only type in the small set, the constraint can never be
490 // satisfied.
David Greene9d7f0112011-02-01 19:12:32 +0000491 if ((hasIntegerTypes() && IntSize == 0)
492 || (hasFloatingPointTypes() && FPSize == 0))
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000493 TP.error("Type inference contradiction found, '" +
494 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000495
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000496 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000497}
498
499/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner66fb9d22010-03-24 00:01:16 +0000500/// whose element is specified by VTOperand.
501bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattner2cacec52010-03-15 06:00:16 +0000502 TreePattern &TP) {
Chris Lattner66fb9d22010-03-24 00:01:16 +0000503 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattner2cacec52010-03-15 06:00:16 +0000504 bool MadeChange = false;
Chris Lattner66fb9d22010-03-24 00:01:16 +0000505 MadeChange |= EnforceVector(TP);
506 MadeChange |= VTOperand.EnforceScalar(TP);
507
508 // If we know the vector type, it forces the scalar to agree.
509 if (isConcrete()) {
510 EVT IVT = getConcrete();
511 IVT = IVT.getVectorElementType();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000512 return MadeChange |
Chris Lattner66fb9d22010-03-24 00:01:16 +0000513 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
514 }
515
516 // If the scalar type is known, filter out vector types whose element types
517 // disagree.
518 if (!VTOperand.isConcrete())
519 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000520
Chris Lattner66fb9d22010-03-24 00:01:16 +0000521 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000522
Chris Lattner66fb9d22010-03-24 00:01:16 +0000523 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000524
Chris Lattner66fb9d22010-03-24 00:01:16 +0000525 // Filter out all the types which don't have the right element type.
526 for (unsigned i = 0; i != TypeVec.size(); ++i) {
527 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
528 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000529 TypeVec.erase(TypeVec.begin()+i--);
530 MadeChange = true;
531 }
Chris Lattner66fb9d22010-03-24 00:01:16 +0000532 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000533
Chris Lattner2cacec52010-03-15 06:00:16 +0000534 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
535 TP.error("Type inference contradiction found, forcing '" +
536 InputSet.getName() + "' to have a vector element");
537 return MadeChange;
538}
539
David Greene60322692011-01-24 20:53:18 +0000540/// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
541/// vector type specified by VTOperand.
542bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
543 TreePattern &TP) {
544 // "This" must be a vector and "VTOperand" must be a vector.
545 bool MadeChange = false;
546 MadeChange |= EnforceVector(TP);
547 MadeChange |= VTOperand.EnforceVector(TP);
548
549 // "This" must be larger than "VTOperand."
550 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
551
552 // If we know the vector type, it forces the scalar types to agree.
553 if (isConcrete()) {
554 EVT IVT = getConcrete();
555 IVT = IVT.getVectorElementType();
556
557 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
558 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
559 } else if (VTOperand.isConcrete()) {
560 EVT IVT = VTOperand.getConcrete();
561 IVT = IVT.getVectorElementType();
562
563 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
564 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
565 }
566
567 return MadeChange;
568}
569
Chris Lattner2cacec52010-03-15 06:00:16 +0000570//===----------------------------------------------------------------------===//
571// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000572
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000573bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
574 return LHS->getID() < RHS->getID();
575}
Scott Michel327d0652008-03-05 17:49:05 +0000576
577/// Dependent variable map for CodeGenDAGPattern variant generation
578typedef std::map<std::string, int> DepVarMap;
579
580/// Const iterator shorthand for DepVarMap
581typedef DepVarMap::const_iterator DepVarMap_citer;
582
Chris Lattner54379062011-04-17 21:38:24 +0000583static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel327d0652008-03-05 17:49:05 +0000584 if (N->isLeaf()) {
Chris Lattner54379062011-04-17 21:38:24 +0000585 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL)
Scott Michel327d0652008-03-05 17:49:05 +0000586 DepMap[N->getName()]++;
Scott Michel327d0652008-03-05 17:49:05 +0000587 } else {
588 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
589 FindDepVarsOf(N->getChild(i), DepMap);
590 }
591}
Chris Lattner54379062011-04-17 21:38:24 +0000592
593/// Find dependent variables within child patterns
594static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000595 DepVarMap depcounts;
596 FindDepVarsOf(N, depcounts);
597 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner54379062011-04-17 21:38:24 +0000598 if (i->second > 1) // std::pair<std::string, int>
Scott Michel327d0652008-03-05 17:49:05 +0000599 DepVars.insert(i->first);
Scott Michel327d0652008-03-05 17:49:05 +0000600 }
601}
602
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000603#ifndef NDEBUG
Chris Lattner54379062011-04-17 21:38:24 +0000604/// Dump the dependent variable set:
605static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000606 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000607 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000608 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000609 DEBUG(errs() << "[ ");
Jim Grosbachbb168242010-10-08 18:13:57 +0000610 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
611 e = DepVars.end(); i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000612 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000613 }
Chris Lattner569f1212009-08-23 04:44:11 +0000614 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000615 }
616}
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000617#endif
618
Chris Lattner54379062011-04-17 21:38:24 +0000619
620//===----------------------------------------------------------------------===//
621// TreePredicateFn Implementation
622//===----------------------------------------------------------------------===//
623
Chris Lattner7ed13912011-04-17 22:05:17 +0000624/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
625TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
626 assert((getPredCode().empty() || getImmCode().empty()) &&
627 ".td file corrupt: can't have a node predicate *and* an imm predicate");
628}
629
Chris Lattner54379062011-04-17 21:38:24 +0000630std::string TreePredicateFn::getPredCode() const {
631 return PatFragRec->getRecord()->getValueAsCode("PredicateCode");
632}
633
Chris Lattner7ed13912011-04-17 22:05:17 +0000634std::string TreePredicateFn::getImmCode() const {
635 return PatFragRec->getRecord()->getValueAsCode("ImmediateCode");
636}
637
Chris Lattner54379062011-04-17 21:38:24 +0000638
639/// isAlwaysTrue - Return true if this is a noop predicate.
640bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000641 return getPredCode().empty() && getImmCode().empty();
Chris Lattner54379062011-04-17 21:38:24 +0000642}
643
644/// Return the name to use in the generated code to reference this, this is
645/// "Predicate_foo" if from a pattern fragment "foo".
646std::string TreePredicateFn::getFnName() const {
647 return "Predicate_" + PatFragRec->getRecord()->getName();
648}
649
650/// getCodeToRunOnSDNode - Return the code for the function body that
651/// evaluates this predicate. The argument is expected to be in "Node",
652/// not N. This handles casting and conversion to a concrete node type as
653/// appropriate.
654std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000655 // Handle immediate predicates first.
656 std::string ImmCode = getImmCode();
657 if (!ImmCode.empty()) {
658 std::string Result =
659 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner7ed13912011-04-17 22:05:17 +0000660 return Result + ImmCode;
661 }
662
663 // Handle arbitrary node predicates.
664 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner54379062011-04-17 21:38:24 +0000665 std::string ClassName;
666 if (PatFragRec->getOnlyTree()->isLeaf())
667 ClassName = "SDNode";
668 else {
669 Record *Op = PatFragRec->getOnlyTree()->getOperator();
670 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
671 }
672 std::string Result;
673 if (ClassName == "SDNode")
674 Result = " SDNode *N = Node;\n";
675 else
676 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
677
678 return Result + getPredCode();
Scott Michel327d0652008-03-05 17:49:05 +0000679}
680
Chris Lattner6cefb772008-01-05 22:25:12 +0000681//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000682// PatternToMatch implementation
683//
684
Chris Lattner48e86db2010-03-29 01:40:38 +0000685
686/// getPatternSize - Return the 'size' of this pattern. We want to match large
687/// patterns before small ones. This is used to determine the size of a
688/// pattern.
689static unsigned getPatternSize(const TreePatternNode *P,
690 const CodeGenDAGPatterns &CGP) {
691 unsigned Size = 3; // The node itself.
692 // If the root node is a ConstantSDNode, increases its size.
693 // e.g. (set R32:$dst, 0).
694 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
695 Size += 2;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000696
Chris Lattner48e86db2010-03-29 01:40:38 +0000697 // FIXME: This is a hack to statically increase the priority of patterns
698 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
699 // Later we can allow complexity / cost for each pattern to be (optionally)
700 // specified. To get best possible pattern match we'll need to dynamically
701 // calculate the complexity of all patterns a dag can potentially map to.
702 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
703 if (AM)
704 Size += AM->getNumOperands() * 3;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000705
Chris Lattner48e86db2010-03-29 01:40:38 +0000706 // If this node has some predicate function that must match, it adds to the
707 // complexity of this node.
708 if (!P->getPredicateFns().empty())
709 ++Size;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000710
Chris Lattner48e86db2010-03-29 01:40:38 +0000711 // Count children in the count if they are also nodes.
712 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
713 TreePatternNode *Child = P->getChild(i);
714 if (!Child->isLeaf() && Child->getNumTypes() &&
715 Child->getType(0) != MVT::Other)
716 Size += getPatternSize(Child, CGP);
717 else if (Child->isLeaf()) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000718 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000719 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
720 else if (Child->getComplexPatternInfo(CGP))
721 Size += getPatternSize(Child, CGP);
722 else if (!Child->getPredicateFns().empty())
723 ++Size;
724 }
725 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000726
Chris Lattner48e86db2010-03-29 01:40:38 +0000727 return Size;
728}
729
730/// Compute the complexity metric for the input pattern. This roughly
731/// corresponds to the number of nodes that are covered.
732unsigned PatternToMatch::
733getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
734 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
735}
736
737
Dan Gohman22bb3112008-08-22 00:20:26 +0000738/// getPredicateCheck - Return a single string containing all of this
739/// pattern's predicates concatenated with "&&" operators.
740///
741std::string PatternToMatch::getPredicateCheck() const {
742 std::string PredicateCheck;
743 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
744 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
745 Record *Def = Pred->getDef();
746 if (!Def->isSubClassOf("Predicate")) {
747#ifndef NDEBUG
748 Def->dump();
749#endif
750 assert(0 && "Unknown predicate type!");
751 }
752 if (!PredicateCheck.empty())
753 PredicateCheck += " && ";
754 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
755 }
756 }
757
758 return PredicateCheck;
759}
760
761//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000762// SDTypeConstraint implementation
763//
764
765SDTypeConstraint::SDTypeConstraint(Record *R) {
766 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000767
Chris Lattner6cefb772008-01-05 22:25:12 +0000768 if (R->isSubClassOf("SDTCisVT")) {
769 ConstraintType = SDTCisVT;
770 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerc8122612010-03-28 06:04:39 +0000771 if (x.SDTCisVT_Info.VT == MVT::isVoid)
772 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000773
Chris Lattner6cefb772008-01-05 22:25:12 +0000774 } else if (R->isSubClassOf("SDTCisPtrTy")) {
775 ConstraintType = SDTCisPtrTy;
776 } else if (R->isSubClassOf("SDTCisInt")) {
777 ConstraintType = SDTCisInt;
778 } else if (R->isSubClassOf("SDTCisFP")) {
779 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000780 } else if (R->isSubClassOf("SDTCisVec")) {
781 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000782 } else if (R->isSubClassOf("SDTCisSameAs")) {
783 ConstraintType = SDTCisSameAs;
784 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
785 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
786 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000787 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000788 R->getValueAsInt("OtherOperandNum");
789 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
790 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000791 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000792 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000793 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
794 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000795 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene60322692011-01-24 20:53:18 +0000796 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
797 ConstraintType = SDTCisSubVecOfVec;
798 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
799 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000800 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000801 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000802 exit(1);
803 }
804}
805
806/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000807/// N, and the result number in ResNo.
808static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
809 const SDNodeInfo &NodeInfo,
810 unsigned &ResNo) {
811 unsigned NumResults = NodeInfo.getNumResults();
812 if (OpNo < NumResults) {
813 ResNo = OpNo;
814 return N;
815 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000816
Chris Lattner2e68a022010-03-19 21:56:21 +0000817 OpNo -= NumResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000818
Chris Lattner2e68a022010-03-19 21:56:21 +0000819 if (OpNo >= N->getNumChildren()) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000820 errs() << "Invalid operand number in type constraint "
Chris Lattner2e68a022010-03-19 21:56:21 +0000821 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000822 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000823 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000824 exit(1);
825 }
826
Chris Lattner2e68a022010-03-19 21:56:21 +0000827 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000828}
829
830/// ApplyTypeConstraint - Given a node in a pattern, apply this type
831/// constraint to the nodes operands. This returns true if it makes a
832/// change, false otherwise. If a type contradiction is found, throw an
833/// exception.
834bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
835 const SDNodeInfo &NodeInfo,
836 TreePattern &TP) const {
Chris Lattner2e68a022010-03-19 21:56:21 +0000837 unsigned ResNo = 0; // The result number being referenced.
838 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000839
Chris Lattner6cefb772008-01-05 22:25:12 +0000840 switch (ConstraintType) {
841 default: assert(0 && "Unknown constraint type!");
842 case SDTCisVT:
843 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000844 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000845 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000846 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000847 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000848 case SDTCisInt:
849 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000850 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000851 case SDTCisFP:
852 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000853 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000854 case SDTCisVec:
855 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000856 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000857 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000858 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000859 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000860 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000861 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
862 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000863 }
864 case SDTCisVTSmallerThanOp: {
865 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
866 // have an integer type that is smaller than the VT.
867 if (!NodeToApply->isLeaf() ||
868 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
869 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
870 ->isSubClassOf("ValueType"))
871 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000872 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000873 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000874
Chris Lattnercc878302010-03-24 00:06:46 +0000875 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000876
Chris Lattner2e68a022010-03-19 21:56:21 +0000877 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000878 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000879 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
880 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000881
Chris Lattnercc878302010-03-24 00:06:46 +0000882 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000883 }
884 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000885 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000886 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000887 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
888 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000889 return NodeToApply->getExtType(ResNo).
890 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000891 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000892 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000893 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000894 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000895 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
896 VResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000897
Chris Lattner66fb9d22010-03-24 00:01:16 +0000898 // Filter vector types out of VecOperand that don't have the right element
899 // type.
900 return VecOperand->getExtType(VResNo).
901 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000902 }
David Greene60322692011-01-24 20:53:18 +0000903 case SDTCisSubVecOfVec: {
904 unsigned VResNo = 0;
905 TreePatternNode *BigVecOperand =
906 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
907 VResNo);
908
909 // Filter vector types out of BigVecOperand that don't have the
910 // right subvector type.
911 return BigVecOperand->getExtType(VResNo).
912 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
913 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000914 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000915 return false;
916}
917
918//===----------------------------------------------------------------------===//
919// SDNodeInfo implementation
920//
921SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
922 EnumName = R->getValueAsString("Opcode");
923 SDClassName = R->getValueAsString("SDClass");
924 Record *TypeProfile = R->getValueAsDef("TypeProfile");
925 NumResults = TypeProfile->getValueAsInt("NumResults");
926 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000927
Chris Lattner6cefb772008-01-05 22:25:12 +0000928 // Parse the properties.
929 Properties = 0;
930 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
931 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
932 if (PropList[i]->getName() == "SDNPCommutative") {
933 Properties |= 1 << SDNPCommutative;
934 } else if (PropList[i]->getName() == "SDNPAssociative") {
935 Properties |= 1 << SDNPAssociative;
936 } else if (PropList[i]->getName() == "SDNPHasChain") {
937 Properties |= 1 << SDNPHasChain;
Chris Lattner036609b2010-12-23 18:28:41 +0000938 } else if (PropList[i]->getName() == "SDNPOutGlue") {
939 Properties |= 1 << SDNPOutGlue;
940 } else if (PropList[i]->getName() == "SDNPInGlue") {
941 Properties |= 1 << SDNPInGlue;
942 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
943 Properties |= 1 << SDNPOptInGlue;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000944 } else if (PropList[i]->getName() == "SDNPMayStore") {
945 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000946 } else if (PropList[i]->getName() == "SDNPMayLoad") {
947 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000948 } else if (PropList[i]->getName() == "SDNPSideEffect") {
949 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000950 } else if (PropList[i]->getName() == "SDNPMemOperand") {
951 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000952 } else if (PropList[i]->getName() == "SDNPVariadic") {
953 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000954 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000955 errs() << "Unknown SD Node property '" << PropList[i]->getName()
956 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000957 exit(1);
958 }
959 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000960
961
Chris Lattner6cefb772008-01-05 22:25:12 +0000962 // Parse the type constraints.
963 std::vector<Record*> ConstraintList =
964 TypeProfile->getValueAsListOfDefs("Constraints");
965 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
966}
967
Chris Lattner22579812010-02-28 00:22:30 +0000968/// getKnownType - If the type constraints on this node imply a fixed type
969/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000970/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000971MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +0000972 unsigned NumResults = getNumResults();
973 assert(NumResults <= 1 &&
974 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +0000975 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000976
Chris Lattner22579812010-02-28 00:22:30 +0000977 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
978 // Make sure that this applies to the correct node result.
979 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
980 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000981
Chris Lattner22579812010-02-28 00:22:30 +0000982 switch (TypeConstraints[i].ConstraintType) {
983 default: break;
984 case SDTypeConstraint::SDTCisVT:
985 return TypeConstraints[i].x.SDTCisVT_Info.VT;
986 case SDTypeConstraint::SDTCisPtrTy:
987 return MVT::iPTR;
988 }
989 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000990 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000991}
992
Chris Lattner6cefb772008-01-05 22:25:12 +0000993//===----------------------------------------------------------------------===//
994// TreePatternNode implementation
995//
996
997TreePatternNode::~TreePatternNode() {
998#if 0 // FIXME: implement refcounted tree nodes!
999 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1000 delete getChild(i);
1001#endif
1002}
1003
Chris Lattnerd7349192010-03-19 21:37:09 +00001004static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1005 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +00001006 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +00001007 return 0; // All return nothing.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001008
Chris Lattner93dc92e2010-03-22 20:56:36 +00001009 if (Operator->isSubClassOf("Intrinsic"))
1010 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001011
Chris Lattnerd7349192010-03-19 21:37:09 +00001012 if (Operator->isSubClassOf("SDNode"))
1013 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001014
Chris Lattnerd7349192010-03-19 21:37:09 +00001015 if (Operator->isSubClassOf("PatFrag")) {
1016 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1017 // the forward reference case where one pattern fragment references another
1018 // before it is processed.
1019 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1020 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001021
Chris Lattnerd7349192010-03-19 21:37:09 +00001022 // Get the result tree.
1023 DagInit *Tree = Operator->getValueAsDag("Fragment");
1024 Record *Op = 0;
1025 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
1026 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
1027 assert(Op && "Invalid Fragment");
1028 return GetNumNodeResults(Op, CDP);
1029 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001030
Chris Lattnerd7349192010-03-19 21:37:09 +00001031 if (Operator->isSubClassOf("Instruction")) {
1032 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001033
1034 // FIXME: Should allow access to all the results here.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001035 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001036
Chris Lattner9414ae52010-03-27 20:09:24 +00001037 // Add on one implicit def if it has a resolvable type.
1038 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1039 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001040 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +00001041 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001042
Chris Lattnerd7349192010-03-19 21:37:09 +00001043 if (Operator->isSubClassOf("SDNodeXForm"))
1044 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001045
Chris Lattnerd7349192010-03-19 21:37:09 +00001046 Operator->dump();
1047 errs() << "Unhandled node in GetNumNodeResults\n";
1048 exit(1);
1049}
1050
1051void TreePatternNode::print(raw_ostream &OS) const {
1052 if (isLeaf())
1053 OS << *getLeafValue();
1054 else
1055 OS << '(' << getOperator()->getName();
1056
1057 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1058 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +00001059
1060 if (!isLeaf()) {
1061 if (getNumChildren() != 0) {
1062 OS << " ";
1063 getChild(0)->print(OS);
1064 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1065 OS << ", ";
1066 getChild(i)->print(OS);
1067 }
1068 }
1069 OS << ")";
1070 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001071
Dan Gohman0540e172008-10-15 06:17:21 +00001072 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner54379062011-04-17 21:38:24 +00001073 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +00001074 if (TransformFn)
1075 OS << "<<X:" << TransformFn->getName() << ">>";
1076 if (!getName().empty())
1077 OS << ":$" << getName();
1078
1079}
1080void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001081 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +00001082}
1083
Scott Michel327d0652008-03-05 17:49:05 +00001084/// isIsomorphicTo - Return true if this node is recursively
1085/// isomorphic to the specified node. For this comparison, the node's
1086/// entire state is considered. The assigned name is ignored, since
1087/// nodes with differing names are considered isomorphic. However, if
1088/// the assigned name is present in the dependent variable set, then
1089/// the assigned name is considered significant and the node is
1090/// isomorphic if the names match.
1091bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1092 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001093 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +00001094 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +00001095 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00001096 getTransformFn() != N->getTransformFn())
1097 return false;
1098
1099 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +00001100 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1101 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +00001102 return ((DI->getDef() == NDI->getDef())
1103 && (DepVars.find(getName()) == DepVars.end()
1104 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +00001105 }
1106 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001107 return getLeafValue() == N->getLeafValue();
1108 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001109
Chris Lattner6cefb772008-01-05 22:25:12 +00001110 if (N->getOperator() != getOperator() ||
1111 N->getNumChildren() != getNumChildren()) return false;
1112 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00001113 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +00001114 return false;
1115 return true;
1116}
1117
1118/// clone - Make a copy of this tree and all of its children.
1119///
1120TreePatternNode *TreePatternNode::clone() const {
1121 TreePatternNode *New;
1122 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001123 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001124 } else {
1125 std::vector<TreePatternNode*> CChildren;
1126 CChildren.reserve(Children.size());
1127 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1128 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +00001129 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001130 }
1131 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001132 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +00001133 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00001134 New->setTransformFn(getTransformFn());
1135 return New;
1136}
1137
Chris Lattner47661322010-02-14 22:22:58 +00001138/// RemoveAllTypes - Recursively strip all the types of this tree.
1139void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +00001140 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1141 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +00001142 if (isLeaf()) return;
1143 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1144 getChild(i)->RemoveAllTypes();
1145}
1146
1147
Chris Lattner6cefb772008-01-05 22:25:12 +00001148/// SubstituteFormalArguments - Replace the formal arguments in this tree
1149/// with actual values specified by ArgMap.
1150void TreePatternNode::
1151SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1152 if (isLeaf()) return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001153
Chris Lattner6cefb772008-01-05 22:25:12 +00001154 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1155 TreePatternNode *Child = getChild(i);
1156 if (Child->isLeaf()) {
1157 Init *Val = Child->getLeafValue();
1158 if (dynamic_cast<DefInit*>(Val) &&
1159 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
1160 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +00001161 TreePatternNode *NewChild = ArgMap[Child->getName()];
1162 assert(NewChild && "Couldn't find formal argument!");
1163 assert((Child->getPredicateFns().empty() ||
1164 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1165 "Non-empty child predicate clobbered!");
1166 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +00001167 }
1168 } else {
1169 getChild(i)->SubstituteFormalArguments(ArgMap);
1170 }
1171 }
1172}
1173
1174
1175/// InlinePatternFragments - If this pattern refers to any pattern
1176/// fragments, inline them into place, giving us a pattern without any
1177/// PatFrag references.
1178TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1179 if (isLeaf()) return this; // nothing to do.
1180 Record *Op = getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001181
Chris Lattner6cefb772008-01-05 22:25:12 +00001182 if (!Op->isSubClassOf("PatFrag")) {
1183 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00001184 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1185 TreePatternNode *Child = getChild(i);
1186 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1187
1188 assert((Child->getPredicateFns().empty() ||
1189 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1190 "Non-empty child predicate clobbered!");
1191
1192 setChild(i, NewChild);
1193 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001194 return this;
1195 }
1196
1197 // Otherwise, we found a reference to a fragment. First, look up its
1198 // TreePattern record.
1199 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001200
Chris Lattner6cefb772008-01-05 22:25:12 +00001201 // Verify that we are passing the right number of operands.
1202 if (Frag->getNumArgs() != Children.size())
1203 TP.error("'" + Op->getName() + "' fragment requires " +
1204 utostr(Frag->getNumArgs()) + " operands!");
1205
1206 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1207
Chris Lattner54379062011-04-17 21:38:24 +00001208 TreePredicateFn PredFn(Frag);
1209 if (!PredFn.isAlwaysTrue())
1210 FragTree->addPredicateFn(PredFn);
Dan Gohman0540e172008-10-15 06:17:21 +00001211
Chris Lattner6cefb772008-01-05 22:25:12 +00001212 // Resolve formal arguments to their actual value.
1213 if (Frag->getNumArgs()) {
1214 // Compute the map of formal to actual arguments.
1215 std::map<std::string, TreePatternNode*> ArgMap;
1216 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1217 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001218
Chris Lattner6cefb772008-01-05 22:25:12 +00001219 FragTree->SubstituteFormalArguments(ArgMap);
1220 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001221
Chris Lattner6cefb772008-01-05 22:25:12 +00001222 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001223 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1224 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +00001225
1226 // Transfer in the old predicates.
1227 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1228 FragTree->addPredicateFn(getPredicateFns()[i]);
1229
Chris Lattner6cefb772008-01-05 22:25:12 +00001230 // Get a new copy of this fragment to stitch into here.
1231 //delete this; // FIXME: implement refcounting!
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001232
Chris Lattner2ca698d2008-06-30 03:02:03 +00001233 // The fragment we inlined could have recursive inlining that is needed. See
1234 // if there are any pattern fragments in it and inline them as needed.
1235 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001236}
1237
1238/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +00001239/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +00001240/// references from the register file information, for example.
1241///
Chris Lattnerd7349192010-03-19 21:37:09 +00001242static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1243 bool NotRegisters, TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001244 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00001245 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001246 assert(ResNo == 0 && "Regclass ref only has one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001247 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001248 return EEVT::TypeSet(); // Unknown.
1249 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1250 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001251 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001252
Chris Lattner640a3f52010-03-23 23:50:31 +00001253 if (R->isSubClassOf("PatFrag")) {
1254 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001255 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001256 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001257 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001258
Chris Lattner640a3f52010-03-23 23:50:31 +00001259 if (R->isSubClassOf("Register")) {
1260 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001261 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001262 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001263 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001264 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001265 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00001266
1267 if (R->isSubClassOf("SubRegIndex")) {
1268 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1269 return EEVT::TypeSet();
1270 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001271
Chris Lattner640a3f52010-03-23 23:50:31 +00001272 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1273 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001274 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001275 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001276 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001277
Chris Lattner640a3f52010-03-23 23:50:31 +00001278 if (R->isSubClassOf("ComplexPattern")) {
1279 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001280 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001281 return EEVT::TypeSet(); // Unknown.
1282 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1283 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001284 }
1285 if (R->isSubClassOf("PointerLikeRegClass")) {
1286 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001287 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001288 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001289
Chris Lattner640a3f52010-03-23 23:50:31 +00001290 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1291 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001292 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001293 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001294 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001295
Chris Lattner6cefb772008-01-05 22:25:12 +00001296 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001297 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001298}
1299
Chris Lattnere67bde52008-01-06 05:36:50 +00001300
1301/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1302/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1303const CodeGenIntrinsic *TreePatternNode::
1304getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1305 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1306 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1307 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1308 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001309
1310 unsigned IID =
Chris Lattnere67bde52008-01-06 05:36:50 +00001311 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1312 return &CDP.getIntrinsicInfo(IID);
1313}
1314
Chris Lattner47661322010-02-14 22:22:58 +00001315/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1316/// return the ComplexPattern information, otherwise return null.
1317const ComplexPattern *
1318TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1319 if (!isLeaf()) return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001320
Chris Lattner47661322010-02-14 22:22:58 +00001321 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1322 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1323 return &CGP.getComplexPattern(DI->getDef());
1324 return 0;
1325}
1326
1327/// NodeHasProperty - Return true if this node has the specified property.
1328bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001329 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001330 if (isLeaf()) {
1331 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1332 return CP->hasProperty(Property);
1333 return false;
1334 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001335
Chris Lattner47661322010-02-14 22:22:58 +00001336 Record *Operator = getOperator();
1337 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001338
Chris Lattner47661322010-02-14 22:22:58 +00001339 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1340}
1341
1342
1343
1344
1345/// TreeHasProperty - Return true if any node in this tree has the specified
1346/// property.
1347bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001348 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001349 if (NodeHasProperty(Property, CGP))
1350 return true;
1351 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1352 if (getChild(i)->TreeHasProperty(Property, CGP))
1353 return true;
1354 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001355}
Chris Lattner47661322010-02-14 22:22:58 +00001356
Evan Cheng6bd95672008-06-16 20:29:38 +00001357/// isCommutativeIntrinsic - Return true if the node corresponds to a
1358/// commutative intrinsic.
1359bool
1360TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1361 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1362 return Int->isCommutative;
1363 return false;
1364}
1365
Chris Lattnere67bde52008-01-06 05:36:50 +00001366
Bob Wilson6c01ca92009-01-05 17:23:09 +00001367/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001368/// this node and its children in the tree. This returns true if it makes a
1369/// change, false otherwise. If a type contradiction is found, throw an
1370/// exception.
1371bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001372 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001373 if (isLeaf()) {
1374 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1375 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001376 bool MadeChange = false;
1377 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1378 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1379 NotRegisters, TP), TP);
1380 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001381 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001382
Chris Lattner523f6a52010-02-14 21:10:15 +00001383 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001384 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001385
Chris Lattnerd7349192010-03-19 21:37:09 +00001386 // Int inits are always integers. :)
1387 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001388
Chris Lattnerd7349192010-03-19 21:37:09 +00001389 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001390 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001391
Chris Lattnerd7349192010-03-19 21:37:09 +00001392 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001393 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1394 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001395
Chris Lattner2cacec52010-03-15 06:00:16 +00001396 unsigned Size = EVT(VT).getSizeInBits();
1397 // Make sure that the value is representable for this type.
1398 if (Size >= 32) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001399
Chris Lattner2cacec52010-03-15 06:00:16 +00001400 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1401 if (Val == II->getValue()) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001402
Chris Lattner2cacec52010-03-15 06:00:16 +00001403 // If sign-extended doesn't fit, does it fit as unsigned?
1404 unsigned ValueMask;
1405 unsigned UnsignedVal;
1406 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1407 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001408
Chris Lattner2cacec52010-03-15 06:00:16 +00001409 if ((ValueMask & UnsignedVal) == UnsignedVal)
1410 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001411
Chris Lattner2cacec52010-03-15 06:00:16 +00001412 TP.error("Integer value '" + itostr(II->getValue())+
Chris Lattnerd7349192010-03-19 21:37:09 +00001413 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001414 return MadeChange;
1415 }
1416 return false;
1417 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001418
Chris Lattner6cefb772008-01-05 22:25:12 +00001419 // special handling for set, which isn't really an SDNode.
1420 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001421 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1422 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001423 unsigned NC = getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001424
Chris Lattnerd7349192010-03-19 21:37:09 +00001425 TreePatternNode *SetVal = getChild(NC-1);
1426 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1427
Chris Lattner6cefb772008-01-05 22:25:12 +00001428 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001429 TreePatternNode *Child = getChild(i);
1430 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001431
Chris Lattner6cefb772008-01-05 22:25:12 +00001432 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001433 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1434 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001435 }
1436 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001437 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001438
Chris Lattner310adf12010-03-27 02:53:27 +00001439 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001440 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1441
Chris Lattner6cefb772008-01-05 22:25:12 +00001442 bool MadeChange = false;
1443 for (unsigned i = 0; i < getNumChildren(); ++i)
1444 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001445 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001446 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001447
Chris Lattner6eb30122010-02-23 05:51:07 +00001448 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001449 bool MadeChange = false;
1450 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1451 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001452
Chris Lattnerd7349192010-03-19 21:37:09 +00001453 assert(getChild(0)->getNumTypes() == 1 &&
1454 getChild(1)->getNumTypes() == 1 && "Unhandled case");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001455
Chris Lattner2cacec52010-03-15 06:00:16 +00001456 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1457 // what type it gets, so if it didn't get a concrete type just give it the
1458 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001459 if (!getChild(1)->hasTypeSet(0) &&
1460 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1461 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1462 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001463 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001464 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001465 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001466
Chris Lattner6eb30122010-02-23 05:51:07 +00001467 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001468 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001469
Chris Lattner6cefb772008-01-05 22:25:12 +00001470 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001471 unsigned NumRetVTs = Int->IS.RetVTs.size();
1472 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001473
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001474 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001475 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001476
Chris Lattnerd7349192010-03-19 21:37:09 +00001477 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001478 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001479 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001480 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001481
1482 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001483 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001484
Chris Lattnerd7349192010-03-19 21:37:09 +00001485 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1486 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001487
Chris Lattnerd7349192010-03-19 21:37:09 +00001488 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1489 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1490 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001491 }
1492 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001493 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001494
Chris Lattner6eb30122010-02-23 05:51:07 +00001495 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001496 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001497
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001498 // Check that the number of operands is sane. Negative operands -> varargs.
1499 if (NI.getNumOperands() >= 0 &&
1500 getNumChildren() != (unsigned)NI.getNumOperands())
1501 TP.error(getOperator()->getName() + " node requires exactly " +
1502 itostr(NI.getNumOperands()) + " operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001503
Chris Lattner6cefb772008-01-05 22:25:12 +00001504 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1505 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1506 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001507 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001508 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001509
Chris Lattner6eb30122010-02-23 05:51:07 +00001510 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001511 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001512 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001513 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001514
Chris Lattner0be6fe72010-03-27 19:15:02 +00001515 bool MadeChange = false;
1516
1517 // Apply the result types to the node, these come from the things in the
1518 // (outs) list of the instruction.
1519 // FIXME: Cap at one result so far.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001520 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001521 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1522 Record *ResultNode = Inst.getResult(ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001523
Chris Lattnera938ac62009-07-29 20:43:05 +00001524 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001525 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001526 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001527 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001528 } else {
1529 assert(ResultNode->isSubClassOf("RegisterClass") &&
1530 "Operands should be register classes!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001531 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001532 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001533 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001534 }
Chris Lattner0be6fe72010-03-27 19:15:02 +00001535 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001536
Chris Lattner0be6fe72010-03-27 19:15:02 +00001537 // If the instruction has implicit defs, we apply the first one as a result.
1538 // FIXME: This sucks, it should apply all implicit defs.
1539 if (!InstInfo.ImplicitDefs.empty()) {
1540 unsigned ResNo = NumResultsToAdd;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001541
Chris Lattner9414ae52010-03-27 20:09:24 +00001542 // FIXME: Generalize to multiple possible types and multiple possible
1543 // ImplicitDefs.
1544 MVT::SimpleValueType VT =
1545 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001546
Chris Lattner9414ae52010-03-27 20:09:24 +00001547 if (VT != MVT::Other)
1548 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001549 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001550
Chris Lattner2cacec52010-03-15 06:00:16 +00001551 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1552 // be the same.
1553 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001554 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1555 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1556 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001557 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001558
1559 unsigned ChildNo = 0;
1560 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1561 Record *OperandNode = Inst.getOperand(i);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001562
Chris Lattner6cefb772008-01-05 22:25:12 +00001563 // If the instruction expects a predicate or optional def operand, we
1564 // codegen this by setting the operand to it's default value if it has a
1565 // non-empty DefaultOps field.
1566 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1567 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1568 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1569 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001570
Chris Lattner6cefb772008-01-05 22:25:12 +00001571 // Verify that we didn't run out of provided operands.
1572 if (ChildNo >= getNumChildren())
1573 TP.error("Instruction '" + getOperator()->getName() +
1574 "' expects more operands than were provided.");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001575
Owen Anderson825b72b2009-08-11 20:47:22 +00001576 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001577 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001578 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001579
Chris Lattner6cefb772008-01-05 22:25:12 +00001580 if (OperandNode->isSubClassOf("RegisterClass")) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001581 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001582 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001583 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001584 } else if (OperandNode->isSubClassOf("Operand")) {
1585 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattner0be6fe72010-03-27 19:15:02 +00001586 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001587 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001588 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001589 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001590 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001591 } else {
1592 assert(0 && "Unknown operand type!");
1593 abort();
1594 }
1595 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1596 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001597
Christopher Lamb02f69372008-03-10 04:16:09 +00001598 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001599 TP.error("Instruction '" + getOperator()->getName() +
1600 "' was provided too many operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001601
Chris Lattner6cefb772008-01-05 22:25:12 +00001602 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001603 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001604
Chris Lattner6eb30122010-02-23 05:51:07 +00001605 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001606
Chris Lattner6eb30122010-02-23 05:51:07 +00001607 // Node transforms always take one operand.
1608 if (getNumChildren() != 1)
1609 TP.error("Node transform '" + getOperator()->getName() +
1610 "' requires one operand!");
1611
Chris Lattner2cacec52010-03-15 06:00:16 +00001612 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1613
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001614
Chris Lattner6eb30122010-02-23 05:51:07 +00001615 // If either the output or input of the xform does not have exact
1616 // type info. We assume they must be the same. Otherwise, it is perfectly
1617 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001618#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001619 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001620 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1621 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001622 return MadeChange;
1623 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001624#endif
1625 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001626}
1627
1628/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1629/// RHS of a commutative operation, not the on LHS.
1630static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1631 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1632 return true;
1633 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1634 return true;
1635 return false;
1636}
1637
1638
1639/// canPatternMatch - If it is impossible for this pattern to match on this
1640/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001641/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001642/// that can never possibly work), and to prevent the pattern permuter from
1643/// generating stuff that is useless.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001644bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001645 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001646 if (isLeaf()) return true;
1647
1648 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1649 if (!getChild(i)->canPatternMatch(Reason, CDP))
1650 return false;
1651
1652 // If this is an intrinsic, handle cases that would make it not match. For
1653 // example, if an operand is required to be an immediate.
1654 if (getOperator()->isSubClassOf("Intrinsic")) {
1655 // TODO:
1656 return true;
1657 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001658
Chris Lattner6cefb772008-01-05 22:25:12 +00001659 // If this node is a commutative operator, check that the LHS isn't an
1660 // immediate.
1661 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001662 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1663 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001664 // Scan all of the operands of the node and make sure that only the last one
1665 // is a constant node, unless the RHS also is.
1666 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001667 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1668 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001669 if (OnlyOnRHSOfCommutative(getChild(i))) {
1670 Reason="Immediate value must be on the RHS of commutative operators!";
1671 return false;
1672 }
1673 }
1674 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001675
Chris Lattner6cefb772008-01-05 22:25:12 +00001676 return true;
1677}
1678
1679//===----------------------------------------------------------------------===//
1680// TreePattern implementation
1681//
1682
1683TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001684 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001685 isInputPattern = isInput;
1686 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattnerc2173052010-03-28 06:50:34 +00001687 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001688}
1689
1690TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001691 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001692 isInputPattern = isInput;
Chris Lattnerc2173052010-03-28 06:50:34 +00001693 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001694}
1695
1696TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001697 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001698 isInputPattern = isInput;
1699 Trees.push_back(Pat);
1700}
1701
Chris Lattner6cefb772008-01-05 22:25:12 +00001702void TreePattern::error(const std::string &Msg) const {
1703 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001704 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001705}
1706
Chris Lattner2cacec52010-03-15 06:00:16 +00001707void TreePattern::ComputeNamedNodes() {
1708 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1709 ComputeNamedNodes(Trees[i]);
1710}
1711
1712void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1713 if (!N->getName().empty())
1714 NamedNodes[N->getName()].push_back(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001715
Chris Lattner2cacec52010-03-15 06:00:16 +00001716 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1717 ComputeNamedNodes(N->getChild(i));
1718}
1719
Chris Lattnerd7349192010-03-19 21:37:09 +00001720
Chris Lattnerc2173052010-03-28 06:50:34 +00001721TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1722 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
1723 Record *R = DI->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001724
Chris Lattnerc2173052010-03-28 06:50:34 +00001725 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1726 // TreePatternNode if its own. For example:
1727 /// (foo GPR, imm) -> (foo GPR, (imm))
1728 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1729 return ParseTreePattern(new DagInit(DI, "",
1730 std::vector<std::pair<Init*, std::string> >()),
1731 OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001732
Chris Lattnerc2173052010-03-28 06:50:34 +00001733 // Input argument?
1734 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001735 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001736 if (OpName.empty())
1737 error("'node' argument requires a name to match with operand list");
1738 Args.push_back(OpName);
1739 }
1740
1741 Res->setName(OpName);
1742 return Res;
1743 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001744
Chris Lattnerc2173052010-03-28 06:50:34 +00001745 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
1746 if (!OpName.empty())
1747 error("Constant int argument should not have a name!");
1748 return new TreePatternNode(II, 1);
1749 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001750
Chris Lattnerc2173052010-03-28 06:50:34 +00001751 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
1752 // Turn this into an IntInit.
1753 Init *II = BI->convertInitializerTo(new IntRecTy());
1754 if (II == 0 || !dynamic_cast<IntInit*>(II))
1755 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001756 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00001757 }
1758
1759 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
1760 if (!Dag) {
1761 TheInit->dump();
1762 error("Pattern has unexpected init kind!");
1763 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001764 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1765 if (!OpDef) error("Pattern has unexpected operator type!");
1766 Record *Operator = OpDef->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001767
Chris Lattner6cefb772008-01-05 22:25:12 +00001768 if (Operator->isSubClassOf("ValueType")) {
1769 // If the operator is a ValueType, then this must be "type cast" of a leaf
1770 // node.
1771 if (Dag->getNumArgs() != 1)
1772 error("Type cast only takes one operand!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001773
Chris Lattnerc2173052010-03-28 06:50:34 +00001774 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001775
Chris Lattner6cefb772008-01-05 22:25:12 +00001776 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001777 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1778 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001779
Chris Lattnerc2173052010-03-28 06:50:34 +00001780 if (!OpName.empty())
1781 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001782 return New;
1783 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001784
Chris Lattner6cefb772008-01-05 22:25:12 +00001785 // Verify that this is something that makes sense for an operator.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001786 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begeman7cee8172009-03-19 05:21:56 +00001787 !Operator->isSubClassOf("SDNode") &&
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001788 !Operator->isSubClassOf("Instruction") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001789 !Operator->isSubClassOf("SDNodeXForm") &&
1790 !Operator->isSubClassOf("Intrinsic") &&
1791 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001792 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001793 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001794
Chris Lattner6cefb772008-01-05 22:25:12 +00001795 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001796 if (isInputPattern) {
1797 if (Operator->isSubClassOf("Instruction") ||
1798 Operator->isSubClassOf("SDNodeXForm"))
1799 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1800 } else {
1801 if (Operator->isSubClassOf("Intrinsic"))
1802 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001803
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001804 if (Operator->isSubClassOf("SDNode") &&
1805 Operator->getName() != "imm" &&
1806 Operator->getName() != "fpimm" &&
1807 Operator->getName() != "tglobaltlsaddr" &&
1808 Operator->getName() != "tconstpool" &&
1809 Operator->getName() != "tjumptable" &&
1810 Operator->getName() != "tframeindex" &&
1811 Operator->getName() != "texternalsym" &&
1812 Operator->getName() != "tblockaddress" &&
1813 Operator->getName() != "tglobaladdr" &&
1814 Operator->getName() != "bb" &&
1815 Operator->getName() != "vt")
1816 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1817 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001818
Chris Lattner6cefb772008-01-05 22:25:12 +00001819 std::vector<TreePatternNode*> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00001820
1821 // Parse all the operands.
1822 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1823 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001824
Chris Lattner6cefb772008-01-05 22:25:12 +00001825 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001826 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner6cefb772008-01-05 22:25:12 +00001827 // convert the intrinsic name to a number.
1828 if (Operator->isSubClassOf("Intrinsic")) {
1829 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1830 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1831
1832 // If this intrinsic returns void, it must have side-effects and thus a
1833 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00001834 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001835 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001836 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00001837 // Has side-effects, requires chain.
1838 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001839 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00001840 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001841
Chris Lattnerd7349192010-03-19 21:37:09 +00001842 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001843 Children.insert(Children.begin(), IIDNode);
1844 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001845
Chris Lattnerd7349192010-03-19 21:37:09 +00001846 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1847 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00001848 Result->setName(OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001849
Chris Lattnerc2173052010-03-28 06:50:34 +00001850 if (!Dag->getName().empty()) {
1851 assert(Result->getName().empty());
1852 Result->setName(Dag->getName());
1853 }
Nate Begeman7cee8172009-03-19 05:21:56 +00001854 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001855}
1856
Chris Lattner7a0eb912010-03-28 08:38:32 +00001857/// SimplifyTree - See if we can simplify this tree to eliminate something that
1858/// will never match in favor of something obvious that will. This is here
1859/// strictly as a convenience to target authors because it allows them to write
1860/// more type generic things and have useless type casts fold away.
1861///
1862/// This returns true if any change is made.
1863static bool SimplifyTree(TreePatternNode *&N) {
1864 if (N->isLeaf())
1865 return false;
1866
1867 // If we have a bitconvert with a resolved type and if the source and
1868 // destination types are the same, then the bitconvert is useless, remove it.
1869 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattner7a0eb912010-03-28 08:38:32 +00001870 N->getExtType(0).isConcrete() &&
1871 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1872 N->getName().empty()) {
1873 N = N->getChild(0);
1874 SimplifyTree(N);
1875 return true;
1876 }
1877
1878 // Walk all children.
1879 bool MadeChange = false;
1880 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1881 TreePatternNode *Child = N->getChild(i);
1882 MadeChange |= SimplifyTree(Child);
1883 N->setChild(i, Child);
1884 }
1885 return MadeChange;
1886}
1887
1888
1889
Chris Lattner6cefb772008-01-05 22:25:12 +00001890/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001891/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001892/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001893bool TreePattern::
1894InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1895 if (NamedNodes.empty())
1896 ComputeNamedNodes();
1897
Chris Lattner6cefb772008-01-05 22:25:12 +00001898 bool MadeChange = true;
1899 while (MadeChange) {
1900 MadeChange = false;
Chris Lattner7a0eb912010-03-28 08:38:32 +00001901 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001902 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner7a0eb912010-03-28 08:38:32 +00001903 MadeChange |= SimplifyTree(Trees[i]);
1904 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001905
1906 // If there are constraints on our named nodes, apply them.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001907 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattner2cacec52010-03-15 06:00:16 +00001908 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1909 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001910
Chris Lattner2cacec52010-03-15 06:00:16 +00001911 // If we have input named node types, propagate their types to the named
1912 // values here.
1913 if (InNamedTypes) {
1914 // FIXME: Should be error?
1915 assert(InNamedTypes->count(I->getKey()) &&
1916 "Named node in output pattern but not input pattern?");
1917
1918 const SmallVectorImpl<TreePatternNode*> &InNodes =
1919 InNamedTypes->find(I->getKey())->second;
1920
1921 // The input types should be fully resolved by now.
1922 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1923 // If this node is a register class, and it is the root of the pattern
1924 // then we're mapping something onto an input register. We allow
1925 // changing the type of the input register in this case. This allows
1926 // us to match things like:
1927 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1928 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1929 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1930 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1931 continue;
1932 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001933
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001934 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001935 InNodes[0]->getNumTypes() == 1 &&
1936 "FIXME: cannot name multiple result nodes yet");
1937 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1938 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001939 }
1940 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001941
Chris Lattner2cacec52010-03-15 06:00:16 +00001942 // If there are multiple nodes with the same name, they must all have the
1943 // same type.
1944 if (I->second.size() > 1) {
1945 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001946 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001947 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001948 "FIXME: cannot name multiple result nodes yet");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001949
Chris Lattnerd7349192010-03-19 21:37:09 +00001950 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1951 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001952 }
1953 }
1954 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001955 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001956
Chris Lattner6cefb772008-01-05 22:25:12 +00001957 bool HasUnresolvedTypes = false;
1958 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1959 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1960 return !HasUnresolvedTypes;
1961}
1962
Daniel Dunbar1a551802009-07-03 00:10:29 +00001963void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001964 OS << getRecord()->getName();
1965 if (!Args.empty()) {
1966 OS << "(" << Args[0];
1967 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1968 OS << ", " << Args[i];
1969 OS << ")";
1970 }
1971 OS << ": ";
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001972
Chris Lattner6cefb772008-01-05 22:25:12 +00001973 if (Trees.size() > 1)
1974 OS << "[\n";
1975 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1976 OS << "\t";
1977 Trees[i]->print(OS);
1978 OS << "\n";
1979 }
1980
1981 if (Trees.size() > 1)
1982 OS << "]\n";
1983}
1984
Daniel Dunbar1a551802009-07-03 00:10:29 +00001985void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001986
1987//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001988// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001989//
1990
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001991CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner67db8832010-12-13 00:23:57 +00001992 Records(R), Target(R) {
1993
Dale Johannesen49de9822009-02-05 01:49:45 +00001994 Intrinsics = LoadIntrinsics(Records, false);
1995 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001996 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001997 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001998 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001999 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00002000 ParseDefaultOperands();
2001 ParseInstructions();
2002 ParsePatterns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002003
Chris Lattner6cefb772008-01-05 22:25:12 +00002004 // Generate variants. For example, commutative patterns can match
2005 // multiple ways. Add them to PatternsToMatch as well.
2006 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00002007
2008 // Infer instruction flags. For example, we can detect loads,
2009 // stores, and side effects in many cases by examining an
2010 // instruction's pattern.
2011 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00002012}
2013
Chris Lattnerfe718932008-01-06 01:10:31 +00002014CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002015 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002016 E = PatternFragments.end(); I != E; ++I)
2017 delete I->second;
2018}
2019
2020
Chris Lattnerfe718932008-01-06 01:10:31 +00002021Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00002022 Record *N = Records.getDef(Name);
2023 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002024 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00002025 exit(1);
2026 }
2027 return N;
2028}
2029
2030// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00002031void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002032 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2033 while (!Nodes.empty()) {
2034 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2035 Nodes.pop_back();
2036 }
2037
Jim Grosbachda4231f2009-03-26 16:17:51 +00002038 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00002039 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2040 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2041 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2042}
2043
2044/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2045/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002046void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002047 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2048 while (!Xforms.empty()) {
2049 Record *XFormNode = Xforms.back();
2050 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2051 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00002052 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002053
2054 Xforms.pop_back();
2055 }
2056}
2057
Chris Lattnerfe718932008-01-06 01:10:31 +00002058void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002059 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2060 while (!AMs.empty()) {
2061 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2062 AMs.pop_back();
2063 }
2064}
2065
2066
2067/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2068/// file, building up the PatternFragments map. After we've collected them all,
2069/// inline fragments together as necessary, so that there are no references left
2070/// inside a pattern fragment to a pattern fragment.
2071///
Chris Lattnerfe718932008-01-06 01:10:31 +00002072void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002073 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002074
Chris Lattnerdc32f982008-01-05 22:43:57 +00002075 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002076 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2077 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
2078 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2079 PatternFragments[Fragments[i]] = P;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002080
Chris Lattnerdc32f982008-01-05 22:43:57 +00002081 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00002082 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002083 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002084
Chris Lattnerdc32f982008-01-05 22:43:57 +00002085 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00002086 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002087
Chris Lattner6cefb772008-01-05 22:25:12 +00002088 // Parse the operands list.
2089 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2090 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
2091 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00002092 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00002093 if (!OpsOp ||
2094 (OpsOp->getDef()->getName() != "ops" &&
2095 OpsOp->getDef()->getName() != "outs" &&
2096 OpsOp->getDef()->getName() != "ins"))
2097 P->error("Operands list should start with '(ops ... '!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002098
2099 // Copy over the arguments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002100 Args.clear();
2101 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2102 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
2103 static_cast<DefInit*>(OpsList->getArg(j))->
2104 getDef()->getName() != "node")
2105 P->error("Operands list should all be 'node' values.");
2106 if (OpsList->getArgName(j).empty())
2107 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002108 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00002109 P->error("'" + OpsList->getArgName(j) +
2110 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002111 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00002112 Args.push_back(OpsList->getArgName(j));
2113 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002114
Chris Lattnerdc32f982008-01-05 22:43:57 +00002115 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00002116 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00002117 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002118
Chris Lattnerdc32f982008-01-05 22:43:57 +00002119 // If there is a code init for this fragment, keep track of the fact that
2120 // this fragment uses it.
Chris Lattner54379062011-04-17 21:38:24 +00002121 TreePredicateFn PredFn(P);
2122 if (!PredFn.isAlwaysTrue())
2123 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002124
Chris Lattner6cefb772008-01-05 22:25:12 +00002125 // If there is a node transformation corresponding to this, keep track of
2126 // it.
2127 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2128 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2129 P->getOnlyTree()->setTransformFn(Transform);
2130 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002131
Chris Lattner6cefb772008-01-05 22:25:12 +00002132 // Now that we've parsed all of the tree fragments, do a closure on them so
2133 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00002134 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2135 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00002136 ThePat->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002137
Chris Lattner6cefb772008-01-05 22:25:12 +00002138 // Infer as many types as possible. Don't worry about it if we don't infer
2139 // all of them, some may depend on the inputs of the pattern.
2140 try {
2141 ThePat->InferAllTypes();
2142 } catch (...) {
2143 // If this pattern fragment is not supported by this target (no types can
2144 // satisfy its constraints), just ignore it. If the bogus pattern is
2145 // actually used by instructions, the type consistency error will be
2146 // reported there.
2147 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002148
Chris Lattner6cefb772008-01-05 22:25:12 +00002149 // If debugging, print out the pattern fragment result.
2150 DEBUG(ThePat->dump());
2151 }
2152}
2153
Chris Lattnerfe718932008-01-06 01:10:31 +00002154void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002155 std::vector<Record*> DefaultOps[2];
2156 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
2157 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
2158
2159 // Find some SDNode.
2160 assert(!SDNodes.empty() && "No SDNodes parsed?");
2161 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002162
Chris Lattner6cefb772008-01-05 22:25:12 +00002163 for (unsigned iter = 0; iter != 2; ++iter) {
2164 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
2165 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002166
Chris Lattner6cefb772008-01-05 22:25:12 +00002167 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2168 // SomeSDnode so that we can parse this.
2169 std::vector<std::pair<Init*, std::string> > Ops;
2170 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2171 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2172 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00002173 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002174
Chris Lattner6cefb772008-01-05 22:25:12 +00002175 // Create a TreePattern to parse this.
2176 TreePattern P(DefaultOps[iter][i], DI, false, *this);
2177 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2178
2179 // Copy the operands over into a DAGDefaultOperand.
2180 DAGDefaultOperand DefaultOpInfo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002181
Chris Lattner6cefb772008-01-05 22:25:12 +00002182 TreePatternNode *T = P.getTree(0);
2183 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2184 TreePatternNode *TPN = T->getChild(op);
2185 while (TPN->ApplyTypeConstraints(P, false))
2186 /* Resolve all types */;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002187
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002188 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002189 if (iter == 0)
2190 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00002191 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00002192 else
2193 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00002194 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002195 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002196 DefaultOpInfo.DefaultOps.push_back(TPN);
2197 }
2198
2199 // Insert it into the DefaultOperands map so we can find it later.
2200 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2201 }
2202 }
2203}
2204
2205/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2206/// instruction input. Return true if this is a real use.
2207static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002208 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002209 // No name -> not interesting.
2210 if (Pat->getName().empty()) {
2211 if (Pat->isLeaf()) {
2212 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2213 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
2214 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002215 }
2216 return false;
2217 }
2218
2219 Record *Rec;
2220 if (Pat->isLeaf()) {
2221 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2222 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2223 Rec = DI->getDef();
2224 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00002225 Rec = Pat->getOperator();
2226 }
2227
2228 // SRCVALUE nodes are ignored.
2229 if (Rec->getName() == "srcvalue")
2230 return false;
2231
2232 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2233 if (!Slot) {
2234 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00002235 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00002236 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00002237 Record *SlotRec;
2238 if (Slot->isLeaf()) {
2239 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
2240 } else {
2241 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2242 SlotRec = Slot->getOperator();
2243 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002244
Chris Lattner53d09bd2010-02-23 05:59:10 +00002245 // Ensure that the inputs agree if we've already seen this input.
2246 if (Rec != SlotRec)
2247 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00002248 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00002249 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00002250 return true;
2251}
2252
2253/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2254/// part of "I", the instruction), computing the set of inputs and outputs of
2255/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00002256void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00002257FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2258 std::map<std::string, TreePatternNode*> &InstInputs,
2259 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner6cefb772008-01-05 22:25:12 +00002260 std::vector<Record*> &InstImpResults) {
2261 if (Pat->isLeaf()) {
Chris Lattneracfb70f2010-04-20 06:30:25 +00002262 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002263 if (!isUse && Pat->getTransformFn())
2264 I->error("Cannot specify a transform function for a non-input value!");
2265 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002266 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002267
Chris Lattner84aa60b2010-02-17 06:53:36 +00002268 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002269 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2270 TreePatternNode *Dest = Pat->getChild(i);
2271 if (!Dest->isLeaf())
2272 I->error("implicitly defined value should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002273
Chris Lattner6cefb772008-01-05 22:25:12 +00002274 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2275 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2276 I->error("implicitly defined value should be a register!");
2277 InstImpResults.push_back(Val->getDef());
2278 }
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() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002283 // If this is not a set, verify that the children nodes are not void typed,
2284 // and recurse.
2285 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002286 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002287 I->error("Cannot have void nodes inside of patterns!");
2288 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002289 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002290 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002291
Chris Lattner6cefb772008-01-05 22:25:12 +00002292 // If this is a non-leaf node with no children, treat it basically as if
2293 // it were a leaf. This handles nodes like (imm).
Chris Lattneracfb70f2010-04-20 06:30:25 +00002294 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002295
Chris Lattner6cefb772008-01-05 22:25:12 +00002296 if (!isUse && Pat->getTransformFn())
2297 I->error("Cannot specify a transform function for a non-input value!");
2298 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002299 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002300
Chris Lattner6cefb772008-01-05 22:25:12 +00002301 // Otherwise, this is a set, validate and collect instruction results.
2302 if (Pat->getNumChildren() == 0)
2303 I->error("set requires operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002304
Chris Lattner6cefb772008-01-05 22:25:12 +00002305 if (Pat->getTransformFn())
2306 I->error("Cannot specify a transform function on a set node!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002307
Chris Lattner6cefb772008-01-05 22:25:12 +00002308 // Check the set destinations.
2309 unsigned NumDests = Pat->getNumChildren()-1;
2310 for (unsigned i = 0; i != NumDests; ++i) {
2311 TreePatternNode *Dest = Pat->getChild(i);
2312 if (!Dest->isLeaf())
2313 I->error("set destination should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002314
Chris Lattner6cefb772008-01-05 22:25:12 +00002315 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2316 if (!Val)
2317 I->error("set destination should be a register!");
2318
2319 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002320 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002321 if (Dest->getName().empty())
2322 I->error("set destination must have a name!");
2323 if (InstResults.count(Dest->getName()))
2324 I->error("cannot set '" + Dest->getName() +"' multiple times");
2325 InstResults[Dest->getName()] = Dest;
2326 } else if (Val->getDef()->isSubClassOf("Register")) {
2327 InstImpResults.push_back(Val->getDef());
2328 } else {
2329 I->error("set destination should be a register!");
2330 }
2331 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002332
Chris Lattner6cefb772008-01-05 22:25:12 +00002333 // Verify and collect info from the computation.
2334 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattneracfb70f2010-04-20 06:30:25 +00002335 InstInputs, InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002336}
2337
Dan Gohmanee4fa192008-04-03 00:02:49 +00002338//===----------------------------------------------------------------------===//
2339// Instruction Analysis
2340//===----------------------------------------------------------------------===//
2341
2342class InstAnalyzer {
2343 const CodeGenDAGPatterns &CDP;
2344 bool &mayStore;
2345 bool &mayLoad;
Evan Cheng0f040a22011-03-15 05:09:26 +00002346 bool &IsBitcast;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002347 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002348 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002349public:
2350 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Evan Cheng0f040a22011-03-15 05:09:26 +00002351 bool &maystore, bool &mayload, bool &isbc, bool &hse, bool &isv)
2352 : CDP(cdp), mayStore(maystore), mayLoad(mayload), IsBitcast(isbc),
2353 HasSideEffects(hse), IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002354 }
2355
2356 /// Analyze - Analyze the specified instruction, returning true if the
2357 /// instruction had a pattern.
2358 bool Analyze(Record *InstRecord) {
2359 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2360 if (Pattern == 0) {
2361 HasSideEffects = 1;
2362 return false; // No pattern.
2363 }
2364
2365 // FIXME: Assume only the first tree is the pattern. The others are clobber
2366 // nodes.
2367 AnalyzeNode(Pattern->getTree(0));
2368 return true;
2369 }
2370
2371private:
Evan Cheng0f040a22011-03-15 05:09:26 +00002372 bool IsNodeBitcast(const TreePatternNode *N) const {
2373 if (HasSideEffects || mayLoad || mayStore || IsVariadic)
2374 return false;
2375
2376 if (N->getNumChildren() != 2)
2377 return false;
2378
2379 const TreePatternNode *N0 = N->getChild(0);
2380 if (!N0->isLeaf() || !dynamic_cast<DefInit*>(N0->getLeafValue()))
2381 return false;
2382
2383 const TreePatternNode *N1 = N->getChild(1);
2384 if (N1->isLeaf())
2385 return false;
2386 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2387 return false;
2388
2389 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2390 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2391 return false;
2392 return OpInfo.getEnumName() == "ISD::BITCAST";
2393 }
2394
Dan Gohmanee4fa192008-04-03 00:02:49 +00002395 void AnalyzeNode(const TreePatternNode *N) {
2396 if (N->isLeaf()) {
2397 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2398 Record *LeafRec = DI->getDef();
2399 // Handle ComplexPattern leaves.
2400 if (LeafRec->isSubClassOf("ComplexPattern")) {
2401 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2402 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2403 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2404 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2405 }
2406 }
2407 return;
2408 }
2409
2410 // Analyze children.
2411 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2412 AnalyzeNode(N->getChild(i));
2413
2414 // Ignore set nodes, which are not SDNodes.
Evan Cheng0f040a22011-03-15 05:09:26 +00002415 if (N->getOperator()->getName() == "set") {
2416 IsBitcast = IsNodeBitcast(N);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002417 return;
Evan Cheng0f040a22011-03-15 05:09:26 +00002418 }
Dan Gohmanee4fa192008-04-03 00:02:49 +00002419
2420 // Get information about the SDNode for the operator.
2421 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2422
2423 // Notice properties of the node.
2424 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2425 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2426 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002427 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002428
2429 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2430 // If this is an intrinsic, analyze it.
2431 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2432 mayLoad = true;// These may load memory.
2433
Dan Gohman7365c092010-08-05 23:36:21 +00002434 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002435 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2436
Dan Gohman7365c092010-08-05 23:36:21 +00002437 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002438 // WriteMem intrinsics can have other strange effects.
2439 HasSideEffects = true;
2440 }
2441 }
2442
2443};
2444
2445static void InferFromPattern(const CodeGenInstruction &Inst,
2446 bool &MayStore, bool &MayLoad,
Evan Cheng0f040a22011-03-15 05:09:26 +00002447 bool &IsBitcast,
Chris Lattner1e506312010-03-19 05:34:15 +00002448 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002449 const CodeGenDAGPatterns &CDP) {
Evan Cheng0f040a22011-03-15 05:09:26 +00002450 MayStore = MayLoad = IsBitcast = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002451
2452 bool HadPattern =
Evan Cheng0f040a22011-03-15 05:09:26 +00002453 InstAnalyzer(CDP, MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic)
Chris Lattner1e506312010-03-19 05:34:15 +00002454 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002455
2456 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2457 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2458 // If we decided that this is a store from the pattern, then the .td file
2459 // entry is redundant.
2460 if (MayStore)
2461 fprintf(stderr,
2462 "Warning: mayStore flag explicitly set on instruction '%s'"
2463 " but flag already inferred from pattern.\n",
2464 Inst.TheDef->getName().c_str());
2465 MayStore = true;
2466 }
2467
2468 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2469 // If we decided that this is a load from the pattern, then the .td file
2470 // entry is redundant.
2471 if (MayLoad)
2472 fprintf(stderr,
2473 "Warning: mayLoad flag explicitly set on instruction '%s'"
2474 " but flag already inferred from pattern.\n",
2475 Inst.TheDef->getName().c_str());
2476 MayLoad = true;
2477 }
2478
2479 if (Inst.neverHasSideEffects) {
2480 if (HadPattern)
2481 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2482 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2483 HasSideEffects = false;
2484 }
2485
2486 if (Inst.hasSideEffects) {
2487 if (HasSideEffects)
2488 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2489 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2490 HasSideEffects = true;
2491 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002492
Chris Lattnerc240bb02010-11-01 04:03:32 +00002493 if (Inst.Operands.isVariadic)
Chris Lattner1e506312010-03-19 05:34:15 +00002494 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002495}
2496
Chris Lattner6cefb772008-01-05 22:25:12 +00002497/// ParseInstructions - Parse all of the instructions, inlining and resolving
2498/// any fragments involved. This populates the Instructions list with fully
2499/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002500void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002501 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002502
Chris Lattner6cefb772008-01-05 22:25:12 +00002503 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2504 ListInit *LI = 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002505
Chris Lattner6cefb772008-01-05 22:25:12 +00002506 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2507 LI = Instrs[i]->getValueAsListInit("Pattern");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002508
Chris Lattner6cefb772008-01-05 22:25:12 +00002509 // If there is no pattern, only collect minimal information about the
2510 // instruction for its operand list. We have to assume that there is one
2511 // result, as we have no detailed info.
2512 if (!LI || LI->getSize() == 0) {
2513 std::vector<Record*> Results;
2514 std::vector<Record*> Operands;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002515
Chris Lattnerf30187a2010-03-19 00:07:20 +00002516 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002517
Chris Lattnerc240bb02010-11-01 04:03:32 +00002518 if (InstInfo.Operands.size() != 0) {
2519 if (InstInfo.Operands.NumDefs == 0) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002520 // These produce no results
Chris Lattnerc240bb02010-11-01 04:03:32 +00002521 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2522 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002523 } else {
2524 // Assume the first operand is the result.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002525 Results.push_back(InstInfo.Operands[0].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002526
Chris Lattner6cefb772008-01-05 22:25:12 +00002527 // The rest are inputs.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002528 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2529 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002530 }
2531 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002532
Chris Lattner6cefb772008-01-05 22:25:12 +00002533 // Create and insert the instruction.
2534 std::vector<Record*> ImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002535 Instructions.insert(std::make_pair(Instrs[i],
Chris Lattner62bcec82010-04-20 06:28:43 +00002536 DAGInstruction(0, Results, Operands, ImpResults)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002537 continue; // no pattern.
2538 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002539
Chris Lattner6cefb772008-01-05 22:25:12 +00002540 // Parse the instruction.
2541 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2542 // Inline pattern fragments into it.
2543 I->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002544
Chris Lattner6cefb772008-01-05 22:25:12 +00002545 // Infer as many types as possible. If we cannot infer all of them, we can
2546 // never do anything with this instruction pattern: report it to the user.
2547 if (!I->InferAllTypes())
2548 I->error("Could not infer all types in pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002549
2550 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner6cefb772008-01-05 22:25:12 +00002551 // with the record they are declared as.
2552 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002553
Chris Lattner6cefb772008-01-05 22:25:12 +00002554 // InstResults - Keep track of all the virtual registers that are 'set'
2555 // in the instruction, including what reg class they are.
2556 std::map<std::string, TreePatternNode*> InstResults;
2557
Chris Lattner6cefb772008-01-05 22:25:12 +00002558 std::vector<Record*> InstImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002559
Chris Lattner6cefb772008-01-05 22:25:12 +00002560 // Verify that the top-level forms in the instruction are of void type, and
2561 // fill in the InstResults map.
2562 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2563 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002564 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002565 I->error("Top-level forms in instruction pattern should have"
2566 " void types");
2567
2568 // Find inputs and outputs, and verify the structure of the uses/defs.
2569 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002570 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002571 }
2572
2573 // Now that we have inputs and outputs of the pattern, inspect the operands
2574 // list for the instruction. This determines the order that operands are
2575 // added to the machine instruction the node corresponds to.
2576 unsigned NumResults = InstResults.size();
2577
2578 // Parse the operands list from the (ops) list, validating it.
2579 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002580 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002581
2582 // Check that all of the results occur first in the list.
2583 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002584 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002585 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00002586 if (i == CGI.Operands.size())
Chris Lattner6cefb772008-01-05 22:25:12 +00002587 I->error("'" + InstResults.begin()->first +
2588 "' set but does not appear in operand list!");
Chris Lattnerc240bb02010-11-01 04:03:32 +00002589 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002590
Chris Lattner6cefb772008-01-05 22:25:12 +00002591 // Check that it exists in InstResults.
2592 TreePatternNode *RNode = InstResults[OpName];
2593 if (RNode == 0)
2594 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002595
Chris Lattner6cefb772008-01-05 22:25:12 +00002596 if (i == 0)
2597 Res0Node = RNode;
2598 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2599 if (R == 0)
2600 I->error("Operand $" + OpName + " should be a set destination: all "
2601 "outputs must occur before inputs in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002602
Chris Lattnerc240bb02010-11-01 04:03:32 +00002603 if (CGI.Operands[i].Rec != R)
Chris Lattner6cefb772008-01-05 22:25:12 +00002604 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002605
Chris Lattner6cefb772008-01-05 22:25:12 +00002606 // Remember the return type.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002607 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002608
Chris Lattner6cefb772008-01-05 22:25:12 +00002609 // Okay, this one checks out.
2610 InstResults.erase(OpName);
2611 }
2612
2613 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2614 // the copy while we're checking the inputs.
2615 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2616
2617 std::vector<TreePatternNode*> ResultNodeOperands;
2618 std::vector<Record*> Operands;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002619 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2620 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner6cefb772008-01-05 22:25:12 +00002621 const std::string &OpName = Op.Name;
2622 if (OpName.empty())
2623 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2624
2625 if (!InstInputsCheck.count(OpName)) {
2626 // If this is an predicate operand or optional def operand with an
2627 // DefaultOps set filled in, we can ignore this. When we codegen it,
2628 // we will do so as always executed.
2629 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2630 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2631 // Does it have a non-empty DefaultOps field? If so, ignore this
2632 // operand.
2633 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2634 continue;
2635 }
2636 I->error("Operand $" + OpName +
2637 " does not appear in the instruction pattern");
2638 }
2639 TreePatternNode *InVal = InstInputsCheck[OpName];
2640 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002641
Chris Lattner6cefb772008-01-05 22:25:12 +00002642 if (InVal->isLeaf() &&
2643 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2644 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2645 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2646 I->error("Operand $" + OpName + "'s register class disagrees"
2647 " between the operand and pattern");
2648 }
2649 Operands.push_back(Op.Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002650
Chris Lattner6cefb772008-01-05 22:25:12 +00002651 // Construct the result for the dest-pattern operand list.
2652 TreePatternNode *OpNode = InVal->clone();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002653
Chris Lattner6cefb772008-01-05 22:25:12 +00002654 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002655 OpNode->clearPredicateFns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002656
Chris Lattner6cefb772008-01-05 22:25:12 +00002657 // Promote the xform function to be an explicit node if set.
2658 if (Record *Xform = OpNode->getTransformFn()) {
2659 OpNode->setTransformFn(0);
2660 std::vector<TreePatternNode*> Children;
2661 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002662 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002663 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002664
Chris Lattner6cefb772008-01-05 22:25:12 +00002665 ResultNodeOperands.push_back(OpNode);
2666 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002667
Chris Lattner6cefb772008-01-05 22:25:12 +00002668 if (!InstInputsCheck.empty())
2669 I->error("Input operand $" + InstInputsCheck.begin()->first +
2670 " occurs in pattern but not in operands list!");
2671
2672 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002673 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2674 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002675 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002676 for (unsigned i = 0; i != NumResults; ++i)
2677 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002678
2679 // Create and insert the instruction.
Chris Lattneracfb70f2010-04-20 06:30:25 +00002680 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner62bcec82010-04-20 06:28:43 +00002681 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002682 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2683
2684 // Use a temporary tree pattern to infer all types and make sure that the
2685 // constructed result is correct. This depends on the instruction already
2686 // being inserted into the Instructions map.
2687 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002688 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002689
2690 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2691 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002692
Chris Lattner6cefb772008-01-05 22:25:12 +00002693 DEBUG(I->dump());
2694 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002695
Chris Lattner6cefb772008-01-05 22:25:12 +00002696 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002697 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2698 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002699 E = Instructions.end(); II != E; ++II) {
2700 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002701 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002702 if (I == 0) continue; // No pattern.
2703
2704 // FIXME: Assume only the first tree is the pattern. The others are clobber
2705 // nodes.
2706 TreePatternNode *Pattern = I->getTree(0);
2707 TreePatternNode *SrcPattern;
2708 if (Pattern->getOperator()->getName() == "set") {
2709 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2710 } else{
2711 // Not a set (store or something?)
2712 SrcPattern = Pattern;
2713 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002714
Chris Lattner6cefb772008-01-05 22:25:12 +00002715 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002716 AddPatternToMatch(I,
Jim Grosbach997759a2010-12-07 23:05:49 +00002717 PatternToMatch(Instr,
2718 Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002719 SrcPattern,
2720 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002721 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002722 Instr->getValueAsInt("AddedComplexity"),
2723 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002724 }
2725}
2726
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002727
2728typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2729
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002730static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002731 std::map<std::string, NameRecord> &Names,
2732 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002733 if (!P->getName().empty()) {
2734 NameRecord &Rec = Names[P->getName()];
2735 // If this is the first instance of the name, remember the node.
2736 if (Rec.second++ == 0)
2737 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002738 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002739 PatternTop->error("repetition of value: $" + P->getName() +
2740 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002741 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002742
Chris Lattner967d54a2010-02-23 06:35:45 +00002743 if (!P->isLeaf()) {
2744 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002745 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002746 }
2747}
2748
Chris Lattner25b6f912010-02-23 06:16:51 +00002749void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2750 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002751 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002752 std::string Reason;
2753 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002754 Pattern->error("Pattern can never match: " + Reason);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002755
Chris Lattner405f1252010-03-01 22:29:19 +00002756 // If the source pattern's root is a complex pattern, that complex pattern
2757 // must specify the nodes it can potentially match.
2758 if (const ComplexPattern *CP =
2759 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2760 if (CP->getRootNodes().empty())
2761 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2762 " could match");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002763
2764
Chris Lattner967d54a2010-02-23 06:35:45 +00002765 // Find all of the named values in the input and output, ensure they have the
2766 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002767 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002768 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2769 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002770
2771 // Scan all of the named values in the destination pattern, rejecting them if
2772 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002773 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002774 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002775 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002776 Pattern->error("Pattern has input without matching name in output: $" +
2777 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002778 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002779
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002780 // Scan all of the named values in the source pattern, rejecting them if the
2781 // name isn't used in the dest, and isn't used to tie two values together.
2782 for (std::map<std::string, NameRecord>::iterator
2783 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2784 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2785 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002786
Chris Lattner25b6f912010-02-23 06:16:51 +00002787 PatternsToMatch.push_back(PTM);
2788}
2789
2790
Dan Gohmanee4fa192008-04-03 00:02:49 +00002791
2792void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002793 const std::vector<const CodeGenInstruction*> &Instructions =
2794 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002795 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2796 CodeGenInstruction &InstInfo =
2797 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002798 // Determine properties of the instruction from its pattern.
Evan Cheng0f040a22011-03-15 05:09:26 +00002799 bool MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic;
2800 InferFromPattern(InstInfo, MayStore, MayLoad, IsBitcast,
2801 HasSideEffects, IsVariadic, *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002802 InstInfo.mayStore = MayStore;
2803 InstInfo.mayLoad = MayLoad;
Evan Cheng0f040a22011-03-15 05:09:26 +00002804 InstInfo.isBitcast = IsBitcast;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002805 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002806 InstInfo.Operands.isVariadic = IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002807 }
2808}
2809
Chris Lattner2cacec52010-03-15 06:00:16 +00002810/// Given a pattern result with an unresolved type, see if we can find one
2811/// instruction with an unresolved result type. Force this result type to an
2812/// arbitrary element if it's possible types to converge results.
2813static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2814 if (N->isLeaf())
2815 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002816
Chris Lattner2cacec52010-03-15 06:00:16 +00002817 // Analyze children.
2818 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2819 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2820 return true;
2821
2822 if (!N->getOperator()->isSubClassOf("Instruction"))
2823 return false;
2824
2825 // If this type is already concrete or completely unknown we can't do
2826 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00002827 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2828 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2829 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002830
Chris Lattnerd7349192010-03-19 21:37:09 +00002831 // Otherwise, force its type to the first possibility (an arbitrary choice).
2832 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2833 return true;
2834 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002835
Chris Lattnerd7349192010-03-19 21:37:09 +00002836 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00002837}
2838
Chris Lattnerfe718932008-01-06 01:10:31 +00002839void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002840 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2841
2842 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002843 Record *CurPattern = Patterns[i];
2844 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Chris Lattner310adf12010-03-27 02:53:27 +00002845 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002846
2847 // Inline pattern fragments into it.
2848 Pattern->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002849
Chris Lattnerd7349192010-03-19 21:37:09 +00002850 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00002851 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002852
Chris Lattner6cefb772008-01-05 22:25:12 +00002853 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00002854 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002855
Chris Lattner6cefb772008-01-05 22:25:12 +00002856 // Inline pattern fragments into it.
2857 Result->InlinePatternFragments();
2858
2859 if (Result->getNumTrees() != 1)
2860 Result->error("Cannot handle instructions producing instructions "
2861 "with temporaries yet!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002862
Chris Lattner6cefb772008-01-05 22:25:12 +00002863 bool IterateInference;
2864 bool InferredAllPatternTypes, InferredAllResultTypes;
2865 do {
2866 // Infer as many types as possible. If we cannot infer all of them, we
2867 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002868 InferredAllPatternTypes =
2869 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002870
Chris Lattner6cefb772008-01-05 22:25:12 +00002871 // Infer as many types as possible. If we cannot infer all of them, we
2872 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002873 InferredAllResultTypes =
2874 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002875
Chris Lattner6c6ba362010-03-18 23:15:10 +00002876 IterateInference = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002877
Chris Lattner6cefb772008-01-05 22:25:12 +00002878 // Apply the type of the result to the source pattern. This helps us
2879 // resolve cases where the input type is known to be a pointer type (which
2880 // is considered resolved), but the result knows it needs to be 32- or
2881 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00002882 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2883 Pattern->getTree(0)->getNumTypes());
2884 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00002885 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002886 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002887 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002888 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002889 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002890
Chris Lattner2cacec52010-03-15 06:00:16 +00002891 // If our iteration has converged and the input pattern's types are fully
2892 // resolved but the result pattern is not fully resolved, we may have a
2893 // situation where we have two instructions in the result pattern and
2894 // the instructions require a common register class, but don't care about
2895 // what actual MVT is used. This is actually a bug in our modelling:
2896 // output patterns should have register classes, not MVTs.
2897 //
2898 // In any case, to handle this, we just go through and disambiguate some
2899 // arbitrary types to the result pattern's nodes.
2900 if (!IterateInference && InferredAllPatternTypes &&
2901 !InferredAllResultTypes)
2902 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2903 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002904 } while (IterateInference);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002905
Chris Lattner6cefb772008-01-05 22:25:12 +00002906 // Verify that we inferred enough types that we can do something with the
2907 // pattern and result. If these fire the user has to add type casts.
2908 if (!InferredAllPatternTypes)
2909 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002910 if (!InferredAllResultTypes) {
2911 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002912 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002913 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002914
Chris Lattner6cefb772008-01-05 22:25:12 +00002915 // Validate that the input pattern is correct.
2916 std::map<std::string, TreePatternNode*> InstInputs;
2917 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00002918 std::vector<Record*> InstImpResults;
2919 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2920 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2921 InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002922 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002923
2924 // Promote the xform function to be an explicit node if set.
2925 TreePatternNode *DstPattern = Result->getOnlyTree();
2926 std::vector<TreePatternNode*> ResultNodeOperands;
2927 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2928 TreePatternNode *OpNode = DstPattern->getChild(ii);
2929 if (Record *Xform = OpNode->getTransformFn()) {
2930 OpNode->setTransformFn(0);
2931 std::vector<TreePatternNode*> Children;
2932 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002933 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002934 }
2935 ResultNodeOperands.push_back(OpNode);
2936 }
2937 DstPattern = Result->getOnlyTree();
2938 if (!DstPattern->isLeaf())
2939 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00002940 ResultNodeOperands,
2941 DstPattern->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002942
Chris Lattnerd7349192010-03-19 21:37:09 +00002943 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2944 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002945
Chris Lattner6cefb772008-01-05 22:25:12 +00002946 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2947 Temp.InferAllTypes();
2948
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002949
Chris Lattner25b6f912010-02-23 06:16:51 +00002950 AddPatternToMatch(Pattern,
Jim Grosbach997759a2010-12-07 23:05:49 +00002951 PatternToMatch(CurPattern,
2952 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerd7349192010-03-19 21:37:09 +00002953 Pattern->getTree(0),
2954 Temp.getOnlyTree(), InstImpResults,
2955 CurPattern->getValueAsInt("AddedComplexity"),
2956 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002957 }
2958}
2959
2960/// CombineChildVariants - Given a bunch of permutations of each child of the
2961/// 'operator' node, put them together in all possible ways.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002962static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00002963 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2964 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002965 CodeGenDAGPatterns &CDP,
2966 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002967 // Make sure that each operand has at least one variant to choose from.
2968 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2969 if (ChildVariants[i].empty())
2970 return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002971
Chris Lattner6cefb772008-01-05 22:25:12 +00002972 // The end result is an all-pairs construction of the resultant pattern.
2973 std::vector<unsigned> Idxs;
2974 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002975 bool NotDone;
2976 do {
2977#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002978 DEBUG(if (!Idxs.empty()) {
2979 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2980 for (unsigned i = 0; i < Idxs.size(); ++i) {
2981 errs() << Idxs[i] << " ";
2982 }
2983 errs() << "]\n";
2984 });
Scott Michel327d0652008-03-05 17:49:05 +00002985#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002986 // Create the variant and add it to the output list.
2987 std::vector<TreePatternNode*> NewChildren;
2988 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2989 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00002990 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2991 Orig->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002992
Chris Lattner6cefb772008-01-05 22:25:12 +00002993 // Copy over properties.
2994 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002995 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002996 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00002997 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2998 R->setType(i, Orig->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002999
Scott Michel327d0652008-03-05 17:49:05 +00003000 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00003001 std::string ErrString;
3002 if (!R->canPatternMatch(ErrString, CDP)) {
3003 delete R;
3004 } else {
3005 bool AlreadyExists = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003006
Chris Lattner6cefb772008-01-05 22:25:12 +00003007 // Scan to see if this pattern has already been emitted. We can get
3008 // duplication due to things like commuting:
3009 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3010 // which are the same pattern. Ignore the dups.
3011 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003012 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003013 AlreadyExists = true;
3014 break;
3015 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003016
Chris Lattner6cefb772008-01-05 22:25:12 +00003017 if (AlreadyExists)
3018 delete R;
3019 else
3020 OutVariants.push_back(R);
3021 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003022
Scott Michel327d0652008-03-05 17:49:05 +00003023 // Increment indices to the next permutation by incrementing the
3024 // indicies from last index backward, e.g., generate the sequence
3025 // [0, 0], [0, 1], [1, 0], [1, 1].
3026 int IdxsIdx;
3027 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3028 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3029 Idxs[IdxsIdx] = 0;
3030 else
Chris Lattner6cefb772008-01-05 22:25:12 +00003031 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00003032 }
Scott Michel327d0652008-03-05 17:49:05 +00003033 NotDone = (IdxsIdx >= 0);
3034 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00003035}
3036
3037/// CombineChildVariants - A helper function for binary operators.
3038///
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003039static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00003040 const std::vector<TreePatternNode*> &LHS,
3041 const std::vector<TreePatternNode*> &RHS,
3042 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003043 CodeGenDAGPatterns &CDP,
3044 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003045 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3046 ChildVariants.push_back(LHS);
3047 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00003048 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003049}
Chris Lattner6cefb772008-01-05 22:25:12 +00003050
3051
3052static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3053 std::vector<TreePatternNode *> &Children) {
3054 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3055 Record *Operator = N->getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003056
Chris Lattner6cefb772008-01-05 22:25:12 +00003057 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00003058 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00003059 N->getTransformFn()) {
3060 Children.push_back(N);
3061 return;
3062 }
3063
3064 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3065 Children.push_back(N->getChild(0));
3066 else
3067 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3068
3069 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3070 Children.push_back(N->getChild(1));
3071 else
3072 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3073}
3074
3075/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3076/// the (potentially recursive) pattern by using algebraic laws.
3077///
3078static void GenerateVariantsOf(TreePatternNode *N,
3079 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003080 CodeGenDAGPatterns &CDP,
3081 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003082 // We cannot permute leaves.
3083 if (N->isLeaf()) {
3084 OutVariants.push_back(N);
3085 return;
3086 }
3087
3088 // Look up interesting info about the node.
3089 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3090
Jim Grosbachda4231f2009-03-26 16:17:51 +00003091 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00003092 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003093 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00003094 std::vector<TreePatternNode*> MaximalChildren;
3095 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3096
3097 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3098 // permutations.
3099 if (MaximalChildren.size() == 3) {
3100 // Find the variants of all of our maximal children.
3101 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003102 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3103 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3104 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003105
Chris Lattner6cefb772008-01-05 22:25:12 +00003106 // There are only two ways we can permute the tree:
3107 // (A op B) op C and A op (B op C)
3108 // Within these forms, we can also permute A/B/C.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003109
Chris Lattner6cefb772008-01-05 22:25:12 +00003110 // Generate legal pair permutations of A/B/C.
3111 std::vector<TreePatternNode*> ABVariants;
3112 std::vector<TreePatternNode*> BAVariants;
3113 std::vector<TreePatternNode*> ACVariants;
3114 std::vector<TreePatternNode*> CAVariants;
3115 std::vector<TreePatternNode*> BCVariants;
3116 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003117 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3118 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3119 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3120 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3121 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3122 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003123
3124 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00003125 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3126 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3127 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3128 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3129 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3130 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003131
3132 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00003133 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3134 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3135 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3136 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3137 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3138 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003139 return;
3140 }
3141 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003142
Chris Lattner6cefb772008-01-05 22:25:12 +00003143 // Compute permutations of all children.
3144 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3145 ChildVariants.resize(N->getNumChildren());
3146 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003147 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003148
3149 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00003150 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003151
3152 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003153 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3154 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3155 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3156 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003157 // Don't count children which are actually register references.
3158 unsigned NC = 0;
3159 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3160 TreePatternNode *Child = N->getChild(i);
3161 if (Child->isLeaf())
3162 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
3163 Record *RR = DI->getDef();
3164 if (RR->isSubClassOf("Register"))
3165 continue;
3166 }
3167 NC++;
3168 }
3169 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003170 if (isCommIntrinsic) {
3171 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3172 // operands are the commutative operands, and there might be more operands
3173 // after those.
3174 assert(NC >= 3 &&
3175 "Commutative intrinsic should have at least 3 childrean!");
3176 std::vector<std::vector<TreePatternNode*> > Variants;
3177 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3178 Variants.push_back(ChildVariants[2]);
3179 Variants.push_back(ChildVariants[1]);
3180 for (unsigned i = 3; i != NC; ++i)
3181 Variants.push_back(ChildVariants[i]);
3182 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3183 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00003184 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00003185 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003186 }
3187}
3188
3189
3190// GenerateVariants - Generate variants. For example, commutative patterns can
3191// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00003192void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00003193 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003194
Chris Lattner6cefb772008-01-05 22:25:12 +00003195 // Loop over all of the patterns we've collected, checking to see if we can
3196 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00003197 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00003198 // the .td file having to contain tons of variants of instructions.
3199 //
3200 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3201 // intentionally do not reconsider these. Any variants of added patterns have
3202 // already been added.
3203 //
3204 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00003205 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00003206 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00003207 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00003208 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00003209 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00003210 DEBUG(errs() << "\n");
Jim Grosbachbb168242010-10-08 18:13:57 +00003211 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3212 DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003213
3214 assert(!Variants.empty() && "Must create at least original variant!");
3215 Variants.erase(Variants.begin()); // Remove the original pattern.
3216
3217 if (Variants.empty()) // No variants for this pattern.
3218 continue;
3219
Chris Lattner569f1212009-08-23 04:44:11 +00003220 DEBUG(errs() << "FOUND VARIANTS OF: ";
3221 PatternsToMatch[i].getSrcPattern()->dump();
3222 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003223
3224 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3225 TreePatternNode *Variant = Variants[v];
3226
Chris Lattner569f1212009-08-23 04:44:11 +00003227 DEBUG(errs() << " VAR#" << v << ": ";
3228 Variant->dump();
3229 errs() << "\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003230
Chris Lattner6cefb772008-01-05 22:25:12 +00003231 // Scan to see if an instruction or explicit pattern already matches this.
3232 bool AlreadyExists = false;
3233 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00003234 // Skip if the top level predicates do not match.
3235 if (PatternsToMatch[i].getPredicates() !=
3236 PatternsToMatch[p].getPredicates())
3237 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00003238 // Check to see if this variant already exists.
Jim Grosbachbb168242010-10-08 18:13:57 +00003239 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3240 DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00003241 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003242 AlreadyExists = true;
3243 break;
3244 }
3245 }
3246 // If we already have it, ignore the variant.
3247 if (AlreadyExists) continue;
3248
3249 // Otherwise, add it to the list of patterns we have.
3250 PatternsToMatch.
Jim Grosbach997759a2010-12-07 23:05:49 +00003251 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3252 PatternsToMatch[i].getPredicates(),
Chris Lattner6cefb772008-01-05 22:25:12 +00003253 Variant, PatternsToMatch[i].getDstPattern(),
3254 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00003255 PatternsToMatch[i].getAddedComplexity(),
3256 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003257 }
3258
Chris Lattner569f1212009-08-23 04:44:11 +00003259 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003260 }
3261}
3262