blob: 79cf18a4d755c73b19b0b9205ea12c854575b751 [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
583namespace {
584void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
585 if (N->isLeaf()) {
586 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
587 DepMap[N->getName()]++;
588 }
589 } else {
590 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
591 FindDepVarsOf(N->getChild(i), DepMap);
592 }
593}
594
595//! Find dependent variables within child patterns
596/*!
597 */
598void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
599 DepVarMap depcounts;
600 FindDepVarsOf(N, depcounts);
601 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
602 if (i->second > 1) { // std::pair<std::string, int>
603 DepVars.insert(i->first);
604 }
605 }
606}
607
608//! Dump the dependent variable set:
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000609#ifndef NDEBUG
Scott Michel327d0652008-03-05 17:49:05 +0000610void DumpDepVars(MultipleUseVarSet &DepVars) {
611 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000612 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000613 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000614 DEBUG(errs() << "[ ");
Jim Grosbachbb168242010-10-08 18:13:57 +0000615 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
616 e = DepVars.end(); i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000617 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000618 }
Chris Lattner569f1212009-08-23 04:44:11 +0000619 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000620 }
621}
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000622#endif
623
Scott Michel327d0652008-03-05 17:49:05 +0000624}
625
Chris Lattner6cefb772008-01-05 22:25:12 +0000626//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000627// PatternToMatch implementation
628//
629
Chris Lattner48e86db2010-03-29 01:40:38 +0000630
631/// getPatternSize - Return the 'size' of this pattern. We want to match large
632/// patterns before small ones. This is used to determine the size of a
633/// pattern.
634static unsigned getPatternSize(const TreePatternNode *P,
635 const CodeGenDAGPatterns &CGP) {
636 unsigned Size = 3; // The node itself.
637 // If the root node is a ConstantSDNode, increases its size.
638 // e.g. (set R32:$dst, 0).
639 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
640 Size += 2;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000641
Chris Lattner48e86db2010-03-29 01:40:38 +0000642 // FIXME: This is a hack to statically increase the priority of patterns
643 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
644 // Later we can allow complexity / cost for each pattern to be (optionally)
645 // specified. To get best possible pattern match we'll need to dynamically
646 // calculate the complexity of all patterns a dag can potentially map to.
647 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
648 if (AM)
649 Size += AM->getNumOperands() * 3;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000650
Chris Lattner48e86db2010-03-29 01:40:38 +0000651 // If this node has some predicate function that must match, it adds to the
652 // complexity of this node.
653 if (!P->getPredicateFns().empty())
654 ++Size;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000655
Chris Lattner48e86db2010-03-29 01:40:38 +0000656 // Count children in the count if they are also nodes.
657 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
658 TreePatternNode *Child = P->getChild(i);
659 if (!Child->isLeaf() && Child->getNumTypes() &&
660 Child->getType(0) != MVT::Other)
661 Size += getPatternSize(Child, CGP);
662 else if (Child->isLeaf()) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000663 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000664 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
665 else if (Child->getComplexPatternInfo(CGP))
666 Size += getPatternSize(Child, CGP);
667 else if (!Child->getPredicateFns().empty())
668 ++Size;
669 }
670 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000671
Chris Lattner48e86db2010-03-29 01:40:38 +0000672 return Size;
673}
674
675/// Compute the complexity metric for the input pattern. This roughly
676/// corresponds to the number of nodes that are covered.
677unsigned PatternToMatch::
678getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
679 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
680}
681
682
Dan Gohman22bb3112008-08-22 00:20:26 +0000683/// getPredicateCheck - Return a single string containing all of this
684/// pattern's predicates concatenated with "&&" operators.
685///
686std::string PatternToMatch::getPredicateCheck() const {
687 std::string PredicateCheck;
688 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
689 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
690 Record *Def = Pred->getDef();
691 if (!Def->isSubClassOf("Predicate")) {
692#ifndef NDEBUG
693 Def->dump();
694#endif
695 assert(0 && "Unknown predicate type!");
696 }
697 if (!PredicateCheck.empty())
698 PredicateCheck += " && ";
699 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
700 }
701 }
702
703 return PredicateCheck;
704}
705
706//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000707// SDTypeConstraint implementation
708//
709
710SDTypeConstraint::SDTypeConstraint(Record *R) {
711 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000712
Chris Lattner6cefb772008-01-05 22:25:12 +0000713 if (R->isSubClassOf("SDTCisVT")) {
714 ConstraintType = SDTCisVT;
715 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerc8122612010-03-28 06:04:39 +0000716 if (x.SDTCisVT_Info.VT == MVT::isVoid)
717 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000718
Chris Lattner6cefb772008-01-05 22:25:12 +0000719 } else if (R->isSubClassOf("SDTCisPtrTy")) {
720 ConstraintType = SDTCisPtrTy;
721 } else if (R->isSubClassOf("SDTCisInt")) {
722 ConstraintType = SDTCisInt;
723 } else if (R->isSubClassOf("SDTCisFP")) {
724 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000725 } else if (R->isSubClassOf("SDTCisVec")) {
726 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000727 } else if (R->isSubClassOf("SDTCisSameAs")) {
728 ConstraintType = SDTCisSameAs;
729 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
730 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
731 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000732 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000733 R->getValueAsInt("OtherOperandNum");
734 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
735 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000736 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000737 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000738 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
739 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000740 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene60322692011-01-24 20:53:18 +0000741 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
742 ConstraintType = SDTCisSubVecOfVec;
743 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
744 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000745 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000746 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000747 exit(1);
748 }
749}
750
751/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000752/// N, and the result number in ResNo.
753static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
754 const SDNodeInfo &NodeInfo,
755 unsigned &ResNo) {
756 unsigned NumResults = NodeInfo.getNumResults();
757 if (OpNo < NumResults) {
758 ResNo = OpNo;
759 return N;
760 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000761
Chris Lattner2e68a022010-03-19 21:56:21 +0000762 OpNo -= NumResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000763
Chris Lattner2e68a022010-03-19 21:56:21 +0000764 if (OpNo >= N->getNumChildren()) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000765 errs() << "Invalid operand number in type constraint "
Chris Lattner2e68a022010-03-19 21:56:21 +0000766 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000767 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000768 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000769 exit(1);
770 }
771
Chris Lattner2e68a022010-03-19 21:56:21 +0000772 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000773}
774
775/// ApplyTypeConstraint - Given a node in a pattern, apply this type
776/// constraint to the nodes operands. This returns true if it makes a
777/// change, false otherwise. If a type contradiction is found, throw an
778/// exception.
779bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
780 const SDNodeInfo &NodeInfo,
781 TreePattern &TP) const {
Chris Lattner2e68a022010-03-19 21:56:21 +0000782 unsigned ResNo = 0; // The result number being referenced.
783 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000784
Chris Lattner6cefb772008-01-05 22:25:12 +0000785 switch (ConstraintType) {
786 default: assert(0 && "Unknown constraint type!");
787 case SDTCisVT:
788 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000789 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000790 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000791 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000792 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000793 case SDTCisInt:
794 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000795 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000796 case SDTCisFP:
797 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000798 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000799 case SDTCisVec:
800 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000801 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000802 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000803 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000804 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000805 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000806 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
807 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000808 }
809 case SDTCisVTSmallerThanOp: {
810 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
811 // have an integer type that is smaller than the VT.
812 if (!NodeToApply->isLeaf() ||
813 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
814 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
815 ->isSubClassOf("ValueType"))
816 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000817 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000818 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000819
Chris Lattnercc878302010-03-24 00:06:46 +0000820 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000821
Chris Lattner2e68a022010-03-19 21:56:21 +0000822 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000823 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000824 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
825 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000826
Chris Lattnercc878302010-03-24 00:06:46 +0000827 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000828 }
829 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000830 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000831 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000832 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
833 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000834 return NodeToApply->getExtType(ResNo).
835 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000836 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000837 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000838 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000839 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000840 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
841 VResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000842
Chris Lattner66fb9d22010-03-24 00:01:16 +0000843 // Filter vector types out of VecOperand that don't have the right element
844 // type.
845 return VecOperand->getExtType(VResNo).
846 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000847 }
David Greene60322692011-01-24 20:53:18 +0000848 case SDTCisSubVecOfVec: {
849 unsigned VResNo = 0;
850 TreePatternNode *BigVecOperand =
851 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
852 VResNo);
853
854 // Filter vector types out of BigVecOperand that don't have the
855 // right subvector type.
856 return BigVecOperand->getExtType(VResNo).
857 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
858 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000859 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000860 return false;
861}
862
863//===----------------------------------------------------------------------===//
864// SDNodeInfo implementation
865//
866SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
867 EnumName = R->getValueAsString("Opcode");
868 SDClassName = R->getValueAsString("SDClass");
869 Record *TypeProfile = R->getValueAsDef("TypeProfile");
870 NumResults = TypeProfile->getValueAsInt("NumResults");
871 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000872
Chris Lattner6cefb772008-01-05 22:25:12 +0000873 // Parse the properties.
874 Properties = 0;
875 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
876 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
877 if (PropList[i]->getName() == "SDNPCommutative") {
878 Properties |= 1 << SDNPCommutative;
879 } else if (PropList[i]->getName() == "SDNPAssociative") {
880 Properties |= 1 << SDNPAssociative;
881 } else if (PropList[i]->getName() == "SDNPHasChain") {
882 Properties |= 1 << SDNPHasChain;
Chris Lattner036609b2010-12-23 18:28:41 +0000883 } else if (PropList[i]->getName() == "SDNPOutGlue") {
884 Properties |= 1 << SDNPOutGlue;
885 } else if (PropList[i]->getName() == "SDNPInGlue") {
886 Properties |= 1 << SDNPInGlue;
887 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
888 Properties |= 1 << SDNPOptInGlue;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000889 } else if (PropList[i]->getName() == "SDNPMayStore") {
890 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000891 } else if (PropList[i]->getName() == "SDNPMayLoad") {
892 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000893 } else if (PropList[i]->getName() == "SDNPSideEffect") {
894 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000895 } else if (PropList[i]->getName() == "SDNPMemOperand") {
896 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000897 } else if (PropList[i]->getName() == "SDNPVariadic") {
898 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000899 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000900 errs() << "Unknown SD Node property '" << PropList[i]->getName()
901 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000902 exit(1);
903 }
904 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000905
906
Chris Lattner6cefb772008-01-05 22:25:12 +0000907 // Parse the type constraints.
908 std::vector<Record*> ConstraintList =
909 TypeProfile->getValueAsListOfDefs("Constraints");
910 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
911}
912
Chris Lattner22579812010-02-28 00:22:30 +0000913/// getKnownType - If the type constraints on this node imply a fixed type
914/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000915/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000916MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +0000917 unsigned NumResults = getNumResults();
918 assert(NumResults <= 1 &&
919 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +0000920 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000921
Chris Lattner22579812010-02-28 00:22:30 +0000922 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
923 // Make sure that this applies to the correct node result.
924 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
925 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000926
Chris Lattner22579812010-02-28 00:22:30 +0000927 switch (TypeConstraints[i].ConstraintType) {
928 default: break;
929 case SDTypeConstraint::SDTCisVT:
930 return TypeConstraints[i].x.SDTCisVT_Info.VT;
931 case SDTypeConstraint::SDTCisPtrTy:
932 return MVT::iPTR;
933 }
934 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000935 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000936}
937
Chris Lattner6cefb772008-01-05 22:25:12 +0000938//===----------------------------------------------------------------------===//
939// TreePatternNode implementation
940//
941
942TreePatternNode::~TreePatternNode() {
943#if 0 // FIXME: implement refcounted tree nodes!
944 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
945 delete getChild(i);
946#endif
947}
948
Chris Lattnerd7349192010-03-19 21:37:09 +0000949static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
950 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +0000951 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +0000952 return 0; // All return nothing.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000953
Chris Lattner93dc92e2010-03-22 20:56:36 +0000954 if (Operator->isSubClassOf("Intrinsic"))
955 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000956
Chris Lattnerd7349192010-03-19 21:37:09 +0000957 if (Operator->isSubClassOf("SDNode"))
958 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000959
Chris Lattnerd7349192010-03-19 21:37:09 +0000960 if (Operator->isSubClassOf("PatFrag")) {
961 // If we've already parsed this pattern fragment, get it. Otherwise, handle
962 // the forward reference case where one pattern fragment references another
963 // before it is processed.
964 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
965 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000966
Chris Lattnerd7349192010-03-19 21:37:09 +0000967 // Get the result tree.
968 DagInit *Tree = Operator->getValueAsDag("Fragment");
969 Record *Op = 0;
970 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
971 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
972 assert(Op && "Invalid Fragment");
973 return GetNumNodeResults(Op, CDP);
974 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000975
Chris Lattnerd7349192010-03-19 21:37:09 +0000976 if (Operator->isSubClassOf("Instruction")) {
977 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +0000978
979 // FIXME: Should allow access to all the results here.
Chris Lattnerc240bb02010-11-01 04:03:32 +0000980 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000981
Chris Lattner9414ae52010-03-27 20:09:24 +0000982 // Add on one implicit def if it has a resolvable type.
983 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
984 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +0000985 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +0000986 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000987
Chris Lattnerd7349192010-03-19 21:37:09 +0000988 if (Operator->isSubClassOf("SDNodeXForm"))
989 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000990
Chris Lattnerd7349192010-03-19 21:37:09 +0000991 Operator->dump();
992 errs() << "Unhandled node in GetNumNodeResults\n";
993 exit(1);
994}
995
996void TreePatternNode::print(raw_ostream &OS) const {
997 if (isLeaf())
998 OS << *getLeafValue();
999 else
1000 OS << '(' << getOperator()->getName();
1001
1002 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1003 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +00001004
1005 if (!isLeaf()) {
1006 if (getNumChildren() != 0) {
1007 OS << " ";
1008 getChild(0)->print(OS);
1009 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1010 OS << ", ";
1011 getChild(i)->print(OS);
1012 }
1013 }
1014 OS << ")";
1015 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001016
Dan Gohman0540e172008-10-15 06:17:21 +00001017 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
1018 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +00001019 if (TransformFn)
1020 OS << "<<X:" << TransformFn->getName() << ">>";
1021 if (!getName().empty())
1022 OS << ":$" << getName();
1023
1024}
1025void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001026 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +00001027}
1028
Scott Michel327d0652008-03-05 17:49:05 +00001029/// isIsomorphicTo - Return true if this node is recursively
1030/// isomorphic to the specified node. For this comparison, the node's
1031/// entire state is considered. The assigned name is ignored, since
1032/// nodes with differing names are considered isomorphic. However, if
1033/// the assigned name is present in the dependent variable set, then
1034/// the assigned name is considered significant and the node is
1035/// isomorphic if the names match.
1036bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1037 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001038 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +00001039 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +00001040 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00001041 getTransformFn() != N->getTransformFn())
1042 return false;
1043
1044 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +00001045 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1046 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +00001047 return ((DI->getDef() == NDI->getDef())
1048 && (DepVars.find(getName()) == DepVars.end()
1049 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +00001050 }
1051 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001052 return getLeafValue() == N->getLeafValue();
1053 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001054
Chris Lattner6cefb772008-01-05 22:25:12 +00001055 if (N->getOperator() != getOperator() ||
1056 N->getNumChildren() != getNumChildren()) return false;
1057 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00001058 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +00001059 return false;
1060 return true;
1061}
1062
1063/// clone - Make a copy of this tree and all of its children.
1064///
1065TreePatternNode *TreePatternNode::clone() const {
1066 TreePatternNode *New;
1067 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001068 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001069 } else {
1070 std::vector<TreePatternNode*> CChildren;
1071 CChildren.reserve(Children.size());
1072 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1073 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +00001074 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001075 }
1076 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001077 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +00001078 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00001079 New->setTransformFn(getTransformFn());
1080 return New;
1081}
1082
Chris Lattner47661322010-02-14 22:22:58 +00001083/// RemoveAllTypes - Recursively strip all the types of this tree.
1084void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +00001085 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1086 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +00001087 if (isLeaf()) return;
1088 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1089 getChild(i)->RemoveAllTypes();
1090}
1091
1092
Chris Lattner6cefb772008-01-05 22:25:12 +00001093/// SubstituteFormalArguments - Replace the formal arguments in this tree
1094/// with actual values specified by ArgMap.
1095void TreePatternNode::
1096SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1097 if (isLeaf()) return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001098
Chris Lattner6cefb772008-01-05 22:25:12 +00001099 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1100 TreePatternNode *Child = getChild(i);
1101 if (Child->isLeaf()) {
1102 Init *Val = Child->getLeafValue();
1103 if (dynamic_cast<DefInit*>(Val) &&
1104 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
1105 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +00001106 TreePatternNode *NewChild = ArgMap[Child->getName()];
1107 assert(NewChild && "Couldn't find formal argument!");
1108 assert((Child->getPredicateFns().empty() ||
1109 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1110 "Non-empty child predicate clobbered!");
1111 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +00001112 }
1113 } else {
1114 getChild(i)->SubstituteFormalArguments(ArgMap);
1115 }
1116 }
1117}
1118
1119
1120/// InlinePatternFragments - If this pattern refers to any pattern
1121/// fragments, inline them into place, giving us a pattern without any
1122/// PatFrag references.
1123TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1124 if (isLeaf()) return this; // nothing to do.
1125 Record *Op = getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001126
Chris Lattner6cefb772008-01-05 22:25:12 +00001127 if (!Op->isSubClassOf("PatFrag")) {
1128 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00001129 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1130 TreePatternNode *Child = getChild(i);
1131 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1132
1133 assert((Child->getPredicateFns().empty() ||
1134 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1135 "Non-empty child predicate clobbered!");
1136
1137 setChild(i, NewChild);
1138 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001139 return this;
1140 }
1141
1142 // Otherwise, we found a reference to a fragment. First, look up its
1143 // TreePattern record.
1144 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001145
Chris Lattner6cefb772008-01-05 22:25:12 +00001146 // Verify that we are passing the right number of operands.
1147 if (Frag->getNumArgs() != Children.size())
1148 TP.error("'" + Op->getName() + "' fragment requires " +
1149 utostr(Frag->getNumArgs()) + " operands!");
1150
1151 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1152
Dan Gohman0540e172008-10-15 06:17:21 +00001153 std::string Code = Op->getValueAsCode("Predicate");
1154 if (!Code.empty())
1155 FragTree->addPredicateFn("Predicate_"+Op->getName());
1156
Chris Lattner6cefb772008-01-05 22:25:12 +00001157 // Resolve formal arguments to their actual value.
1158 if (Frag->getNumArgs()) {
1159 // Compute the map of formal to actual arguments.
1160 std::map<std::string, TreePatternNode*> ArgMap;
1161 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1162 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001163
Chris Lattner6cefb772008-01-05 22:25:12 +00001164 FragTree->SubstituteFormalArguments(ArgMap);
1165 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001166
Chris Lattner6cefb772008-01-05 22:25:12 +00001167 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001168 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1169 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +00001170
1171 // Transfer in the old predicates.
1172 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1173 FragTree->addPredicateFn(getPredicateFns()[i]);
1174
Chris Lattner6cefb772008-01-05 22:25:12 +00001175 // Get a new copy of this fragment to stitch into here.
1176 //delete this; // FIXME: implement refcounting!
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001177
Chris Lattner2ca698d2008-06-30 03:02:03 +00001178 // The fragment we inlined could have recursive inlining that is needed. See
1179 // if there are any pattern fragments in it and inline them as needed.
1180 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001181}
1182
1183/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +00001184/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +00001185/// references from the register file information, for example.
1186///
Chris Lattnerd7349192010-03-19 21:37:09 +00001187static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1188 bool NotRegisters, TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001189 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00001190 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001191 assert(ResNo == 0 && "Regclass ref only has one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001192 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001193 return EEVT::TypeSet(); // Unknown.
1194 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1195 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001196 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001197
Chris Lattner640a3f52010-03-23 23:50:31 +00001198 if (R->isSubClassOf("PatFrag")) {
1199 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001200 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001201 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001202 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001203
Chris Lattner640a3f52010-03-23 23:50:31 +00001204 if (R->isSubClassOf("Register")) {
1205 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001206 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001207 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001208 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001209 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001210 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00001211
1212 if (R->isSubClassOf("SubRegIndex")) {
1213 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1214 return EEVT::TypeSet();
1215 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001216
Chris Lattner640a3f52010-03-23 23:50:31 +00001217 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1218 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001219 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001220 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001221 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001222
Chris Lattner640a3f52010-03-23 23:50:31 +00001223 if (R->isSubClassOf("ComplexPattern")) {
1224 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001225 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001226 return EEVT::TypeSet(); // Unknown.
1227 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1228 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001229 }
1230 if (R->isSubClassOf("PointerLikeRegClass")) {
1231 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001232 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001233 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001234
Chris Lattner640a3f52010-03-23 23:50:31 +00001235 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1236 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001237 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001238 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001239 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001240
Chris Lattner6cefb772008-01-05 22:25:12 +00001241 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001242 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001243}
1244
Chris Lattnere67bde52008-01-06 05:36:50 +00001245
1246/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1247/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1248const CodeGenIntrinsic *TreePatternNode::
1249getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1250 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1251 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1252 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1253 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001254
1255 unsigned IID =
Chris Lattnere67bde52008-01-06 05:36:50 +00001256 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1257 return &CDP.getIntrinsicInfo(IID);
1258}
1259
Chris Lattner47661322010-02-14 22:22:58 +00001260/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1261/// return the ComplexPattern information, otherwise return null.
1262const ComplexPattern *
1263TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1264 if (!isLeaf()) return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001265
Chris Lattner47661322010-02-14 22:22:58 +00001266 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1267 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1268 return &CGP.getComplexPattern(DI->getDef());
1269 return 0;
1270}
1271
1272/// NodeHasProperty - Return true if this node has the specified property.
1273bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001274 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001275 if (isLeaf()) {
1276 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1277 return CP->hasProperty(Property);
1278 return false;
1279 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001280
Chris Lattner47661322010-02-14 22:22:58 +00001281 Record *Operator = getOperator();
1282 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001283
Chris Lattner47661322010-02-14 22:22:58 +00001284 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1285}
1286
1287
1288
1289
1290/// TreeHasProperty - Return true if any node in this tree has the specified
1291/// property.
1292bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001293 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001294 if (NodeHasProperty(Property, CGP))
1295 return true;
1296 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1297 if (getChild(i)->TreeHasProperty(Property, CGP))
1298 return true;
1299 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001300}
Chris Lattner47661322010-02-14 22:22:58 +00001301
Evan Cheng6bd95672008-06-16 20:29:38 +00001302/// isCommutativeIntrinsic - Return true if the node corresponds to a
1303/// commutative intrinsic.
1304bool
1305TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1306 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1307 return Int->isCommutative;
1308 return false;
1309}
1310
Chris Lattnere67bde52008-01-06 05:36:50 +00001311
Bob Wilson6c01ca92009-01-05 17:23:09 +00001312/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001313/// this node and its children in the tree. This returns true if it makes a
1314/// change, false otherwise. If a type contradiction is found, throw an
1315/// exception.
1316bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001317 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001318 if (isLeaf()) {
1319 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1320 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001321 bool MadeChange = false;
1322 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1323 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1324 NotRegisters, TP), TP);
1325 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001326 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001327
Chris Lattner523f6a52010-02-14 21:10:15 +00001328 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001329 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001330
Chris Lattnerd7349192010-03-19 21:37:09 +00001331 // Int inits are always integers. :)
1332 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001333
Chris Lattnerd7349192010-03-19 21:37:09 +00001334 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001335 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001336
Chris Lattnerd7349192010-03-19 21:37:09 +00001337 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001338 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1339 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001340
Chris Lattner2cacec52010-03-15 06:00:16 +00001341 unsigned Size = EVT(VT).getSizeInBits();
1342 // Make sure that the value is representable for this type.
1343 if (Size >= 32) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001344
Chris Lattner2cacec52010-03-15 06:00:16 +00001345 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1346 if (Val == II->getValue()) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001347
Chris Lattner2cacec52010-03-15 06:00:16 +00001348 // If sign-extended doesn't fit, does it fit as unsigned?
1349 unsigned ValueMask;
1350 unsigned UnsignedVal;
1351 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1352 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001353
Chris Lattner2cacec52010-03-15 06:00:16 +00001354 if ((ValueMask & UnsignedVal) == UnsignedVal)
1355 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001356
Chris Lattner2cacec52010-03-15 06:00:16 +00001357 TP.error("Integer value '" + itostr(II->getValue())+
Chris Lattnerd7349192010-03-19 21:37:09 +00001358 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001359 return MadeChange;
1360 }
1361 return false;
1362 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001363
Chris Lattner6cefb772008-01-05 22:25:12 +00001364 // special handling for set, which isn't really an SDNode.
1365 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001366 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1367 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001368 unsigned NC = getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001369
Chris Lattnerd7349192010-03-19 21:37:09 +00001370 TreePatternNode *SetVal = getChild(NC-1);
1371 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1372
Chris Lattner6cefb772008-01-05 22:25:12 +00001373 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001374 TreePatternNode *Child = getChild(i);
1375 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001376
Chris Lattner6cefb772008-01-05 22:25:12 +00001377 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001378 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1379 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001380 }
1381 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001382 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001383
Chris Lattner310adf12010-03-27 02:53:27 +00001384 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001385 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1386
Chris Lattner6cefb772008-01-05 22:25:12 +00001387 bool MadeChange = false;
1388 for (unsigned i = 0; i < getNumChildren(); ++i)
1389 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001390 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001391 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001392
Chris Lattner6eb30122010-02-23 05:51:07 +00001393 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001394 bool MadeChange = false;
1395 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1396 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001397
Chris Lattnerd7349192010-03-19 21:37:09 +00001398 assert(getChild(0)->getNumTypes() == 1 &&
1399 getChild(1)->getNumTypes() == 1 && "Unhandled case");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001400
Chris Lattner2cacec52010-03-15 06:00:16 +00001401 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1402 // what type it gets, so if it didn't get a concrete type just give it the
1403 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001404 if (!getChild(1)->hasTypeSet(0) &&
1405 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1406 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1407 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001408 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001409 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001410 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001411
Chris Lattner6eb30122010-02-23 05:51:07 +00001412 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001413 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001414
Chris Lattner6cefb772008-01-05 22:25:12 +00001415 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001416 unsigned NumRetVTs = Int->IS.RetVTs.size();
1417 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001418
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001419 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001420 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001421
Chris Lattnerd7349192010-03-19 21:37:09 +00001422 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001423 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001424 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001425 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001426
1427 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001428 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001429
Chris Lattnerd7349192010-03-19 21:37:09 +00001430 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1431 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001432
Chris Lattnerd7349192010-03-19 21:37:09 +00001433 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1434 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1435 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001436 }
1437 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001438 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001439
Chris Lattner6eb30122010-02-23 05:51:07 +00001440 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001441 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001442
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001443 // Check that the number of operands is sane. Negative operands -> varargs.
1444 if (NI.getNumOperands() >= 0 &&
1445 getNumChildren() != (unsigned)NI.getNumOperands())
1446 TP.error(getOperator()->getName() + " node requires exactly " +
1447 itostr(NI.getNumOperands()) + " operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001448
Chris Lattner6cefb772008-01-05 22:25:12 +00001449 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1450 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1451 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001452 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001453 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001454
Chris Lattner6eb30122010-02-23 05:51:07 +00001455 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001456 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001457 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001458 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001459
Chris Lattner0be6fe72010-03-27 19:15:02 +00001460 bool MadeChange = false;
1461
1462 // Apply the result types to the node, these come from the things in the
1463 // (outs) list of the instruction.
1464 // FIXME: Cap at one result so far.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001465 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001466 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1467 Record *ResultNode = Inst.getResult(ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001468
Chris Lattnera938ac62009-07-29 20:43:05 +00001469 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001470 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001471 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001472 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001473 } else {
1474 assert(ResultNode->isSubClassOf("RegisterClass") &&
1475 "Operands should be register classes!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001476 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001477 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001478 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001479 }
Chris Lattner0be6fe72010-03-27 19:15:02 +00001480 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001481
Chris Lattner0be6fe72010-03-27 19:15:02 +00001482 // If the instruction has implicit defs, we apply the first one as a result.
1483 // FIXME: This sucks, it should apply all implicit defs.
1484 if (!InstInfo.ImplicitDefs.empty()) {
1485 unsigned ResNo = NumResultsToAdd;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001486
Chris Lattner9414ae52010-03-27 20:09:24 +00001487 // FIXME: Generalize to multiple possible types and multiple possible
1488 // ImplicitDefs.
1489 MVT::SimpleValueType VT =
1490 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001491
Chris Lattner9414ae52010-03-27 20:09:24 +00001492 if (VT != MVT::Other)
1493 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001494 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001495
Chris Lattner2cacec52010-03-15 06:00:16 +00001496 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1497 // be the same.
1498 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001499 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1500 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1501 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001502 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001503
1504 unsigned ChildNo = 0;
1505 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1506 Record *OperandNode = Inst.getOperand(i);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001507
Chris Lattner6cefb772008-01-05 22:25:12 +00001508 // If the instruction expects a predicate or optional def operand, we
1509 // codegen this by setting the operand to it's default value if it has a
1510 // non-empty DefaultOps field.
1511 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1512 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1513 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1514 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001515
Chris Lattner6cefb772008-01-05 22:25:12 +00001516 // Verify that we didn't run out of provided operands.
1517 if (ChildNo >= getNumChildren())
1518 TP.error("Instruction '" + getOperator()->getName() +
1519 "' expects more operands than were provided.");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001520
Owen Anderson825b72b2009-08-11 20:47:22 +00001521 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001522 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001523 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001524
Chris Lattner6cefb772008-01-05 22:25:12 +00001525 if (OperandNode->isSubClassOf("RegisterClass")) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001526 const CodeGenRegisterClass &RC =
Chris Lattner6cefb772008-01-05 22:25:12 +00001527 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001528 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001529 } else if (OperandNode->isSubClassOf("Operand")) {
1530 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattner0be6fe72010-03-27 19:15:02 +00001531 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001532 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001533 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001534 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001535 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001536 } else {
1537 assert(0 && "Unknown operand type!");
1538 abort();
1539 }
1540 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1541 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001542
Christopher Lamb02f69372008-03-10 04:16:09 +00001543 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001544 TP.error("Instruction '" + getOperator()->getName() +
1545 "' was provided too many operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001546
Chris Lattner6cefb772008-01-05 22:25:12 +00001547 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001548 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001549
Chris Lattner6eb30122010-02-23 05:51:07 +00001550 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001551
Chris Lattner6eb30122010-02-23 05:51:07 +00001552 // Node transforms always take one operand.
1553 if (getNumChildren() != 1)
1554 TP.error("Node transform '" + getOperator()->getName() +
1555 "' requires one operand!");
1556
Chris Lattner2cacec52010-03-15 06:00:16 +00001557 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1558
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001559
Chris Lattner6eb30122010-02-23 05:51:07 +00001560 // If either the output or input of the xform does not have exact
1561 // type info. We assume they must be the same. Otherwise, it is perfectly
1562 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001563#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001564 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001565 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1566 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001567 return MadeChange;
1568 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001569#endif
1570 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001571}
1572
1573/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1574/// RHS of a commutative operation, not the on LHS.
1575static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1576 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1577 return true;
1578 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1579 return true;
1580 return false;
1581}
1582
1583
1584/// canPatternMatch - If it is impossible for this pattern to match on this
1585/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001586/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001587/// that can never possibly work), and to prevent the pattern permuter from
1588/// generating stuff that is useless.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001589bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001590 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001591 if (isLeaf()) return true;
1592
1593 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1594 if (!getChild(i)->canPatternMatch(Reason, CDP))
1595 return false;
1596
1597 // If this is an intrinsic, handle cases that would make it not match. For
1598 // example, if an operand is required to be an immediate.
1599 if (getOperator()->isSubClassOf("Intrinsic")) {
1600 // TODO:
1601 return true;
1602 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001603
Chris Lattner6cefb772008-01-05 22:25:12 +00001604 // If this node is a commutative operator, check that the LHS isn't an
1605 // immediate.
1606 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001607 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1608 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001609 // Scan all of the operands of the node and make sure that only the last one
1610 // is a constant node, unless the RHS also is.
1611 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001612 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1613 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001614 if (OnlyOnRHSOfCommutative(getChild(i))) {
1615 Reason="Immediate value must be on the RHS of commutative operators!";
1616 return false;
1617 }
1618 }
1619 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001620
Chris Lattner6cefb772008-01-05 22:25:12 +00001621 return true;
1622}
1623
1624//===----------------------------------------------------------------------===//
1625// TreePattern implementation
1626//
1627
1628TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001629 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001630 isInputPattern = isInput;
1631 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattnerc2173052010-03-28 06:50:34 +00001632 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001633}
1634
1635TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001636 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001637 isInputPattern = isInput;
Chris Lattnerc2173052010-03-28 06:50:34 +00001638 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001639}
1640
1641TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001642 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001643 isInputPattern = isInput;
1644 Trees.push_back(Pat);
1645}
1646
Chris Lattner6cefb772008-01-05 22:25:12 +00001647void TreePattern::error(const std::string &Msg) const {
1648 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001649 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001650}
1651
Chris Lattner2cacec52010-03-15 06:00:16 +00001652void TreePattern::ComputeNamedNodes() {
1653 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1654 ComputeNamedNodes(Trees[i]);
1655}
1656
1657void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1658 if (!N->getName().empty())
1659 NamedNodes[N->getName()].push_back(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001660
Chris Lattner2cacec52010-03-15 06:00:16 +00001661 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1662 ComputeNamedNodes(N->getChild(i));
1663}
1664
Chris Lattnerd7349192010-03-19 21:37:09 +00001665
Chris Lattnerc2173052010-03-28 06:50:34 +00001666TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1667 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
1668 Record *R = DI->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001669
Chris Lattnerc2173052010-03-28 06:50:34 +00001670 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1671 // TreePatternNode if its own. For example:
1672 /// (foo GPR, imm) -> (foo GPR, (imm))
1673 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1674 return ParseTreePattern(new DagInit(DI, "",
1675 std::vector<std::pair<Init*, std::string> >()),
1676 OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001677
Chris Lattnerc2173052010-03-28 06:50:34 +00001678 // Input argument?
1679 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001680 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001681 if (OpName.empty())
1682 error("'node' argument requires a name to match with operand list");
1683 Args.push_back(OpName);
1684 }
1685
1686 Res->setName(OpName);
1687 return Res;
1688 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001689
Chris Lattnerc2173052010-03-28 06:50:34 +00001690 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
1691 if (!OpName.empty())
1692 error("Constant int argument should not have a name!");
1693 return new TreePatternNode(II, 1);
1694 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001695
Chris Lattnerc2173052010-03-28 06:50:34 +00001696 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
1697 // Turn this into an IntInit.
1698 Init *II = BI->convertInitializerTo(new IntRecTy());
1699 if (II == 0 || !dynamic_cast<IntInit*>(II))
1700 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001701 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00001702 }
1703
1704 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
1705 if (!Dag) {
1706 TheInit->dump();
1707 error("Pattern has unexpected init kind!");
1708 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001709 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1710 if (!OpDef) error("Pattern has unexpected operator type!");
1711 Record *Operator = OpDef->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001712
Chris Lattner6cefb772008-01-05 22:25:12 +00001713 if (Operator->isSubClassOf("ValueType")) {
1714 // If the operator is a ValueType, then this must be "type cast" of a leaf
1715 // node.
1716 if (Dag->getNumArgs() != 1)
1717 error("Type cast only takes one operand!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001718
Chris Lattnerc2173052010-03-28 06:50:34 +00001719 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001720
Chris Lattner6cefb772008-01-05 22:25:12 +00001721 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001722 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1723 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001724
Chris Lattnerc2173052010-03-28 06:50:34 +00001725 if (!OpName.empty())
1726 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001727 return New;
1728 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001729
Chris Lattner6cefb772008-01-05 22:25:12 +00001730 // Verify that this is something that makes sense for an operator.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001731 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begeman7cee8172009-03-19 05:21:56 +00001732 !Operator->isSubClassOf("SDNode") &&
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001733 !Operator->isSubClassOf("Instruction") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001734 !Operator->isSubClassOf("SDNodeXForm") &&
1735 !Operator->isSubClassOf("Intrinsic") &&
1736 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001737 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001738 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001739
Chris Lattner6cefb772008-01-05 22:25:12 +00001740 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001741 if (isInputPattern) {
1742 if (Operator->isSubClassOf("Instruction") ||
1743 Operator->isSubClassOf("SDNodeXForm"))
1744 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1745 } else {
1746 if (Operator->isSubClassOf("Intrinsic"))
1747 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001748
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001749 if (Operator->isSubClassOf("SDNode") &&
1750 Operator->getName() != "imm" &&
1751 Operator->getName() != "fpimm" &&
1752 Operator->getName() != "tglobaltlsaddr" &&
1753 Operator->getName() != "tconstpool" &&
1754 Operator->getName() != "tjumptable" &&
1755 Operator->getName() != "tframeindex" &&
1756 Operator->getName() != "texternalsym" &&
1757 Operator->getName() != "tblockaddress" &&
1758 Operator->getName() != "tglobaladdr" &&
1759 Operator->getName() != "bb" &&
1760 Operator->getName() != "vt")
1761 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1762 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001763
Chris Lattner6cefb772008-01-05 22:25:12 +00001764 std::vector<TreePatternNode*> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00001765
1766 // Parse all the operands.
1767 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1768 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001769
Chris Lattner6cefb772008-01-05 22:25:12 +00001770 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001771 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner6cefb772008-01-05 22:25:12 +00001772 // convert the intrinsic name to a number.
1773 if (Operator->isSubClassOf("Intrinsic")) {
1774 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1775 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1776
1777 // If this intrinsic returns void, it must have side-effects and thus a
1778 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00001779 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001780 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001781 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00001782 // Has side-effects, requires chain.
1783 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001784 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00001785 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001786
Chris Lattnerd7349192010-03-19 21:37:09 +00001787 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001788 Children.insert(Children.begin(), IIDNode);
1789 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001790
Chris Lattnerd7349192010-03-19 21:37:09 +00001791 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1792 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00001793 Result->setName(OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001794
Chris Lattnerc2173052010-03-28 06:50:34 +00001795 if (!Dag->getName().empty()) {
1796 assert(Result->getName().empty());
1797 Result->setName(Dag->getName());
1798 }
Nate Begeman7cee8172009-03-19 05:21:56 +00001799 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001800}
1801
Chris Lattner7a0eb912010-03-28 08:38:32 +00001802/// SimplifyTree - See if we can simplify this tree to eliminate something that
1803/// will never match in favor of something obvious that will. This is here
1804/// strictly as a convenience to target authors because it allows them to write
1805/// more type generic things and have useless type casts fold away.
1806///
1807/// This returns true if any change is made.
1808static bool SimplifyTree(TreePatternNode *&N) {
1809 if (N->isLeaf())
1810 return false;
1811
1812 // If we have a bitconvert with a resolved type and if the source and
1813 // destination types are the same, then the bitconvert is useless, remove it.
1814 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattner7a0eb912010-03-28 08:38:32 +00001815 N->getExtType(0).isConcrete() &&
1816 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1817 N->getName().empty()) {
1818 N = N->getChild(0);
1819 SimplifyTree(N);
1820 return true;
1821 }
1822
1823 // Walk all children.
1824 bool MadeChange = false;
1825 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1826 TreePatternNode *Child = N->getChild(i);
1827 MadeChange |= SimplifyTree(Child);
1828 N->setChild(i, Child);
1829 }
1830 return MadeChange;
1831}
1832
1833
1834
Chris Lattner6cefb772008-01-05 22:25:12 +00001835/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001836/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001837/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001838bool TreePattern::
1839InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1840 if (NamedNodes.empty())
1841 ComputeNamedNodes();
1842
Chris Lattner6cefb772008-01-05 22:25:12 +00001843 bool MadeChange = true;
1844 while (MadeChange) {
1845 MadeChange = false;
Chris Lattner7a0eb912010-03-28 08:38:32 +00001846 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001847 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner7a0eb912010-03-28 08:38:32 +00001848 MadeChange |= SimplifyTree(Trees[i]);
1849 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001850
1851 // If there are constraints on our named nodes, apply them.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001852 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattner2cacec52010-03-15 06:00:16 +00001853 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1854 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001855
Chris Lattner2cacec52010-03-15 06:00:16 +00001856 // If we have input named node types, propagate their types to the named
1857 // values here.
1858 if (InNamedTypes) {
1859 // FIXME: Should be error?
1860 assert(InNamedTypes->count(I->getKey()) &&
1861 "Named node in output pattern but not input pattern?");
1862
1863 const SmallVectorImpl<TreePatternNode*> &InNodes =
1864 InNamedTypes->find(I->getKey())->second;
1865
1866 // The input types should be fully resolved by now.
1867 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1868 // If this node is a register class, and it is the root of the pattern
1869 // then we're mapping something onto an input register. We allow
1870 // changing the type of the input register in this case. This allows
1871 // us to match things like:
1872 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1873 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1874 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1875 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1876 continue;
1877 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001878
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001879 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001880 InNodes[0]->getNumTypes() == 1 &&
1881 "FIXME: cannot name multiple result nodes yet");
1882 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1883 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001884 }
1885 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001886
Chris Lattner2cacec52010-03-15 06:00:16 +00001887 // If there are multiple nodes with the same name, they must all have the
1888 // same type.
1889 if (I->second.size() > 1) {
1890 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001891 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001892 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001893 "FIXME: cannot name multiple result nodes yet");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001894
Chris Lattnerd7349192010-03-19 21:37:09 +00001895 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1896 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001897 }
1898 }
1899 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001900 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001901
Chris Lattner6cefb772008-01-05 22:25:12 +00001902 bool HasUnresolvedTypes = false;
1903 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1904 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1905 return !HasUnresolvedTypes;
1906}
1907
Daniel Dunbar1a551802009-07-03 00:10:29 +00001908void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001909 OS << getRecord()->getName();
1910 if (!Args.empty()) {
1911 OS << "(" << Args[0];
1912 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1913 OS << ", " << Args[i];
1914 OS << ")";
1915 }
1916 OS << ": ";
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001917
Chris Lattner6cefb772008-01-05 22:25:12 +00001918 if (Trees.size() > 1)
1919 OS << "[\n";
1920 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1921 OS << "\t";
1922 Trees[i]->print(OS);
1923 OS << "\n";
1924 }
1925
1926 if (Trees.size() > 1)
1927 OS << "]\n";
1928}
1929
Daniel Dunbar1a551802009-07-03 00:10:29 +00001930void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001931
1932//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001933// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001934//
1935
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001936CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner67db8832010-12-13 00:23:57 +00001937 Records(R), Target(R) {
1938
Dale Johannesen49de9822009-02-05 01:49:45 +00001939 Intrinsics = LoadIntrinsics(Records, false);
1940 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001941 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001942 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001943 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001944 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001945 ParseDefaultOperands();
1946 ParseInstructions();
1947 ParsePatterns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001948
Chris Lattner6cefb772008-01-05 22:25:12 +00001949 // Generate variants. For example, commutative patterns can match
1950 // multiple ways. Add them to PatternsToMatch as well.
1951 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001952
1953 // Infer instruction flags. For example, we can detect loads,
1954 // stores, and side effects in many cases by examining an
1955 // instruction's pattern.
1956 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001957}
1958
Chris Lattnerfe718932008-01-06 01:10:31 +00001959CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001960 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001961 E = PatternFragments.end(); I != E; ++I)
1962 delete I->second;
1963}
1964
1965
Chris Lattnerfe718932008-01-06 01:10:31 +00001966Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001967 Record *N = Records.getDef(Name);
1968 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001969 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001970 exit(1);
1971 }
1972 return N;
1973}
1974
1975// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001976void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001977 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1978 while (!Nodes.empty()) {
1979 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1980 Nodes.pop_back();
1981 }
1982
Jim Grosbachda4231f2009-03-26 16:17:51 +00001983 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001984 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1985 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1986 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1987}
1988
1989/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1990/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001991void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001992 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1993 while (!Xforms.empty()) {
1994 Record *XFormNode = Xforms.back();
1995 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1996 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001997 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001998
1999 Xforms.pop_back();
2000 }
2001}
2002
Chris Lattnerfe718932008-01-06 01:10:31 +00002003void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002004 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2005 while (!AMs.empty()) {
2006 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2007 AMs.pop_back();
2008 }
2009}
2010
2011
2012/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2013/// file, building up the PatternFragments map. After we've collected them all,
2014/// inline fragments together as necessary, so that there are no references left
2015/// inside a pattern fragment to a pattern fragment.
2016///
Chris Lattnerfe718932008-01-06 01:10:31 +00002017void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002018 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002019
Chris Lattnerdc32f982008-01-05 22:43:57 +00002020 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002021 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2022 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
2023 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2024 PatternFragments[Fragments[i]] = P;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002025
Chris Lattnerdc32f982008-01-05 22:43:57 +00002026 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00002027 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002028 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002029
Chris Lattnerdc32f982008-01-05 22:43:57 +00002030 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00002031 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002032
Chris Lattner6cefb772008-01-05 22:25:12 +00002033 // Parse the operands list.
2034 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2035 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
2036 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00002037 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00002038 if (!OpsOp ||
2039 (OpsOp->getDef()->getName() != "ops" &&
2040 OpsOp->getDef()->getName() != "outs" &&
2041 OpsOp->getDef()->getName() != "ins"))
2042 P->error("Operands list should start with '(ops ... '!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002043
2044 // Copy over the arguments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002045 Args.clear();
2046 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2047 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
2048 static_cast<DefInit*>(OpsList->getArg(j))->
2049 getDef()->getName() != "node")
2050 P->error("Operands list should all be 'node' values.");
2051 if (OpsList->getArgName(j).empty())
2052 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002053 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00002054 P->error("'" + OpsList->getArgName(j) +
2055 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002056 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00002057 Args.push_back(OpsList->getArgName(j));
2058 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002059
Chris Lattnerdc32f982008-01-05 22:43:57 +00002060 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00002061 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00002062 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002063
Chris Lattnerdc32f982008-01-05 22:43:57 +00002064 // If there is a code init for this fragment, keep track of the fact that
2065 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00002066 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002067 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00002068 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002069
Chris Lattner6cefb772008-01-05 22:25:12 +00002070 // If there is a node transformation corresponding to this, keep track of
2071 // it.
2072 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2073 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2074 P->getOnlyTree()->setTransformFn(Transform);
2075 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002076
Chris Lattner6cefb772008-01-05 22:25:12 +00002077 // Now that we've parsed all of the tree fragments, do a closure on them so
2078 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00002079 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2080 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00002081 ThePat->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002082
Chris Lattner6cefb772008-01-05 22:25:12 +00002083 // Infer as many types as possible. Don't worry about it if we don't infer
2084 // all of them, some may depend on the inputs of the pattern.
2085 try {
2086 ThePat->InferAllTypes();
2087 } catch (...) {
2088 // If this pattern fragment is not supported by this target (no types can
2089 // satisfy its constraints), just ignore it. If the bogus pattern is
2090 // actually used by instructions, the type consistency error will be
2091 // reported there.
2092 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002093
Chris Lattner6cefb772008-01-05 22:25:12 +00002094 // If debugging, print out the pattern fragment result.
2095 DEBUG(ThePat->dump());
2096 }
2097}
2098
Chris Lattnerfe718932008-01-06 01:10:31 +00002099void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002100 std::vector<Record*> DefaultOps[2];
2101 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
2102 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
2103
2104 // Find some SDNode.
2105 assert(!SDNodes.empty() && "No SDNodes parsed?");
2106 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002107
Chris Lattner6cefb772008-01-05 22:25:12 +00002108 for (unsigned iter = 0; iter != 2; ++iter) {
2109 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
2110 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002111
Chris Lattner6cefb772008-01-05 22:25:12 +00002112 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2113 // SomeSDnode so that we can parse this.
2114 std::vector<std::pair<Init*, std::string> > Ops;
2115 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2116 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2117 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00002118 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002119
Chris Lattner6cefb772008-01-05 22:25:12 +00002120 // Create a TreePattern to parse this.
2121 TreePattern P(DefaultOps[iter][i], DI, false, *this);
2122 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2123
2124 // Copy the operands over into a DAGDefaultOperand.
2125 DAGDefaultOperand DefaultOpInfo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002126
Chris Lattner6cefb772008-01-05 22:25:12 +00002127 TreePatternNode *T = P.getTree(0);
2128 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2129 TreePatternNode *TPN = T->getChild(op);
2130 while (TPN->ApplyTypeConstraints(P, false))
2131 /* Resolve all types */;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002132
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002133 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002134 if (iter == 0)
2135 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00002136 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00002137 else
2138 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00002139 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002140 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002141 DefaultOpInfo.DefaultOps.push_back(TPN);
2142 }
2143
2144 // Insert it into the DefaultOperands map so we can find it later.
2145 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2146 }
2147 }
2148}
2149
2150/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2151/// instruction input. Return true if this is a real use.
2152static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002153 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002154 // No name -> not interesting.
2155 if (Pat->getName().empty()) {
2156 if (Pat->isLeaf()) {
2157 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2158 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
2159 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002160 }
2161 return false;
2162 }
2163
2164 Record *Rec;
2165 if (Pat->isLeaf()) {
2166 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2167 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2168 Rec = DI->getDef();
2169 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00002170 Rec = Pat->getOperator();
2171 }
2172
2173 // SRCVALUE nodes are ignored.
2174 if (Rec->getName() == "srcvalue")
2175 return false;
2176
2177 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2178 if (!Slot) {
2179 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00002180 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00002181 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00002182 Record *SlotRec;
2183 if (Slot->isLeaf()) {
2184 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
2185 } else {
2186 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2187 SlotRec = Slot->getOperator();
2188 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002189
Chris Lattner53d09bd2010-02-23 05:59:10 +00002190 // Ensure that the inputs agree if we've already seen this input.
2191 if (Rec != SlotRec)
2192 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00002193 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00002194 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00002195 return true;
2196}
2197
2198/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2199/// part of "I", the instruction), computing the set of inputs and outputs of
2200/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00002201void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00002202FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2203 std::map<std::string, TreePatternNode*> &InstInputs,
2204 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner6cefb772008-01-05 22:25:12 +00002205 std::vector<Record*> &InstImpResults) {
2206 if (Pat->isLeaf()) {
Chris Lattneracfb70f2010-04-20 06:30:25 +00002207 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002208 if (!isUse && Pat->getTransformFn())
2209 I->error("Cannot specify a transform function for a non-input value!");
2210 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002211 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002212
Chris Lattner84aa60b2010-02-17 06:53:36 +00002213 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002214 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2215 TreePatternNode *Dest = Pat->getChild(i);
2216 if (!Dest->isLeaf())
2217 I->error("implicitly defined value should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002218
Chris Lattner6cefb772008-01-05 22:25:12 +00002219 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2220 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2221 I->error("implicitly defined value should be a register!");
2222 InstImpResults.push_back(Val->getDef());
2223 }
2224 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002225 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002226
Chris Lattner84aa60b2010-02-17 06:53:36 +00002227 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002228 // If this is not a set, verify that the children nodes are not void typed,
2229 // and recurse.
2230 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002231 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002232 I->error("Cannot have void nodes inside of patterns!");
2233 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002234 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002235 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002236
Chris Lattner6cefb772008-01-05 22:25:12 +00002237 // If this is a non-leaf node with no children, treat it basically as if
2238 // it were a leaf. This handles nodes like (imm).
Chris Lattneracfb70f2010-04-20 06:30:25 +00002239 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002240
Chris Lattner6cefb772008-01-05 22:25:12 +00002241 if (!isUse && Pat->getTransformFn())
2242 I->error("Cannot specify a transform function for a non-input value!");
2243 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002244 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002245
Chris Lattner6cefb772008-01-05 22:25:12 +00002246 // Otherwise, this is a set, validate and collect instruction results.
2247 if (Pat->getNumChildren() == 0)
2248 I->error("set requires operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002249
Chris Lattner6cefb772008-01-05 22:25:12 +00002250 if (Pat->getTransformFn())
2251 I->error("Cannot specify a transform function on a set node!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002252
Chris Lattner6cefb772008-01-05 22:25:12 +00002253 // Check the set destinations.
2254 unsigned NumDests = Pat->getNumChildren()-1;
2255 for (unsigned i = 0; i != NumDests; ++i) {
2256 TreePatternNode *Dest = Pat->getChild(i);
2257 if (!Dest->isLeaf())
2258 I->error("set destination should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002259
Chris Lattner6cefb772008-01-05 22:25:12 +00002260 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2261 if (!Val)
2262 I->error("set destination should be a register!");
2263
2264 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002265 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002266 if (Dest->getName().empty())
2267 I->error("set destination must have a name!");
2268 if (InstResults.count(Dest->getName()))
2269 I->error("cannot set '" + Dest->getName() +"' multiple times");
2270 InstResults[Dest->getName()] = Dest;
2271 } else if (Val->getDef()->isSubClassOf("Register")) {
2272 InstImpResults.push_back(Val->getDef());
2273 } else {
2274 I->error("set destination should be a register!");
2275 }
2276 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002277
Chris Lattner6cefb772008-01-05 22:25:12 +00002278 // Verify and collect info from the computation.
2279 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattneracfb70f2010-04-20 06:30:25 +00002280 InstInputs, InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002281}
2282
Dan Gohmanee4fa192008-04-03 00:02:49 +00002283//===----------------------------------------------------------------------===//
2284// Instruction Analysis
2285//===----------------------------------------------------------------------===//
2286
2287class InstAnalyzer {
2288 const CodeGenDAGPatterns &CDP;
2289 bool &mayStore;
2290 bool &mayLoad;
Evan Cheng0f040a22011-03-15 05:09:26 +00002291 bool &IsBitcast;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002292 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002293 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002294public:
2295 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Evan Cheng0f040a22011-03-15 05:09:26 +00002296 bool &maystore, bool &mayload, bool &isbc, bool &hse, bool &isv)
2297 : CDP(cdp), mayStore(maystore), mayLoad(mayload), IsBitcast(isbc),
2298 HasSideEffects(hse), IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002299 }
2300
2301 /// Analyze - Analyze the specified instruction, returning true if the
2302 /// instruction had a pattern.
2303 bool Analyze(Record *InstRecord) {
2304 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2305 if (Pattern == 0) {
2306 HasSideEffects = 1;
2307 return false; // No pattern.
2308 }
2309
2310 // FIXME: Assume only the first tree is the pattern. The others are clobber
2311 // nodes.
2312 AnalyzeNode(Pattern->getTree(0));
2313 return true;
2314 }
2315
2316private:
Evan Cheng0f040a22011-03-15 05:09:26 +00002317 bool IsNodeBitcast(const TreePatternNode *N) const {
2318 if (HasSideEffects || mayLoad || mayStore || IsVariadic)
2319 return false;
2320
2321 if (N->getNumChildren() != 2)
2322 return false;
2323
2324 const TreePatternNode *N0 = N->getChild(0);
2325 if (!N0->isLeaf() || !dynamic_cast<DefInit*>(N0->getLeafValue()))
2326 return false;
2327
2328 const TreePatternNode *N1 = N->getChild(1);
2329 if (N1->isLeaf())
2330 return false;
2331 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2332 return false;
2333
2334 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2335 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2336 return false;
2337 return OpInfo.getEnumName() == "ISD::BITCAST";
2338 }
2339
Dan Gohmanee4fa192008-04-03 00:02:49 +00002340 void AnalyzeNode(const TreePatternNode *N) {
2341 if (N->isLeaf()) {
2342 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2343 Record *LeafRec = DI->getDef();
2344 // Handle ComplexPattern leaves.
2345 if (LeafRec->isSubClassOf("ComplexPattern")) {
2346 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2347 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2348 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2349 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2350 }
2351 }
2352 return;
2353 }
2354
2355 // Analyze children.
2356 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2357 AnalyzeNode(N->getChild(i));
2358
2359 // Ignore set nodes, which are not SDNodes.
Evan Cheng0f040a22011-03-15 05:09:26 +00002360 if (N->getOperator()->getName() == "set") {
2361 IsBitcast = IsNodeBitcast(N);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002362 return;
Evan Cheng0f040a22011-03-15 05:09:26 +00002363 }
Dan Gohmanee4fa192008-04-03 00:02:49 +00002364
2365 // Get information about the SDNode for the operator.
2366 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2367
2368 // Notice properties of the node.
2369 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2370 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2371 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002372 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002373
2374 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2375 // If this is an intrinsic, analyze it.
2376 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2377 mayLoad = true;// These may load memory.
2378
Dan Gohman7365c092010-08-05 23:36:21 +00002379 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002380 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2381
Dan Gohman7365c092010-08-05 23:36:21 +00002382 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002383 // WriteMem intrinsics can have other strange effects.
2384 HasSideEffects = true;
2385 }
2386 }
2387
2388};
2389
2390static void InferFromPattern(const CodeGenInstruction &Inst,
2391 bool &MayStore, bool &MayLoad,
Evan Cheng0f040a22011-03-15 05:09:26 +00002392 bool &IsBitcast,
Chris Lattner1e506312010-03-19 05:34:15 +00002393 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002394 const CodeGenDAGPatterns &CDP) {
Evan Cheng0f040a22011-03-15 05:09:26 +00002395 MayStore = MayLoad = IsBitcast = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002396
2397 bool HadPattern =
Evan Cheng0f040a22011-03-15 05:09:26 +00002398 InstAnalyzer(CDP, MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic)
Chris Lattner1e506312010-03-19 05:34:15 +00002399 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002400
2401 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2402 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2403 // If we decided that this is a store from the pattern, then the .td file
2404 // entry is redundant.
2405 if (MayStore)
2406 fprintf(stderr,
2407 "Warning: mayStore flag explicitly set on instruction '%s'"
2408 " but flag already inferred from pattern.\n",
2409 Inst.TheDef->getName().c_str());
2410 MayStore = true;
2411 }
2412
2413 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2414 // If we decided that this is a load from the pattern, then the .td file
2415 // entry is redundant.
2416 if (MayLoad)
2417 fprintf(stderr,
2418 "Warning: mayLoad flag explicitly set on instruction '%s'"
2419 " but flag already inferred from pattern.\n",
2420 Inst.TheDef->getName().c_str());
2421 MayLoad = true;
2422 }
2423
2424 if (Inst.neverHasSideEffects) {
2425 if (HadPattern)
2426 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2427 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2428 HasSideEffects = false;
2429 }
2430
2431 if (Inst.hasSideEffects) {
2432 if (HasSideEffects)
2433 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2434 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2435 HasSideEffects = true;
2436 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002437
Chris Lattnerc240bb02010-11-01 04:03:32 +00002438 if (Inst.Operands.isVariadic)
Chris Lattner1e506312010-03-19 05:34:15 +00002439 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002440}
2441
Chris Lattner6cefb772008-01-05 22:25:12 +00002442/// ParseInstructions - Parse all of the instructions, inlining and resolving
2443/// any fragments involved. This populates the Instructions list with fully
2444/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002445void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002446 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002447
Chris Lattner6cefb772008-01-05 22:25:12 +00002448 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2449 ListInit *LI = 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002450
Chris Lattner6cefb772008-01-05 22:25:12 +00002451 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2452 LI = Instrs[i]->getValueAsListInit("Pattern");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002453
Chris Lattner6cefb772008-01-05 22:25:12 +00002454 // If there is no pattern, only collect minimal information about the
2455 // instruction for its operand list. We have to assume that there is one
2456 // result, as we have no detailed info.
2457 if (!LI || LI->getSize() == 0) {
2458 std::vector<Record*> Results;
2459 std::vector<Record*> Operands;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002460
Chris Lattnerf30187a2010-03-19 00:07:20 +00002461 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002462
Chris Lattnerc240bb02010-11-01 04:03:32 +00002463 if (InstInfo.Operands.size() != 0) {
2464 if (InstInfo.Operands.NumDefs == 0) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002465 // These produce no results
Chris Lattnerc240bb02010-11-01 04:03:32 +00002466 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2467 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002468 } else {
2469 // Assume the first operand is the result.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002470 Results.push_back(InstInfo.Operands[0].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002471
Chris Lattner6cefb772008-01-05 22:25:12 +00002472 // The rest are inputs.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002473 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2474 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002475 }
2476 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002477
Chris Lattner6cefb772008-01-05 22:25:12 +00002478 // Create and insert the instruction.
2479 std::vector<Record*> ImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002480 Instructions.insert(std::make_pair(Instrs[i],
Chris Lattner62bcec82010-04-20 06:28:43 +00002481 DAGInstruction(0, Results, Operands, ImpResults)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002482 continue; // no pattern.
2483 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002484
Chris Lattner6cefb772008-01-05 22:25:12 +00002485 // Parse the instruction.
2486 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2487 // Inline pattern fragments into it.
2488 I->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002489
Chris Lattner6cefb772008-01-05 22:25:12 +00002490 // Infer as many types as possible. If we cannot infer all of them, we can
2491 // never do anything with this instruction pattern: report it to the user.
2492 if (!I->InferAllTypes())
2493 I->error("Could not infer all types in pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002494
2495 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner6cefb772008-01-05 22:25:12 +00002496 // with the record they are declared as.
2497 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002498
Chris Lattner6cefb772008-01-05 22:25:12 +00002499 // InstResults - Keep track of all the virtual registers that are 'set'
2500 // in the instruction, including what reg class they are.
2501 std::map<std::string, TreePatternNode*> InstResults;
2502
Chris Lattner6cefb772008-01-05 22:25:12 +00002503 std::vector<Record*> InstImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002504
Chris Lattner6cefb772008-01-05 22:25:12 +00002505 // Verify that the top-level forms in the instruction are of void type, and
2506 // fill in the InstResults map.
2507 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2508 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002509 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002510 I->error("Top-level forms in instruction pattern should have"
2511 " void types");
2512
2513 // Find inputs and outputs, and verify the structure of the uses/defs.
2514 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002515 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002516 }
2517
2518 // Now that we have inputs and outputs of the pattern, inspect the operands
2519 // list for the instruction. This determines the order that operands are
2520 // added to the machine instruction the node corresponds to.
2521 unsigned NumResults = InstResults.size();
2522
2523 // Parse the operands list from the (ops) list, validating it.
2524 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002525 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002526
2527 // Check that all of the results occur first in the list.
2528 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002529 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002530 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00002531 if (i == CGI.Operands.size())
Chris Lattner6cefb772008-01-05 22:25:12 +00002532 I->error("'" + InstResults.begin()->first +
2533 "' set but does not appear in operand list!");
Chris Lattnerc240bb02010-11-01 04:03:32 +00002534 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002535
Chris Lattner6cefb772008-01-05 22:25:12 +00002536 // Check that it exists in InstResults.
2537 TreePatternNode *RNode = InstResults[OpName];
2538 if (RNode == 0)
2539 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002540
Chris Lattner6cefb772008-01-05 22:25:12 +00002541 if (i == 0)
2542 Res0Node = RNode;
2543 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2544 if (R == 0)
2545 I->error("Operand $" + OpName + " should be a set destination: all "
2546 "outputs must occur before inputs in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002547
Chris Lattnerc240bb02010-11-01 04:03:32 +00002548 if (CGI.Operands[i].Rec != R)
Chris Lattner6cefb772008-01-05 22:25:12 +00002549 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002550
Chris Lattner6cefb772008-01-05 22:25:12 +00002551 // Remember the return type.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002552 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002553
Chris Lattner6cefb772008-01-05 22:25:12 +00002554 // Okay, this one checks out.
2555 InstResults.erase(OpName);
2556 }
2557
2558 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2559 // the copy while we're checking the inputs.
2560 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2561
2562 std::vector<TreePatternNode*> ResultNodeOperands;
2563 std::vector<Record*> Operands;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002564 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2565 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner6cefb772008-01-05 22:25:12 +00002566 const std::string &OpName = Op.Name;
2567 if (OpName.empty())
2568 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2569
2570 if (!InstInputsCheck.count(OpName)) {
2571 // If this is an predicate operand or optional def operand with an
2572 // DefaultOps set filled in, we can ignore this. When we codegen it,
2573 // we will do so as always executed.
2574 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2575 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2576 // Does it have a non-empty DefaultOps field? If so, ignore this
2577 // operand.
2578 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2579 continue;
2580 }
2581 I->error("Operand $" + OpName +
2582 " does not appear in the instruction pattern");
2583 }
2584 TreePatternNode *InVal = InstInputsCheck[OpName];
2585 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002586
Chris Lattner6cefb772008-01-05 22:25:12 +00002587 if (InVal->isLeaf() &&
2588 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2589 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2590 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2591 I->error("Operand $" + OpName + "'s register class disagrees"
2592 " between the operand and pattern");
2593 }
2594 Operands.push_back(Op.Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002595
Chris Lattner6cefb772008-01-05 22:25:12 +00002596 // Construct the result for the dest-pattern operand list.
2597 TreePatternNode *OpNode = InVal->clone();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002598
Chris Lattner6cefb772008-01-05 22:25:12 +00002599 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002600 OpNode->clearPredicateFns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002601
Chris Lattner6cefb772008-01-05 22:25:12 +00002602 // Promote the xform function to be an explicit node if set.
2603 if (Record *Xform = OpNode->getTransformFn()) {
2604 OpNode->setTransformFn(0);
2605 std::vector<TreePatternNode*> Children;
2606 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002607 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002608 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002609
Chris Lattner6cefb772008-01-05 22:25:12 +00002610 ResultNodeOperands.push_back(OpNode);
2611 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002612
Chris Lattner6cefb772008-01-05 22:25:12 +00002613 if (!InstInputsCheck.empty())
2614 I->error("Input operand $" + InstInputsCheck.begin()->first +
2615 " occurs in pattern but not in operands list!");
2616
2617 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002618 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2619 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002620 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002621 for (unsigned i = 0; i != NumResults; ++i)
2622 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002623
2624 // Create and insert the instruction.
Chris Lattneracfb70f2010-04-20 06:30:25 +00002625 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner62bcec82010-04-20 06:28:43 +00002626 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002627 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2628
2629 // Use a temporary tree pattern to infer all types and make sure that the
2630 // constructed result is correct. This depends on the instruction already
2631 // being inserted into the Instructions map.
2632 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002633 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002634
2635 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2636 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002637
Chris Lattner6cefb772008-01-05 22:25:12 +00002638 DEBUG(I->dump());
2639 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002640
Chris Lattner6cefb772008-01-05 22:25:12 +00002641 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002642 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2643 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002644 E = Instructions.end(); II != E; ++II) {
2645 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002646 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002647 if (I == 0) continue; // No pattern.
2648
2649 // FIXME: Assume only the first tree is the pattern. The others are clobber
2650 // nodes.
2651 TreePatternNode *Pattern = I->getTree(0);
2652 TreePatternNode *SrcPattern;
2653 if (Pattern->getOperator()->getName() == "set") {
2654 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2655 } else{
2656 // Not a set (store or something?)
2657 SrcPattern = Pattern;
2658 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002659
Chris Lattner6cefb772008-01-05 22:25:12 +00002660 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002661 AddPatternToMatch(I,
Jim Grosbach997759a2010-12-07 23:05:49 +00002662 PatternToMatch(Instr,
2663 Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002664 SrcPattern,
2665 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002666 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002667 Instr->getValueAsInt("AddedComplexity"),
2668 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002669 }
2670}
2671
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002672
2673typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2674
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002675static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002676 std::map<std::string, NameRecord> &Names,
2677 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002678 if (!P->getName().empty()) {
2679 NameRecord &Rec = Names[P->getName()];
2680 // If this is the first instance of the name, remember the node.
2681 if (Rec.second++ == 0)
2682 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002683 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002684 PatternTop->error("repetition of value: $" + P->getName() +
2685 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002686 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002687
Chris Lattner967d54a2010-02-23 06:35:45 +00002688 if (!P->isLeaf()) {
2689 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002690 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002691 }
2692}
2693
Chris Lattner25b6f912010-02-23 06:16:51 +00002694void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2695 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002696 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002697 std::string Reason;
2698 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002699 Pattern->error("Pattern can never match: " + Reason);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002700
Chris Lattner405f1252010-03-01 22:29:19 +00002701 // If the source pattern's root is a complex pattern, that complex pattern
2702 // must specify the nodes it can potentially match.
2703 if (const ComplexPattern *CP =
2704 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2705 if (CP->getRootNodes().empty())
2706 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2707 " could match");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002708
2709
Chris Lattner967d54a2010-02-23 06:35:45 +00002710 // Find all of the named values in the input and output, ensure they have the
2711 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002712 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002713 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2714 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002715
2716 // Scan all of the named values in the destination pattern, rejecting them if
2717 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002718 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002719 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002720 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002721 Pattern->error("Pattern has input without matching name in output: $" +
2722 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002723 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002724
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002725 // Scan all of the named values in the source pattern, rejecting them if the
2726 // name isn't used in the dest, and isn't used to tie two values together.
2727 for (std::map<std::string, NameRecord>::iterator
2728 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2729 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2730 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002731
Chris Lattner25b6f912010-02-23 06:16:51 +00002732 PatternsToMatch.push_back(PTM);
2733}
2734
2735
Dan Gohmanee4fa192008-04-03 00:02:49 +00002736
2737void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002738 const std::vector<const CodeGenInstruction*> &Instructions =
2739 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002740 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2741 CodeGenInstruction &InstInfo =
2742 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002743 // Determine properties of the instruction from its pattern.
Evan Cheng0f040a22011-03-15 05:09:26 +00002744 bool MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic;
2745 InferFromPattern(InstInfo, MayStore, MayLoad, IsBitcast,
2746 HasSideEffects, IsVariadic, *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002747 InstInfo.mayStore = MayStore;
2748 InstInfo.mayLoad = MayLoad;
Evan Cheng0f040a22011-03-15 05:09:26 +00002749 InstInfo.isBitcast = IsBitcast;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002750 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002751 InstInfo.Operands.isVariadic = IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002752 }
2753}
2754
Chris Lattner2cacec52010-03-15 06:00:16 +00002755/// Given a pattern result with an unresolved type, see if we can find one
2756/// instruction with an unresolved result type. Force this result type to an
2757/// arbitrary element if it's possible types to converge results.
2758static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2759 if (N->isLeaf())
2760 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002761
Chris Lattner2cacec52010-03-15 06:00:16 +00002762 // Analyze children.
2763 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2764 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2765 return true;
2766
2767 if (!N->getOperator()->isSubClassOf("Instruction"))
2768 return false;
2769
2770 // If this type is already concrete or completely unknown we can't do
2771 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00002772 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2773 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2774 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002775
Chris Lattnerd7349192010-03-19 21:37:09 +00002776 // Otherwise, force its type to the first possibility (an arbitrary choice).
2777 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2778 return true;
2779 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002780
Chris Lattnerd7349192010-03-19 21:37:09 +00002781 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00002782}
2783
Chris Lattnerfe718932008-01-06 01:10:31 +00002784void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002785 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2786
2787 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002788 Record *CurPattern = Patterns[i];
2789 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Chris Lattner310adf12010-03-27 02:53:27 +00002790 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002791
2792 // Inline pattern fragments into it.
2793 Pattern->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002794
Chris Lattnerd7349192010-03-19 21:37:09 +00002795 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00002796 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002797
Chris Lattner6cefb772008-01-05 22:25:12 +00002798 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00002799 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002800
Chris Lattner6cefb772008-01-05 22:25:12 +00002801 // Inline pattern fragments into it.
2802 Result->InlinePatternFragments();
2803
2804 if (Result->getNumTrees() != 1)
2805 Result->error("Cannot handle instructions producing instructions "
2806 "with temporaries yet!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002807
Chris Lattner6cefb772008-01-05 22:25:12 +00002808 bool IterateInference;
2809 bool InferredAllPatternTypes, InferredAllResultTypes;
2810 do {
2811 // Infer as many types as possible. If we cannot infer all of them, we
2812 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002813 InferredAllPatternTypes =
2814 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002815
Chris Lattner6cefb772008-01-05 22:25:12 +00002816 // Infer as many types as possible. If we cannot infer all of them, we
2817 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002818 InferredAllResultTypes =
2819 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002820
Chris Lattner6c6ba362010-03-18 23:15:10 +00002821 IterateInference = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002822
Chris Lattner6cefb772008-01-05 22:25:12 +00002823 // Apply the type of the result to the source pattern. This helps us
2824 // resolve cases where the input type is known to be a pointer type (which
2825 // is considered resolved), but the result knows it needs to be 32- or
2826 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00002827 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2828 Pattern->getTree(0)->getNumTypes());
2829 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00002830 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002831 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002832 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002833 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002834 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002835
Chris Lattner2cacec52010-03-15 06:00:16 +00002836 // If our iteration has converged and the input pattern's types are fully
2837 // resolved but the result pattern is not fully resolved, we may have a
2838 // situation where we have two instructions in the result pattern and
2839 // the instructions require a common register class, but don't care about
2840 // what actual MVT is used. This is actually a bug in our modelling:
2841 // output patterns should have register classes, not MVTs.
2842 //
2843 // In any case, to handle this, we just go through and disambiguate some
2844 // arbitrary types to the result pattern's nodes.
2845 if (!IterateInference && InferredAllPatternTypes &&
2846 !InferredAllResultTypes)
2847 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2848 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002849 } while (IterateInference);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002850
Chris Lattner6cefb772008-01-05 22:25:12 +00002851 // Verify that we inferred enough types that we can do something with the
2852 // pattern and result. If these fire the user has to add type casts.
2853 if (!InferredAllPatternTypes)
2854 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002855 if (!InferredAllResultTypes) {
2856 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002857 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002858 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002859
Chris Lattner6cefb772008-01-05 22:25:12 +00002860 // Validate that the input pattern is correct.
2861 std::map<std::string, TreePatternNode*> InstInputs;
2862 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00002863 std::vector<Record*> InstImpResults;
2864 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2865 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2866 InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002867 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002868
2869 // Promote the xform function to be an explicit node if set.
2870 TreePatternNode *DstPattern = Result->getOnlyTree();
2871 std::vector<TreePatternNode*> ResultNodeOperands;
2872 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2873 TreePatternNode *OpNode = DstPattern->getChild(ii);
2874 if (Record *Xform = OpNode->getTransformFn()) {
2875 OpNode->setTransformFn(0);
2876 std::vector<TreePatternNode*> Children;
2877 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002878 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002879 }
2880 ResultNodeOperands.push_back(OpNode);
2881 }
2882 DstPattern = Result->getOnlyTree();
2883 if (!DstPattern->isLeaf())
2884 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00002885 ResultNodeOperands,
2886 DstPattern->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002887
Chris Lattnerd7349192010-03-19 21:37:09 +00002888 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2889 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002890
Chris Lattner6cefb772008-01-05 22:25:12 +00002891 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2892 Temp.InferAllTypes();
2893
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002894
Chris Lattner25b6f912010-02-23 06:16:51 +00002895 AddPatternToMatch(Pattern,
Jim Grosbach997759a2010-12-07 23:05:49 +00002896 PatternToMatch(CurPattern,
2897 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerd7349192010-03-19 21:37:09 +00002898 Pattern->getTree(0),
2899 Temp.getOnlyTree(), InstImpResults,
2900 CurPattern->getValueAsInt("AddedComplexity"),
2901 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002902 }
2903}
2904
2905/// CombineChildVariants - Given a bunch of permutations of each child of the
2906/// 'operator' node, put them together in all possible ways.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002907static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00002908 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2909 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002910 CodeGenDAGPatterns &CDP,
2911 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002912 // Make sure that each operand has at least one variant to choose from.
2913 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2914 if (ChildVariants[i].empty())
2915 return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002916
Chris Lattner6cefb772008-01-05 22:25:12 +00002917 // The end result is an all-pairs construction of the resultant pattern.
2918 std::vector<unsigned> Idxs;
2919 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002920 bool NotDone;
2921 do {
2922#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002923 DEBUG(if (!Idxs.empty()) {
2924 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2925 for (unsigned i = 0; i < Idxs.size(); ++i) {
2926 errs() << Idxs[i] << " ";
2927 }
2928 errs() << "]\n";
2929 });
Scott Michel327d0652008-03-05 17:49:05 +00002930#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002931 // Create the variant and add it to the output list.
2932 std::vector<TreePatternNode*> NewChildren;
2933 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2934 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00002935 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2936 Orig->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002937
Chris Lattner6cefb772008-01-05 22:25:12 +00002938 // Copy over properties.
2939 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002940 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002941 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00002942 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2943 R->setType(i, Orig->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002944
Scott Michel327d0652008-03-05 17:49:05 +00002945 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002946 std::string ErrString;
2947 if (!R->canPatternMatch(ErrString, CDP)) {
2948 delete R;
2949 } else {
2950 bool AlreadyExists = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002951
Chris Lattner6cefb772008-01-05 22:25:12 +00002952 // Scan to see if this pattern has already been emitted. We can get
2953 // duplication due to things like commuting:
2954 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2955 // which are the same pattern. Ignore the dups.
2956 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002957 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002958 AlreadyExists = true;
2959 break;
2960 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002961
Chris Lattner6cefb772008-01-05 22:25:12 +00002962 if (AlreadyExists)
2963 delete R;
2964 else
2965 OutVariants.push_back(R);
2966 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002967
Scott Michel327d0652008-03-05 17:49:05 +00002968 // Increment indices to the next permutation by incrementing the
2969 // indicies from last index backward, e.g., generate the sequence
2970 // [0, 0], [0, 1], [1, 0], [1, 1].
2971 int IdxsIdx;
2972 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2973 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2974 Idxs[IdxsIdx] = 0;
2975 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002976 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002977 }
Scott Michel327d0652008-03-05 17:49:05 +00002978 NotDone = (IdxsIdx >= 0);
2979 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002980}
2981
2982/// CombineChildVariants - A helper function for binary operators.
2983///
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002984static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00002985 const std::vector<TreePatternNode*> &LHS,
2986 const std::vector<TreePatternNode*> &RHS,
2987 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002988 CodeGenDAGPatterns &CDP,
2989 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002990 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2991 ChildVariants.push_back(LHS);
2992 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002993 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002994}
Chris Lattner6cefb772008-01-05 22:25:12 +00002995
2996
2997static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2998 std::vector<TreePatternNode *> &Children) {
2999 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3000 Record *Operator = N->getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003001
Chris Lattner6cefb772008-01-05 22:25:12 +00003002 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00003003 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00003004 N->getTransformFn()) {
3005 Children.push_back(N);
3006 return;
3007 }
3008
3009 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3010 Children.push_back(N->getChild(0));
3011 else
3012 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3013
3014 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3015 Children.push_back(N->getChild(1));
3016 else
3017 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3018}
3019
3020/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3021/// the (potentially recursive) pattern by using algebraic laws.
3022///
3023static void GenerateVariantsOf(TreePatternNode *N,
3024 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003025 CodeGenDAGPatterns &CDP,
3026 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003027 // We cannot permute leaves.
3028 if (N->isLeaf()) {
3029 OutVariants.push_back(N);
3030 return;
3031 }
3032
3033 // Look up interesting info about the node.
3034 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3035
Jim Grosbachda4231f2009-03-26 16:17:51 +00003036 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00003037 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003038 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00003039 std::vector<TreePatternNode*> MaximalChildren;
3040 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3041
3042 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3043 // permutations.
3044 if (MaximalChildren.size() == 3) {
3045 // Find the variants of all of our maximal children.
3046 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003047 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3048 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3049 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003050
Chris Lattner6cefb772008-01-05 22:25:12 +00003051 // There are only two ways we can permute the tree:
3052 // (A op B) op C and A op (B op C)
3053 // Within these forms, we can also permute A/B/C.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003054
Chris Lattner6cefb772008-01-05 22:25:12 +00003055 // Generate legal pair permutations of A/B/C.
3056 std::vector<TreePatternNode*> ABVariants;
3057 std::vector<TreePatternNode*> BAVariants;
3058 std::vector<TreePatternNode*> ACVariants;
3059 std::vector<TreePatternNode*> CAVariants;
3060 std::vector<TreePatternNode*> BCVariants;
3061 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003062 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3063 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3064 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3065 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3066 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3067 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003068
3069 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00003070 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3071 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3072 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3073 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3074 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3075 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003076
3077 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00003078 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3079 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3080 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3081 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3082 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3083 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003084 return;
3085 }
3086 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003087
Chris Lattner6cefb772008-01-05 22:25:12 +00003088 // Compute permutations of all children.
3089 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3090 ChildVariants.resize(N->getNumChildren());
3091 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003092 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003093
3094 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00003095 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003096
3097 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003098 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3099 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3100 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3101 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003102 // Don't count children which are actually register references.
3103 unsigned NC = 0;
3104 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3105 TreePatternNode *Child = N->getChild(i);
3106 if (Child->isLeaf())
3107 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
3108 Record *RR = DI->getDef();
3109 if (RR->isSubClassOf("Register"))
3110 continue;
3111 }
3112 NC++;
3113 }
3114 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003115 if (isCommIntrinsic) {
3116 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3117 // operands are the commutative operands, and there might be more operands
3118 // after those.
3119 assert(NC >= 3 &&
3120 "Commutative intrinsic should have at least 3 childrean!");
3121 std::vector<std::vector<TreePatternNode*> > Variants;
3122 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3123 Variants.push_back(ChildVariants[2]);
3124 Variants.push_back(ChildVariants[1]);
3125 for (unsigned i = 3; i != NC; ++i)
3126 Variants.push_back(ChildVariants[i]);
3127 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3128 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00003129 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00003130 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003131 }
3132}
3133
3134
3135// GenerateVariants - Generate variants. For example, commutative patterns can
3136// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00003137void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00003138 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003139
Chris Lattner6cefb772008-01-05 22:25:12 +00003140 // Loop over all of the patterns we've collected, checking to see if we can
3141 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00003142 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00003143 // the .td file having to contain tons of variants of instructions.
3144 //
3145 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3146 // intentionally do not reconsider these. Any variants of added patterns have
3147 // already been added.
3148 //
3149 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00003150 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00003151 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00003152 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00003153 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00003154 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00003155 DEBUG(errs() << "\n");
Jim Grosbachbb168242010-10-08 18:13:57 +00003156 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3157 DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003158
3159 assert(!Variants.empty() && "Must create at least original variant!");
3160 Variants.erase(Variants.begin()); // Remove the original pattern.
3161
3162 if (Variants.empty()) // No variants for this pattern.
3163 continue;
3164
Chris Lattner569f1212009-08-23 04:44:11 +00003165 DEBUG(errs() << "FOUND VARIANTS OF: ";
3166 PatternsToMatch[i].getSrcPattern()->dump();
3167 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003168
3169 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3170 TreePatternNode *Variant = Variants[v];
3171
Chris Lattner569f1212009-08-23 04:44:11 +00003172 DEBUG(errs() << " VAR#" << v << ": ";
3173 Variant->dump();
3174 errs() << "\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003175
Chris Lattner6cefb772008-01-05 22:25:12 +00003176 // Scan to see if an instruction or explicit pattern already matches this.
3177 bool AlreadyExists = false;
3178 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00003179 // Skip if the top level predicates do not match.
3180 if (PatternsToMatch[i].getPredicates() !=
3181 PatternsToMatch[p].getPredicates())
3182 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00003183 // Check to see if this variant already exists.
Jim Grosbachbb168242010-10-08 18:13:57 +00003184 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3185 DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00003186 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003187 AlreadyExists = true;
3188 break;
3189 }
3190 }
3191 // If we already have it, ignore the variant.
3192 if (AlreadyExists) continue;
3193
3194 // Otherwise, add it to the list of patterns we have.
3195 PatternsToMatch.
Jim Grosbach997759a2010-12-07 23:05:49 +00003196 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3197 PatternsToMatch[i].getPredicates(),
Chris Lattner6cefb772008-01-05 22:25:12 +00003198 Variant, PatternsToMatch[i].getDstPattern(),
3199 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00003200 PatternsToMatch[i].getAddedComplexity(),
3201 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003202 }
3203
Chris Lattner569f1212009-08-23 04:44:11 +00003204 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003205 }
3206}
3207