blob: 6bb239ac69af92b577738622299991e47f4c770a [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());
59
60 if (!VTList.empty())
61 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62 VTList[0] != MVT::fAny);
63
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());
Chris Lattner774ce292010-03-19 17:41:26 +000075 const std::vector<MVT::SimpleValueType> &LegalTypes =
76 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
77
78 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 " +
85 std::string(PredicateName) + " types found");
86 // 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());
92
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;
103}
104
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;
112}
113
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>";
Chris Lattner2cacec52010-03-15 06:00:16 +0000126
127 std::string Result;
128
129 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 }
137
138 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;
149
150 if (isCompletelyUnknown()) {
151 *this = InVT;
152 return true;
153 }
154
155 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
156
157 // 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);
166
167 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 }
172
173 // If the input has multiple scalar integers, this doesn't add any info.
174 if (!InCopy.isCompletelyUnknown())
175 return false;
176 }
177 break;
178 }
179
180 // 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);
185
186 // 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 }
194
195 return MadeChange;
196 }
197
198 // 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 }
210
211 if (InInVT) continue;
212 TypeVec.erase(TypeVec.begin()+i--);
213 MadeChange = true;
214 }
215
216 // If we removed all of our types, we have a type contradiction.
217 if (!TypeVec.empty())
218 return MadeChange;
219
220 // 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);
Chris Lattner2cacec52010-03-15 06:00:16 +0000235
236 // 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--);
240
241 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);
Chris Lattner2cacec52010-03-15 06:00:16 +0000257
258 // 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--);
262
263 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);
Chris Lattner2cacec52010-03-15 06:00:16 +0000279
280 // 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--);
284
285 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;
299
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 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000306
307 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;
320
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000321 if (isCompletelyUnknown())
322 MadeChange = FillWithPossibleTypes(TP);
323
324 if (Other.isCompletelyUnknown())
325 MadeChange = Other.FillWithPossibleTypes(TP);
326
327 // 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);
337
338 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339 "Should have a type list now");
340
341 // 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);
346
Chris Lattner2cacec52010-03-15 06:00:16 +0000347 // This code does not currently handle nodes which have multiple types,
348 // where some types are integer, and some are fp. Assert that this is not
349 // the case.
350 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
351 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
352 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000353
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000354 // Okay, find the smallest type from the current set and remove it from the
355 // largest set.
356 MVT::SimpleValueType Smallest = TypeVec[0];
357 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
358 if (TypeVec[i] < Smallest)
359 Smallest = TypeVec[i];
Chris Lattner2cacec52010-03-15 06:00:16 +0000360
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000361 // If this is the only type in the large set, the constraint can never be
362 // satisfied.
363 if (Other.TypeVec.size() == 1 && Other.TypeVec[0] == Smallest)
364 TP.error("Type inference contradiction found, '" +
365 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000366
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000367 SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
368 std::find(Other.TypeVec.begin(), Other.TypeVec.end(), Smallest);
369 if (TVI != Other.TypeVec.end()) {
370 Other.TypeVec.erase(TVI);
371 MadeChange = true;
372 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000373
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000374 // Okay, find the largest type in the Other set and remove it from the
375 // current set.
376 MVT::SimpleValueType Largest = Other.TypeVec[0];
377 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
378 if (Other.TypeVec[i] > Largest)
379 Largest = Other.TypeVec[i];
Chris Lattner2cacec52010-03-15 06:00:16 +0000380
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000381 // If this is the only type in the small set, the constraint can never be
382 // satisfied.
383 if (TypeVec.size() == 1 && TypeVec[0] == Largest)
384 TP.error("Type inference contradiction found, '" +
385 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
386
387 TVI = std::find(TypeVec.begin(), TypeVec.end(), Largest);
388 if (TVI != TypeVec.end()) {
389 TypeVec.erase(TVI);
390 MadeChange = true;
391 }
392
393 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000394}
395
396/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner66fb9d22010-03-24 00:01:16 +0000397/// whose element is specified by VTOperand.
398bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattner2cacec52010-03-15 06:00:16 +0000399 TreePattern &TP) {
Chris Lattner66fb9d22010-03-24 00:01:16 +0000400 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattner2cacec52010-03-15 06:00:16 +0000401 bool MadeChange = false;
Chris Lattner66fb9d22010-03-24 00:01:16 +0000402 MadeChange |= EnforceVector(TP);
403 MadeChange |= VTOperand.EnforceScalar(TP);
404
405 // If we know the vector type, it forces the scalar to agree.
406 if (isConcrete()) {
407 EVT IVT = getConcrete();
408 IVT = IVT.getVectorElementType();
409 return MadeChange |
410 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
411 }
412
413 // If the scalar type is known, filter out vector types whose element types
414 // disagree.
415 if (!VTOperand.isConcrete())
416 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000417
Chris Lattner66fb9d22010-03-24 00:01:16 +0000418 MVT::SimpleValueType VT = VTOperand.getConcrete();
Chris Lattner2cacec52010-03-15 06:00:16 +0000419
Chris Lattner66fb9d22010-03-24 00:01:16 +0000420 TypeSet InputSet(*this);
421
422 // Filter out all the types which don't have the right element type.
423 for (unsigned i = 0; i != TypeVec.size(); ++i) {
424 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
425 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000426 TypeVec.erase(TypeVec.begin()+i--);
427 MadeChange = true;
428 }
Chris Lattner66fb9d22010-03-24 00:01:16 +0000429 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000430
431 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
432 TP.error("Type inference contradiction found, forcing '" +
433 InputSet.getName() + "' to have a vector element");
434 return MadeChange;
435}
436
437//===----------------------------------------------------------------------===//
438// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000439
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000440bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
441 return LHS->getID() < RHS->getID();
442}
Scott Michel327d0652008-03-05 17:49:05 +0000443
444/// Dependent variable map for CodeGenDAGPattern variant generation
445typedef std::map<std::string, int> DepVarMap;
446
447/// Const iterator shorthand for DepVarMap
448typedef DepVarMap::const_iterator DepVarMap_citer;
449
450namespace {
451void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
452 if (N->isLeaf()) {
453 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
454 DepMap[N->getName()]++;
455 }
456 } else {
457 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
458 FindDepVarsOf(N->getChild(i), DepMap);
459 }
460}
461
462//! Find dependent variables within child patterns
463/*!
464 */
465void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
466 DepVarMap depcounts;
467 FindDepVarsOf(N, depcounts);
468 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
469 if (i->second > 1) { // std::pair<std::string, int>
470 DepVars.insert(i->first);
471 }
472 }
473}
474
475//! Dump the dependent variable set:
476void DumpDepVars(MultipleUseVarSet &DepVars) {
477 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000478 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000479 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000480 DEBUG(errs() << "[ ");
Scott Michel327d0652008-03-05 17:49:05 +0000481 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
482 i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000483 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000484 }
Chris Lattner569f1212009-08-23 04:44:11 +0000485 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000486 }
487}
488}
489
Chris Lattner6cefb772008-01-05 22:25:12 +0000490//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000491// PatternToMatch implementation
492//
493
494/// getPredicateCheck - Return a single string containing all of this
495/// pattern's predicates concatenated with "&&" operators.
496///
497std::string PatternToMatch::getPredicateCheck() const {
498 std::string PredicateCheck;
499 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
500 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
501 Record *Def = Pred->getDef();
502 if (!Def->isSubClassOf("Predicate")) {
503#ifndef NDEBUG
504 Def->dump();
505#endif
506 assert(0 && "Unknown predicate type!");
507 }
508 if (!PredicateCheck.empty())
509 PredicateCheck += " && ";
510 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
511 }
512 }
513
514 return PredicateCheck;
515}
516
517//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000518// SDTypeConstraint implementation
519//
520
521SDTypeConstraint::SDTypeConstraint(Record *R) {
522 OperandNo = R->getValueAsInt("OperandNum");
523
524 if (R->isSubClassOf("SDTCisVT")) {
525 ConstraintType = SDTCisVT;
526 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerc8122612010-03-28 06:04:39 +0000527 if (x.SDTCisVT_Info.VT == MVT::isVoid)
528 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
529
Chris Lattner6cefb772008-01-05 22:25:12 +0000530 } else if (R->isSubClassOf("SDTCisPtrTy")) {
531 ConstraintType = SDTCisPtrTy;
532 } else if (R->isSubClassOf("SDTCisInt")) {
533 ConstraintType = SDTCisInt;
534 } else if (R->isSubClassOf("SDTCisFP")) {
535 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000536 } else if (R->isSubClassOf("SDTCisVec")) {
537 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000538 } else if (R->isSubClassOf("SDTCisSameAs")) {
539 ConstraintType = SDTCisSameAs;
540 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
541 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
542 ConstraintType = SDTCisVTSmallerThanOp;
543 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
544 R->getValueAsInt("OtherOperandNum");
545 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
546 ConstraintType = SDTCisOpSmallerThanOp;
547 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
548 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000549 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
550 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000551 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000552 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000553 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000554 exit(1);
555 }
556}
557
558/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000559/// N, and the result number in ResNo.
560static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
561 const SDNodeInfo &NodeInfo,
562 unsigned &ResNo) {
563 unsigned NumResults = NodeInfo.getNumResults();
564 if (OpNo < NumResults) {
565 ResNo = OpNo;
566 return N;
567 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000568
Chris Lattner2e68a022010-03-19 21:56:21 +0000569 OpNo -= NumResults;
570
571 if (OpNo >= N->getNumChildren()) {
572 errs() << "Invalid operand number in type constraint "
573 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000574 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000575 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000576 exit(1);
577 }
578
Chris Lattner2e68a022010-03-19 21:56:21 +0000579 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000580}
581
582/// ApplyTypeConstraint - Given a node in a pattern, apply this type
583/// constraint to the nodes operands. This returns true if it makes a
584/// change, false otherwise. If a type contradiction is found, throw an
585/// exception.
586bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
587 const SDNodeInfo &NodeInfo,
588 TreePattern &TP) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000589 // Check that the number of operands is sane. Negative operands -> varargs.
590 if (NodeInfo.getNumOperands() >= 0) {
591 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
592 TP.error(N->getOperator()->getName() + " node requires exactly " +
593 itostr(NodeInfo.getNumOperands()) + " operands!");
594 }
595
Chris Lattner2e68a022010-03-19 21:56:21 +0000596 unsigned ResNo = 0; // The result number being referenced.
597 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000598
599 switch (ConstraintType) {
600 default: assert(0 && "Unknown constraint type!");
601 case SDTCisVT:
602 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000603 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000604 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000605 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000606 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000607 case SDTCisInt:
608 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000609 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000610 case SDTCisFP:
611 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000612 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000613 case SDTCisVec:
614 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000615 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000616 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000617 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000618 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000619 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000620 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
621 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000622 }
623 case SDTCisVTSmallerThanOp: {
624 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
625 // have an integer type that is smaller than the VT.
626 if (!NodeToApply->isLeaf() ||
627 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
628 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
629 ->isSubClassOf("ValueType"))
630 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000631 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000632 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Chris Lattnercc878302010-03-24 00:06:46 +0000633
634 EEVT::TypeSet TypeListTmp(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000635
Chris Lattner2e68a022010-03-19 21:56:21 +0000636 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000637 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000638 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
639 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000640
Chris Lattnercc878302010-03-24 00:06:46 +0000641 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000642 }
643 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000644 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000645 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000646 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
647 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000648 return NodeToApply->getExtType(ResNo).
649 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000650 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000651 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000652 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000653 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000654 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
655 VResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000656
Chris Lattner66fb9d22010-03-24 00:01:16 +0000657 // Filter vector types out of VecOperand that don't have the right element
658 // type.
659 return VecOperand->getExtType(VResNo).
660 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000661 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000662 }
663 return false;
664}
665
666//===----------------------------------------------------------------------===//
667// SDNodeInfo implementation
668//
669SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
670 EnumName = R->getValueAsString("Opcode");
671 SDClassName = R->getValueAsString("SDClass");
672 Record *TypeProfile = R->getValueAsDef("TypeProfile");
673 NumResults = TypeProfile->getValueAsInt("NumResults");
674 NumOperands = TypeProfile->getValueAsInt("NumOperands");
675
676 // Parse the properties.
677 Properties = 0;
678 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
679 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
680 if (PropList[i]->getName() == "SDNPCommutative") {
681 Properties |= 1 << SDNPCommutative;
682 } else if (PropList[i]->getName() == "SDNPAssociative") {
683 Properties |= 1 << SDNPAssociative;
684 } else if (PropList[i]->getName() == "SDNPHasChain") {
685 Properties |= 1 << SDNPHasChain;
686 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000687 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000688 } else if (PropList[i]->getName() == "SDNPInFlag") {
689 Properties |= 1 << SDNPInFlag;
690 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
691 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000692 } else if (PropList[i]->getName() == "SDNPMayStore") {
693 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000694 } else if (PropList[i]->getName() == "SDNPMayLoad") {
695 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000696 } else if (PropList[i]->getName() == "SDNPSideEffect") {
697 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000698 } else if (PropList[i]->getName() == "SDNPMemOperand") {
699 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000700 } else if (PropList[i]->getName() == "SDNPVariadic") {
701 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000702 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000703 errs() << "Unknown SD Node property '" << PropList[i]->getName()
704 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000705 exit(1);
706 }
707 }
708
709
710 // Parse the type constraints.
711 std::vector<Record*> ConstraintList =
712 TypeProfile->getValueAsListOfDefs("Constraints");
713 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
714}
715
Chris Lattner22579812010-02-28 00:22:30 +0000716/// getKnownType - If the type constraints on this node imply a fixed type
717/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000718/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000719MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +0000720 unsigned NumResults = getNumResults();
721 assert(NumResults <= 1 &&
722 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +0000723 assert(ResNo == 0 && "Only handles single result nodes so far");
Chris Lattner22579812010-02-28 00:22:30 +0000724
725 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
726 // Make sure that this applies to the correct node result.
727 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
728 continue;
729
730 switch (TypeConstraints[i].ConstraintType) {
731 default: break;
732 case SDTypeConstraint::SDTCisVT:
733 return TypeConstraints[i].x.SDTCisVT_Info.VT;
734 case SDTypeConstraint::SDTCisPtrTy:
735 return MVT::iPTR;
736 }
737 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000738 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000739}
740
Chris Lattner6cefb772008-01-05 22:25:12 +0000741//===----------------------------------------------------------------------===//
742// TreePatternNode implementation
743//
744
745TreePatternNode::~TreePatternNode() {
746#if 0 // FIXME: implement refcounted tree nodes!
747 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
748 delete getChild(i);
749#endif
750}
751
Chris Lattnerd7349192010-03-19 21:37:09 +0000752static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
753 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +0000754 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +0000755 return 0; // All return nothing.
756
Chris Lattner93dc92e2010-03-22 20:56:36 +0000757 if (Operator->isSubClassOf("Intrinsic"))
758 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Chris Lattner6cefb772008-01-05 22:25:12 +0000759
Chris Lattnerd7349192010-03-19 21:37:09 +0000760 if (Operator->isSubClassOf("SDNode"))
761 return CDP.getSDNodeInfo(Operator).getNumResults();
762
763 if (Operator->isSubClassOf("PatFrag")) {
764 // If we've already parsed this pattern fragment, get it. Otherwise, handle
765 // the forward reference case where one pattern fragment references another
766 // before it is processed.
767 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
768 return PFRec->getOnlyTree()->getNumTypes();
769
770 // Get the result tree.
771 DagInit *Tree = Operator->getValueAsDag("Fragment");
772 Record *Op = 0;
773 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
774 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
775 assert(Op && "Invalid Fragment");
776 return GetNumNodeResults(Op, CDP);
777 }
778
779 if (Operator->isSubClassOf("Instruction")) {
780 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +0000781
782 // FIXME: Should allow access to all the results here.
783 unsigned NumDefsToAdd = InstInfo.NumDefs ? 1 : 0;
Chris Lattnerd7349192010-03-19 21:37:09 +0000784
Chris Lattner9414ae52010-03-27 20:09:24 +0000785 // Add on one implicit def if it has a resolvable type.
786 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
787 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +0000788 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +0000789 }
790
791 if (Operator->isSubClassOf("SDNodeXForm"))
792 return 1; // FIXME: Generalize SDNodeXForm
793
794 Operator->dump();
795 errs() << "Unhandled node in GetNumNodeResults\n";
796 exit(1);
797}
798
799void TreePatternNode::print(raw_ostream &OS) const {
800 if (isLeaf())
801 OS << *getLeafValue();
802 else
803 OS << '(' << getOperator()->getName();
804
805 for (unsigned i = 0, e = Types.size(); i != e; ++i)
806 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000807
808 if (!isLeaf()) {
809 if (getNumChildren() != 0) {
810 OS << " ";
811 getChild(0)->print(OS);
812 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
813 OS << ", ";
814 getChild(i)->print(OS);
815 }
816 }
817 OS << ")";
818 }
819
Dan Gohman0540e172008-10-15 06:17:21 +0000820 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
821 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000822 if (TransformFn)
823 OS << "<<X:" << TransformFn->getName() << ">>";
824 if (!getName().empty())
825 OS << ":$" << getName();
826
827}
828void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000829 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000830}
831
Scott Michel327d0652008-03-05 17:49:05 +0000832/// isIsomorphicTo - Return true if this node is recursively
833/// isomorphic to the specified node. For this comparison, the node's
834/// entire state is considered. The assigned name is ignored, since
835/// nodes with differing names are considered isomorphic. However, if
836/// the assigned name is present in the dependent variable set, then
837/// the assigned name is considered significant and the node is
838/// isomorphic if the names match.
839bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
840 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000841 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +0000842 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000843 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000844 getTransformFn() != N->getTransformFn())
845 return false;
846
847 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000848 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
849 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000850 return ((DI->getDef() == NDI->getDef())
851 && (DepVars.find(getName()) == DepVars.end()
852 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000853 }
854 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000855 return getLeafValue() == N->getLeafValue();
856 }
857
858 if (N->getOperator() != getOperator() ||
859 N->getNumChildren() != getNumChildren()) return false;
860 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000861 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000862 return false;
863 return true;
864}
865
866/// clone - Make a copy of this tree and all of its children.
867///
868TreePatternNode *TreePatternNode::clone() const {
869 TreePatternNode *New;
870 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +0000871 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000872 } else {
873 std::vector<TreePatternNode*> CChildren;
874 CChildren.reserve(Children.size());
875 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
876 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +0000877 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000878 }
879 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +0000880 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +0000881 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000882 New->setTransformFn(getTransformFn());
883 return New;
884}
885
Chris Lattner47661322010-02-14 22:22:58 +0000886/// RemoveAllTypes - Recursively strip all the types of this tree.
887void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +0000888 for (unsigned i = 0, e = Types.size(); i != e; ++i)
889 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +0000890 if (isLeaf()) return;
891 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
892 getChild(i)->RemoveAllTypes();
893}
894
895
Chris Lattner6cefb772008-01-05 22:25:12 +0000896/// SubstituteFormalArguments - Replace the formal arguments in this tree
897/// with actual values specified by ArgMap.
898void TreePatternNode::
899SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
900 if (isLeaf()) return;
901
902 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
903 TreePatternNode *Child = getChild(i);
904 if (Child->isLeaf()) {
905 Init *Val = Child->getLeafValue();
906 if (dynamic_cast<DefInit*>(Val) &&
907 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
908 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000909 TreePatternNode *NewChild = ArgMap[Child->getName()];
910 assert(NewChild && "Couldn't find formal argument!");
911 assert((Child->getPredicateFns().empty() ||
912 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
913 "Non-empty child predicate clobbered!");
914 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000915 }
916 } else {
917 getChild(i)->SubstituteFormalArguments(ArgMap);
918 }
919 }
920}
921
922
923/// InlinePatternFragments - If this pattern refers to any pattern
924/// fragments, inline them into place, giving us a pattern without any
925/// PatFrag references.
926TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
927 if (isLeaf()) return this; // nothing to do.
928 Record *Op = getOperator();
929
930 if (!Op->isSubClassOf("PatFrag")) {
931 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000932 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
933 TreePatternNode *Child = getChild(i);
934 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
935
936 assert((Child->getPredicateFns().empty() ||
937 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
938 "Non-empty child predicate clobbered!");
939
940 setChild(i, NewChild);
941 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000942 return this;
943 }
944
945 // Otherwise, we found a reference to a fragment. First, look up its
946 // TreePattern record.
947 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
948
949 // Verify that we are passing the right number of operands.
950 if (Frag->getNumArgs() != Children.size())
951 TP.error("'" + Op->getName() + "' fragment requires " +
952 utostr(Frag->getNumArgs()) + " operands!");
953
954 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
955
Dan Gohman0540e172008-10-15 06:17:21 +0000956 std::string Code = Op->getValueAsCode("Predicate");
957 if (!Code.empty())
958 FragTree->addPredicateFn("Predicate_"+Op->getName());
959
Chris Lattner6cefb772008-01-05 22:25:12 +0000960 // Resolve formal arguments to their actual value.
961 if (Frag->getNumArgs()) {
962 // Compute the map of formal to actual arguments.
963 std::map<std::string, TreePatternNode*> ArgMap;
964 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
965 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
966
967 FragTree->SubstituteFormalArguments(ArgMap);
968 }
969
970 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +0000971 for (unsigned i = 0, e = Types.size(); i != e; ++i)
972 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000973
974 // Transfer in the old predicates.
975 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
976 FragTree->addPredicateFn(getPredicateFns()[i]);
977
Chris Lattner6cefb772008-01-05 22:25:12 +0000978 // Get a new copy of this fragment to stitch into here.
979 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000980
981 // The fragment we inlined could have recursive inlining that is needed. See
982 // if there are any pattern fragments in it and inline them as needed.
983 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000984}
985
986/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000987/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +0000988/// references from the register file information, for example.
989///
Chris Lattnerd7349192010-03-19 21:37:09 +0000990static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
991 bool NotRegisters, TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000992 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +0000993 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +0000994 assert(ResNo == 0 && "Regclass ref only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +0000995 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000996 return EEVT::TypeSet(); // Unknown.
997 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
998 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +0000999 }
1000
1001 if (R->isSubClassOf("PatFrag")) {
1002 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001003 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001004 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001005 }
1006
1007 if (R->isSubClassOf("Register")) {
1008 assert(ResNo == 0 && "Registers only produce one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001009 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001010 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001011 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001012 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001013 }
1014
1015 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1016 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001017 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001018 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001019 }
1020
1021 if (R->isSubClassOf("ComplexPattern")) {
1022 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001023 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001024 return EEVT::TypeSet(); // Unknown.
1025 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1026 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001027 }
1028 if (R->isSubClassOf("PointerLikeRegClass")) {
1029 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001030 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001031 }
1032
1033 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1034 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001035 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001036 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001037 }
1038
1039 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001040 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001041}
1042
Chris Lattnere67bde52008-01-06 05:36:50 +00001043
1044/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1045/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1046const CodeGenIntrinsic *TreePatternNode::
1047getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1048 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1049 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1050 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1051 return 0;
1052
1053 unsigned IID =
1054 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1055 return &CDP.getIntrinsicInfo(IID);
1056}
1057
Chris Lattner47661322010-02-14 22:22:58 +00001058/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1059/// return the ComplexPattern information, otherwise return null.
1060const ComplexPattern *
1061TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1062 if (!isLeaf()) return 0;
1063
1064 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1065 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1066 return &CGP.getComplexPattern(DI->getDef());
1067 return 0;
1068}
1069
1070/// NodeHasProperty - Return true if this node has the specified property.
1071bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001072 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001073 if (isLeaf()) {
1074 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1075 return CP->hasProperty(Property);
1076 return false;
1077 }
1078
1079 Record *Operator = getOperator();
1080 if (!Operator->isSubClassOf("SDNode")) return false;
1081
1082 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1083}
1084
1085
1086
1087
1088/// TreeHasProperty - Return true if any node in this tree has the specified
1089/// property.
1090bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001091 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001092 if (NodeHasProperty(Property, CGP))
1093 return true;
1094 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1095 if (getChild(i)->TreeHasProperty(Property, CGP))
1096 return true;
1097 return false;
1098}
1099
Evan Cheng6bd95672008-06-16 20:29:38 +00001100/// isCommutativeIntrinsic - Return true if the node corresponds to a
1101/// commutative intrinsic.
1102bool
1103TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1104 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1105 return Int->isCommutative;
1106 return false;
1107}
1108
Chris Lattnere67bde52008-01-06 05:36:50 +00001109
Bob Wilson6c01ca92009-01-05 17:23:09 +00001110/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001111/// this node and its children in the tree. This returns true if it makes a
1112/// change, false otherwise. If a type contradiction is found, throw an
1113/// exception.
1114bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001115 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001116 if (isLeaf()) {
1117 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1118 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001119 bool MadeChange = false;
1120 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1121 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1122 NotRegisters, TP), TP);
1123 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001124 }
1125
1126 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001127 assert(Types.size() == 1 && "Invalid IntInit");
Chris Lattner6cefb772008-01-05 22:25:12 +00001128
Chris Lattnerd7349192010-03-19 21:37:09 +00001129 // Int inits are always integers. :)
1130 bool MadeChange = Types[0].EnforceInteger(TP);
1131
1132 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001133 return MadeChange;
1134
Chris Lattnerd7349192010-03-19 21:37:09 +00001135 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001136 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1137 return MadeChange;
1138
1139 unsigned Size = EVT(VT).getSizeInBits();
1140 // Make sure that the value is representable for this type.
1141 if (Size >= 32) return MadeChange;
1142
1143 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1144 if (Val == II->getValue()) return MadeChange;
1145
1146 // If sign-extended doesn't fit, does it fit as unsigned?
1147 unsigned ValueMask;
1148 unsigned UnsignedVal;
1149 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1150 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001151
Chris Lattner2cacec52010-03-15 06:00:16 +00001152 if ((ValueMask & UnsignedVal) == UnsignedVal)
1153 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001154
Chris Lattner2cacec52010-03-15 06:00:16 +00001155 TP.error("Integer value '" + itostr(II->getValue())+
Chris Lattnerd7349192010-03-19 21:37:09 +00001156 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001157 return MadeChange;
1158 }
1159 return false;
1160 }
1161
1162 // special handling for set, which isn't really an SDNode.
1163 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001164 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1165 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001166 unsigned NC = getNumChildren();
Chris Lattnerd7349192010-03-19 21:37:09 +00001167
1168 TreePatternNode *SetVal = getChild(NC-1);
1169 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1170
Chris Lattner6cefb772008-01-05 22:25:12 +00001171 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001172 TreePatternNode *Child = getChild(i);
1173 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001174
1175 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001176 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1177 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001178 }
1179 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001180 }
1181
Chris Lattner310adf12010-03-27 02:53:27 +00001182 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001183 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1184
Chris Lattner6cefb772008-01-05 22:25:12 +00001185 bool MadeChange = false;
1186 for (unsigned i = 0; i < getNumChildren(); ++i)
1187 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001188 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001189 }
1190
1191 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001192 bool MadeChange = false;
1193 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1194 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner2cacec52010-03-15 06:00:16 +00001195
Chris Lattnerd7349192010-03-19 21:37:09 +00001196 assert(getChild(0)->getNumTypes() == 1 &&
1197 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1198
Chris Lattner2cacec52010-03-15 06:00:16 +00001199 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1200 // what type it gets, so if it didn't get a concrete type just give it the
1201 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001202 if (!getChild(1)->hasTypeSet(0) &&
1203 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1204 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1205 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001206 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001207 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001208 }
1209
1210 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001211 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001212
Chris Lattner6cefb772008-01-05 22:25:12 +00001213 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001214 unsigned NumRetVTs = Int->IS.RetVTs.size();
1215 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Chris Lattnerd7349192010-03-19 21:37:09 +00001216
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001217 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001218 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001219
Chris Lattnerd7349192010-03-19 21:37:09 +00001220 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001221 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001222 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001223 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001224
1225 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001226 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001227
Chris Lattnerd7349192010-03-19 21:37:09 +00001228 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1229 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1230
1231 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1232 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1233 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001234 }
1235 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001236 }
1237
1238 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001239 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1240
1241 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1242 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1243 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001244 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001245 }
1246
1247 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001248 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001249 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001250 CDP.getTargetInfo().getInstruction(getOperator());
Chris Lattner6c6ba362010-03-18 23:15:10 +00001251
Chris Lattner0be6fe72010-03-27 19:15:02 +00001252 bool MadeChange = false;
1253
1254 // Apply the result types to the node, these come from the things in the
1255 // (outs) list of the instruction.
1256 // FIXME: Cap at one result so far.
1257 unsigned NumResultsToAdd = InstInfo.NumDefs ? 1 : 0;
1258 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1259 Record *ResultNode = Inst.getResult(ResNo);
Chris Lattner6cefb772008-01-05 22:25:12 +00001260
Chris Lattnera938ac62009-07-29 20:43:05 +00001261 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001262 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001263 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001264 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001265 } else {
1266 assert(ResultNode->isSubClassOf("RegisterClass") &&
1267 "Operands should be register classes!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001268 const CodeGenRegisterClass &RC =
1269 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001270 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001271 }
Chris Lattner0be6fe72010-03-27 19:15:02 +00001272 }
1273
1274 // If the instruction has implicit defs, we apply the first one as a result.
1275 // FIXME: This sucks, it should apply all implicit defs.
1276 if (!InstInfo.ImplicitDefs.empty()) {
1277 unsigned ResNo = NumResultsToAdd;
1278
Chris Lattner9414ae52010-03-27 20:09:24 +00001279 // FIXME: Generalize to multiple possible types and multiple possible
1280 // ImplicitDefs.
1281 MVT::SimpleValueType VT =
1282 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1283
1284 if (VT != MVT::Other)
1285 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001286 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001287
1288 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1289 // be the same.
1290 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001291 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1292 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1293 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001294 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001295
1296 unsigned ChildNo = 0;
1297 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1298 Record *OperandNode = Inst.getOperand(i);
1299
1300 // If the instruction expects a predicate or optional def operand, we
1301 // codegen this by setting the operand to it's default value if it has a
1302 // non-empty DefaultOps field.
1303 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1304 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1305 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1306 continue;
1307
1308 // Verify that we didn't run out of provided operands.
1309 if (ChildNo >= getNumChildren())
1310 TP.error("Instruction '" + getOperator()->getName() +
1311 "' expects more operands than were provided.");
1312
Owen Anderson825b72b2009-08-11 20:47:22 +00001313 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001314 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001315 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Chris Lattnerd7349192010-03-19 21:37:09 +00001316
Chris Lattner6cefb772008-01-05 22:25:12 +00001317 if (OperandNode->isSubClassOf("RegisterClass")) {
1318 const CodeGenRegisterClass &RC =
1319 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001320 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001321 } else if (OperandNode->isSubClassOf("Operand")) {
1322 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattner0be6fe72010-03-27 19:15:02 +00001323 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001324 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001325 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001326 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001327 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001328 } else {
1329 assert(0 && "Unknown operand type!");
1330 abort();
1331 }
1332 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1333 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001334
Christopher Lamb02f69372008-03-10 04:16:09 +00001335 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001336 TP.error("Instruction '" + getOperator()->getName() +
1337 "' was provided too many operands!");
1338
1339 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001340 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001341
1342 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1343
1344 // Node transforms always take one operand.
1345 if (getNumChildren() != 1)
1346 TP.error("Node transform '" + getOperator()->getName() +
1347 "' requires one operand!");
1348
Chris Lattner2cacec52010-03-15 06:00:16 +00001349 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1350
1351
Chris Lattner6eb30122010-02-23 05:51:07 +00001352 // If either the output or input of the xform does not have exact
1353 // type info. We assume they must be the same. Otherwise, it is perfectly
1354 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001355#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001356 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001357 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1358 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001359 return MadeChange;
1360 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001361#endif
1362 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001363}
1364
1365/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1366/// RHS of a commutative operation, not the on LHS.
1367static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1368 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1369 return true;
1370 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1371 return true;
1372 return false;
1373}
1374
1375
1376/// canPatternMatch - If it is impossible for this pattern to match on this
1377/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001378/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001379/// that can never possibly work), and to prevent the pattern permuter from
1380/// generating stuff that is useless.
1381bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001382 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001383 if (isLeaf()) return true;
1384
1385 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1386 if (!getChild(i)->canPatternMatch(Reason, CDP))
1387 return false;
1388
1389 // If this is an intrinsic, handle cases that would make it not match. For
1390 // example, if an operand is required to be an immediate.
1391 if (getOperator()->isSubClassOf("Intrinsic")) {
1392 // TODO:
1393 return true;
1394 }
1395
1396 // If this node is a commutative operator, check that the LHS isn't an
1397 // immediate.
1398 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001399 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1400 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001401 // Scan all of the operands of the node and make sure that only the last one
1402 // is a constant node, unless the RHS also is.
1403 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001404 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1405 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001406 if (OnlyOnRHSOfCommutative(getChild(i))) {
1407 Reason="Immediate value must be on the RHS of commutative operators!";
1408 return false;
1409 }
1410 }
1411 }
1412
1413 return true;
1414}
1415
1416//===----------------------------------------------------------------------===//
1417// TreePattern implementation
1418//
1419
1420TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001421 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001422 isInputPattern = isInput;
1423 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattnerc2173052010-03-28 06:50:34 +00001424 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001425}
1426
1427TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001428 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001429 isInputPattern = isInput;
Chris Lattnerc2173052010-03-28 06:50:34 +00001430 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001431}
1432
1433TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001434 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001435 isInputPattern = isInput;
1436 Trees.push_back(Pat);
1437}
1438
Chris Lattner6cefb772008-01-05 22:25:12 +00001439void TreePattern::error(const std::string &Msg) const {
1440 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001441 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001442}
1443
Chris Lattner2cacec52010-03-15 06:00:16 +00001444void TreePattern::ComputeNamedNodes() {
1445 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1446 ComputeNamedNodes(Trees[i]);
1447}
1448
1449void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1450 if (!N->getName().empty())
1451 NamedNodes[N->getName()].push_back(N);
1452
1453 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1454 ComputeNamedNodes(N->getChild(i));
1455}
1456
Chris Lattnerd7349192010-03-19 21:37:09 +00001457
Chris Lattnerc2173052010-03-28 06:50:34 +00001458TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1459 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
1460 Record *R = DI->getDef();
1461
1462 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1463 // TreePatternNode if its own. For example:
1464 /// (foo GPR, imm) -> (foo GPR, (imm))
1465 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1466 return ParseTreePattern(new DagInit(DI, "",
1467 std::vector<std::pair<Init*, std::string> >()),
1468 OpName);
1469
1470 // Input argument?
1471 TreePatternNode *Res = new TreePatternNode(DI, 1);
1472 if (R->getName() == "node") {
1473 if (OpName.empty())
1474 error("'node' argument requires a name to match with operand list");
1475 Args.push_back(OpName);
1476 }
1477
1478 Res->setName(OpName);
1479 return Res;
1480 }
1481
1482 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
1483 if (!OpName.empty())
1484 error("Constant int argument should not have a name!");
1485 return new TreePatternNode(II, 1);
1486 }
1487
1488 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
1489 // Turn this into an IntInit.
1490 Init *II = BI->convertInitializerTo(new IntRecTy());
1491 if (II == 0 || !dynamic_cast<IntInit*>(II))
1492 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001493 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00001494 }
1495
1496 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
1497 if (!Dag) {
1498 TheInit->dump();
1499 error("Pattern has unexpected init kind!");
1500 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001501 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1502 if (!OpDef) error("Pattern has unexpected operator type!");
1503 Record *Operator = OpDef->getDef();
1504
1505 if (Operator->isSubClassOf("ValueType")) {
1506 // If the operator is a ValueType, then this must be "type cast" of a leaf
1507 // node.
1508 if (Dag->getNumArgs() != 1)
1509 error("Type cast only takes one operand!");
1510
Chris Lattnerc2173052010-03-28 06:50:34 +00001511 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001512
1513 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001514 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1515 New->UpdateNodeType(0, getValueType(Operator), *this);
Chris Lattnerc2173052010-03-28 06:50:34 +00001516
1517 if (!OpName.empty())
1518 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001519 return New;
1520 }
1521
1522 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001523 if (!Operator->isSubClassOf("PatFrag") &&
1524 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001525 !Operator->isSubClassOf("Instruction") &&
1526 !Operator->isSubClassOf("SDNodeXForm") &&
1527 !Operator->isSubClassOf("Intrinsic") &&
1528 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001529 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001530 error("Unrecognized node '" + Operator->getName() + "'!");
1531
1532 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001533 if (isInputPattern) {
1534 if (Operator->isSubClassOf("Instruction") ||
1535 Operator->isSubClassOf("SDNodeXForm"))
1536 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1537 } else {
1538 if (Operator->isSubClassOf("Intrinsic"))
1539 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1540
1541 if (Operator->isSubClassOf("SDNode") &&
1542 Operator->getName() != "imm" &&
1543 Operator->getName() != "fpimm" &&
1544 Operator->getName() != "tglobaltlsaddr" &&
1545 Operator->getName() != "tconstpool" &&
1546 Operator->getName() != "tjumptable" &&
1547 Operator->getName() != "tframeindex" &&
1548 Operator->getName() != "texternalsym" &&
1549 Operator->getName() != "tblockaddress" &&
1550 Operator->getName() != "tglobaladdr" &&
1551 Operator->getName() != "bb" &&
1552 Operator->getName() != "vt")
1553 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1554 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001555
1556 std::vector<TreePatternNode*> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00001557
1558 // Parse all the operands.
1559 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1560 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001561
1562 // If the operator is an intrinsic, then this is just syntactic sugar for for
1563 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1564 // convert the intrinsic name to a number.
1565 if (Operator->isSubClassOf("Intrinsic")) {
1566 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1567 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1568
1569 // If this intrinsic returns void, it must have side-effects and thus a
1570 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00001571 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001572 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001573 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00001574 // Has side-effects, requires chain.
1575 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001576 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00001577 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Chris Lattner6cefb772008-01-05 22:25:12 +00001578
Chris Lattnerd7349192010-03-19 21:37:09 +00001579 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001580 Children.insert(Children.begin(), IIDNode);
1581 }
1582
Chris Lattnerd7349192010-03-19 21:37:09 +00001583 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1584 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00001585 Result->setName(OpName);
1586
1587 if (!Dag->getName().empty()) {
1588 assert(Result->getName().empty());
1589 Result->setName(Dag->getName());
1590 }
Nate Begeman7cee8172009-03-19 05:21:56 +00001591 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001592}
1593
1594/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001595/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001596/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001597bool TreePattern::
1598InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1599 if (NamedNodes.empty())
1600 ComputeNamedNodes();
1601
Chris Lattner6cefb772008-01-05 22:25:12 +00001602 bool MadeChange = true;
1603 while (MadeChange) {
1604 MadeChange = false;
1605 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1606 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner2cacec52010-03-15 06:00:16 +00001607
1608 // If there are constraints on our named nodes, apply them.
1609 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1610 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1611 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1612
1613 // If we have input named node types, propagate their types to the named
1614 // values here.
1615 if (InNamedTypes) {
1616 // FIXME: Should be error?
1617 assert(InNamedTypes->count(I->getKey()) &&
1618 "Named node in output pattern but not input pattern?");
1619
1620 const SmallVectorImpl<TreePatternNode*> &InNodes =
1621 InNamedTypes->find(I->getKey())->second;
1622
1623 // The input types should be fully resolved by now.
1624 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1625 // If this node is a register class, and it is the root of the pattern
1626 // then we're mapping something onto an input register. We allow
1627 // changing the type of the input register in this case. This allows
1628 // us to match things like:
1629 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1630 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1631 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1632 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1633 continue;
1634 }
1635
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001636 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001637 InNodes[0]->getNumTypes() == 1 &&
1638 "FIXME: cannot name multiple result nodes yet");
1639 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1640 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001641 }
1642 }
1643
1644 // If there are multiple nodes with the same name, they must all have the
1645 // same type.
1646 if (I->second.size() > 1) {
1647 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001648 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001649 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001650 "FIXME: cannot name multiple result nodes yet");
1651
1652 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1653 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001654 }
1655 }
1656 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001657 }
1658
1659 bool HasUnresolvedTypes = false;
1660 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1661 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1662 return !HasUnresolvedTypes;
1663}
1664
Daniel Dunbar1a551802009-07-03 00:10:29 +00001665void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001666 OS << getRecord()->getName();
1667 if (!Args.empty()) {
1668 OS << "(" << Args[0];
1669 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1670 OS << ", " << Args[i];
1671 OS << ")";
1672 }
1673 OS << ": ";
1674
1675 if (Trees.size() > 1)
1676 OS << "[\n";
1677 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1678 OS << "\t";
1679 Trees[i]->print(OS);
1680 OS << "\n";
1681 }
1682
1683 if (Trees.size() > 1)
1684 OS << "]\n";
1685}
1686
Daniel Dunbar1a551802009-07-03 00:10:29 +00001687void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001688
1689//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001690// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001691//
1692
Chris Lattnerfe718932008-01-06 01:10:31 +00001693CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001694 Intrinsics = LoadIntrinsics(Records, false);
1695 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001696 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001697 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001698 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001699 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001700 ParseDefaultOperands();
1701 ParseInstructions();
1702 ParsePatterns();
1703
1704 // Generate variants. For example, commutative patterns can match
1705 // multiple ways. Add them to PatternsToMatch as well.
1706 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001707
1708 // Infer instruction flags. For example, we can detect loads,
1709 // stores, and side effects in many cases by examining an
1710 // instruction's pattern.
1711 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001712}
1713
Chris Lattnerfe718932008-01-06 01:10:31 +00001714CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001715 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001716 E = PatternFragments.end(); I != E; ++I)
1717 delete I->second;
1718}
1719
1720
Chris Lattnerfe718932008-01-06 01:10:31 +00001721Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001722 Record *N = Records.getDef(Name);
1723 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001724 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001725 exit(1);
1726 }
1727 return N;
1728}
1729
1730// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001731void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001732 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1733 while (!Nodes.empty()) {
1734 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1735 Nodes.pop_back();
1736 }
1737
Jim Grosbachda4231f2009-03-26 16:17:51 +00001738 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001739 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1740 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1741 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1742}
1743
1744/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1745/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001746void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001747 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1748 while (!Xforms.empty()) {
1749 Record *XFormNode = Xforms.back();
1750 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1751 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001752 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001753
1754 Xforms.pop_back();
1755 }
1756}
1757
Chris Lattnerfe718932008-01-06 01:10:31 +00001758void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001759 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1760 while (!AMs.empty()) {
1761 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1762 AMs.pop_back();
1763 }
1764}
1765
1766
1767/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1768/// file, building up the PatternFragments map. After we've collected them all,
1769/// inline fragments together as necessary, so that there are no references left
1770/// inside a pattern fragment to a pattern fragment.
1771///
Chris Lattnerfe718932008-01-06 01:10:31 +00001772void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001773 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1774
Chris Lattnerdc32f982008-01-05 22:43:57 +00001775 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001776 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1777 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1778 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1779 PatternFragments[Fragments[i]] = P;
1780
Chris Lattnerdc32f982008-01-05 22:43:57 +00001781 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001782 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001783 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001784
Chris Lattnerdc32f982008-01-05 22:43:57 +00001785 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001786 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1787
1788 // Parse the operands list.
1789 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1790 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1791 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001792 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001793 if (!OpsOp ||
1794 (OpsOp->getDef()->getName() != "ops" &&
1795 OpsOp->getDef()->getName() != "outs" &&
1796 OpsOp->getDef()->getName() != "ins"))
1797 P->error("Operands list should start with '(ops ... '!");
1798
1799 // Copy over the arguments.
1800 Args.clear();
1801 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1802 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1803 static_cast<DefInit*>(OpsList->getArg(j))->
1804 getDef()->getName() != "node")
1805 P->error("Operands list should all be 'node' values.");
1806 if (OpsList->getArgName(j).empty())
1807 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001808 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001809 P->error("'" + OpsList->getArgName(j) +
1810 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001811 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001812 Args.push_back(OpsList->getArgName(j));
1813 }
1814
Chris Lattnerdc32f982008-01-05 22:43:57 +00001815 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001816 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001817 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001818
Chris Lattnerdc32f982008-01-05 22:43:57 +00001819 // If there is a code init for this fragment, keep track of the fact that
1820 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001821 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001822 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001823 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001824
1825 // If there is a node transformation corresponding to this, keep track of
1826 // it.
1827 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1828 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1829 P->getOnlyTree()->setTransformFn(Transform);
1830 }
1831
Chris Lattner6cefb772008-01-05 22:25:12 +00001832 // Now that we've parsed all of the tree fragments, do a closure on them so
1833 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001834 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1835 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001836 ThePat->InlinePatternFragments();
1837
1838 // Infer as many types as possible. Don't worry about it if we don't infer
1839 // all of them, some may depend on the inputs of the pattern.
1840 try {
1841 ThePat->InferAllTypes();
1842 } catch (...) {
1843 // If this pattern fragment is not supported by this target (no types can
1844 // satisfy its constraints), just ignore it. If the bogus pattern is
1845 // actually used by instructions, the type consistency error will be
1846 // reported there.
1847 }
1848
1849 // If debugging, print out the pattern fragment result.
1850 DEBUG(ThePat->dump());
1851 }
1852}
1853
Chris Lattnerfe718932008-01-06 01:10:31 +00001854void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001855 std::vector<Record*> DefaultOps[2];
1856 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1857 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1858
1859 // Find some SDNode.
1860 assert(!SDNodes.empty() && "No SDNodes parsed?");
1861 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1862
1863 for (unsigned iter = 0; iter != 2; ++iter) {
1864 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1865 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1866
1867 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1868 // SomeSDnode so that we can parse this.
1869 std::vector<std::pair<Init*, std::string> > Ops;
1870 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1871 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1872 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001873 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001874
1875 // Create a TreePattern to parse this.
1876 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1877 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1878
1879 // Copy the operands over into a DAGDefaultOperand.
1880 DAGDefaultOperand DefaultOpInfo;
1881
1882 TreePatternNode *T = P.getTree(0);
1883 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1884 TreePatternNode *TPN = T->getChild(op);
1885 while (TPN->ApplyTypeConstraints(P, false))
1886 /* Resolve all types */;
1887
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001888 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001889 if (iter == 0)
1890 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001891 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00001892 else
1893 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001894 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001895 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001896 DefaultOpInfo.DefaultOps.push_back(TPN);
1897 }
1898
1899 // Insert it into the DefaultOperands map so we can find it later.
1900 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1901 }
1902 }
1903}
1904
1905/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1906/// instruction input. Return true if this is a real use.
1907static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1908 std::map<std::string, TreePatternNode*> &InstInputs,
1909 std::vector<Record*> &InstImpInputs) {
1910 // No name -> not interesting.
1911 if (Pat->getName().empty()) {
1912 if (Pat->isLeaf()) {
1913 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1914 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1915 I->error("Input " + DI->getDef()->getName() + " must be named!");
1916 else if (DI && DI->getDef()->isSubClassOf("Register"))
1917 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001918 }
1919 return false;
1920 }
1921
1922 Record *Rec;
1923 if (Pat->isLeaf()) {
1924 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1925 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1926 Rec = DI->getDef();
1927 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001928 Rec = Pat->getOperator();
1929 }
1930
1931 // SRCVALUE nodes are ignored.
1932 if (Rec->getName() == "srcvalue")
1933 return false;
1934
1935 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1936 if (!Slot) {
1937 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00001938 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00001939 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00001940 Record *SlotRec;
1941 if (Slot->isLeaf()) {
1942 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1943 } else {
1944 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1945 SlotRec = Slot->getOperator();
1946 }
1947
1948 // Ensure that the inputs agree if we've already seen this input.
1949 if (Rec != SlotRec)
1950 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00001951 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00001952 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00001953 return true;
1954}
1955
1956/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1957/// part of "I", the instruction), computing the set of inputs and outputs of
1958/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001959void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001960FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1961 std::map<std::string, TreePatternNode*> &InstInputs,
1962 std::map<std::string, TreePatternNode*>&InstResults,
1963 std::vector<Record*> &InstImpInputs,
1964 std::vector<Record*> &InstImpResults) {
1965 if (Pat->isLeaf()) {
1966 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1967 if (!isUse && Pat->getTransformFn())
1968 I->error("Cannot specify a transform function for a non-input value!");
1969 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001970 }
1971
1972 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001973 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1974 TreePatternNode *Dest = Pat->getChild(i);
1975 if (!Dest->isLeaf())
1976 I->error("implicitly defined value should be a register!");
1977
1978 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1979 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1980 I->error("implicitly defined value should be a register!");
1981 InstImpResults.push_back(Val->getDef());
1982 }
1983 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001984 }
1985
1986 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001987 // If this is not a set, verify that the children nodes are not void typed,
1988 // and recurse.
1989 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001990 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00001991 I->error("Cannot have void nodes inside of patterns!");
1992 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1993 InstImpInputs, InstImpResults);
1994 }
1995
1996 // If this is a non-leaf node with no children, treat it basically as if
1997 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00001998 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00001999
2000 if (!isUse && Pat->getTransformFn())
2001 I->error("Cannot specify a transform function for a non-input value!");
2002 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002003 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002004
2005 // Otherwise, this is a set, validate and collect instruction results.
2006 if (Pat->getNumChildren() == 0)
2007 I->error("set requires operands!");
2008
2009 if (Pat->getTransformFn())
2010 I->error("Cannot specify a transform function on a set node!");
2011
2012 // Check the set destinations.
2013 unsigned NumDests = Pat->getNumChildren()-1;
2014 for (unsigned i = 0; i != NumDests; ++i) {
2015 TreePatternNode *Dest = Pat->getChild(i);
2016 if (!Dest->isLeaf())
2017 I->error("set destination should be a register!");
2018
2019 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2020 if (!Val)
2021 I->error("set destination should be a register!");
2022
2023 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002024 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002025 if (Dest->getName().empty())
2026 I->error("set destination must have a name!");
2027 if (InstResults.count(Dest->getName()))
2028 I->error("cannot set '" + Dest->getName() +"' multiple times");
2029 InstResults[Dest->getName()] = Dest;
2030 } else if (Val->getDef()->isSubClassOf("Register")) {
2031 InstImpResults.push_back(Val->getDef());
2032 } else {
2033 I->error("set destination should be a register!");
2034 }
2035 }
2036
2037 // Verify and collect info from the computation.
2038 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2039 InstInputs, InstResults,
2040 InstImpInputs, InstImpResults);
2041}
2042
Dan Gohmanee4fa192008-04-03 00:02:49 +00002043//===----------------------------------------------------------------------===//
2044// Instruction Analysis
2045//===----------------------------------------------------------------------===//
2046
2047class InstAnalyzer {
2048 const CodeGenDAGPatterns &CDP;
2049 bool &mayStore;
2050 bool &mayLoad;
2051 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002052 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002053public:
2054 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Chris Lattner1e506312010-03-19 05:34:15 +00002055 bool &maystore, bool &mayload, bool &hse, bool &isv)
2056 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
2057 IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002058 }
2059
2060 /// Analyze - Analyze the specified instruction, returning true if the
2061 /// instruction had a pattern.
2062 bool Analyze(Record *InstRecord) {
2063 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2064 if (Pattern == 0) {
2065 HasSideEffects = 1;
2066 return false; // No pattern.
2067 }
2068
2069 // FIXME: Assume only the first tree is the pattern. The others are clobber
2070 // nodes.
2071 AnalyzeNode(Pattern->getTree(0));
2072 return true;
2073 }
2074
2075private:
2076 void AnalyzeNode(const TreePatternNode *N) {
2077 if (N->isLeaf()) {
2078 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2079 Record *LeafRec = DI->getDef();
2080 // Handle ComplexPattern leaves.
2081 if (LeafRec->isSubClassOf("ComplexPattern")) {
2082 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2083 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2084 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2085 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2086 }
2087 }
2088 return;
2089 }
2090
2091 // Analyze children.
2092 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2093 AnalyzeNode(N->getChild(i));
2094
2095 // Ignore set nodes, which are not SDNodes.
2096 if (N->getOperator()->getName() == "set")
2097 return;
2098
2099 // Get information about the SDNode for the operator.
2100 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2101
2102 // Notice properties of the node.
2103 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2104 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2105 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002106 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002107
2108 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2109 // If this is an intrinsic, analyze it.
2110 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2111 mayLoad = true;// These may load memory.
2112
2113 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2114 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2115
2116 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2117 // WriteMem intrinsics can have other strange effects.
2118 HasSideEffects = true;
2119 }
2120 }
2121
2122};
2123
2124static void InferFromPattern(const CodeGenInstruction &Inst,
2125 bool &MayStore, bool &MayLoad,
Chris Lattner1e506312010-03-19 05:34:15 +00002126 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002127 const CodeGenDAGPatterns &CDP) {
Chris Lattner1e506312010-03-19 05:34:15 +00002128 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002129
2130 bool HadPattern =
Chris Lattner1e506312010-03-19 05:34:15 +00002131 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2132 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002133
2134 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2135 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2136 // If we decided that this is a store from the pattern, then the .td file
2137 // entry is redundant.
2138 if (MayStore)
2139 fprintf(stderr,
2140 "Warning: mayStore flag explicitly set on instruction '%s'"
2141 " but flag already inferred from pattern.\n",
2142 Inst.TheDef->getName().c_str());
2143 MayStore = true;
2144 }
2145
2146 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2147 // If we decided that this is a load from the pattern, then the .td file
2148 // entry is redundant.
2149 if (MayLoad)
2150 fprintf(stderr,
2151 "Warning: mayLoad flag explicitly set on instruction '%s'"
2152 " but flag already inferred from pattern.\n",
2153 Inst.TheDef->getName().c_str());
2154 MayLoad = true;
2155 }
2156
2157 if (Inst.neverHasSideEffects) {
2158 if (HadPattern)
2159 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2160 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2161 HasSideEffects = false;
2162 }
2163
2164 if (Inst.hasSideEffects) {
2165 if (HasSideEffects)
2166 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2167 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2168 HasSideEffects = true;
2169 }
Chris Lattner1e506312010-03-19 05:34:15 +00002170
2171 if (Inst.isVariadic)
2172 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002173}
2174
Chris Lattner6cefb772008-01-05 22:25:12 +00002175/// ParseInstructions - Parse all of the instructions, inlining and resolving
2176/// any fragments involved. This populates the Instructions list with fully
2177/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002178void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002179 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2180
2181 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2182 ListInit *LI = 0;
2183
2184 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2185 LI = Instrs[i]->getValueAsListInit("Pattern");
2186
2187 // If there is no pattern, only collect minimal information about the
2188 // instruction for its operand list. We have to assume that there is one
2189 // result, as we have no detailed info.
2190 if (!LI || LI->getSize() == 0) {
2191 std::vector<Record*> Results;
2192 std::vector<Record*> Operands;
2193
Chris Lattnerf30187a2010-03-19 00:07:20 +00002194 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002195
2196 if (InstInfo.OperandList.size() != 0) {
2197 if (InstInfo.NumDefs == 0) {
2198 // These produce no results
2199 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2200 Operands.push_back(InstInfo.OperandList[j].Rec);
2201 } else {
2202 // Assume the first operand is the result.
2203 Results.push_back(InstInfo.OperandList[0].Rec);
2204
2205 // The rest are inputs.
2206 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2207 Operands.push_back(InstInfo.OperandList[j].Rec);
2208 }
2209 }
2210
2211 // Create and insert the instruction.
2212 std::vector<Record*> ImpResults;
2213 std::vector<Record*> ImpOperands;
2214 Instructions.insert(std::make_pair(Instrs[i],
2215 DAGInstruction(0, Results, Operands, ImpResults,
2216 ImpOperands)));
2217 continue; // no pattern.
2218 }
2219
2220 // Parse the instruction.
2221 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2222 // Inline pattern fragments into it.
2223 I->InlinePatternFragments();
2224
2225 // Infer as many types as possible. If we cannot infer all of them, we can
2226 // never do anything with this instruction pattern: report it to the user.
2227 if (!I->InferAllTypes())
2228 I->error("Could not infer all types in pattern!");
2229
2230 // InstInputs - Keep track of all of the inputs of the instruction, along
2231 // with the record they are declared as.
2232 std::map<std::string, TreePatternNode*> InstInputs;
2233
2234 // InstResults - Keep track of all the virtual registers that are 'set'
2235 // in the instruction, including what reg class they are.
2236 std::map<std::string, TreePatternNode*> InstResults;
2237
2238 std::vector<Record*> InstImpInputs;
2239 std::vector<Record*> InstImpResults;
2240
2241 // Verify that the top-level forms in the instruction are of void type, and
2242 // fill in the InstResults map.
2243 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2244 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002245 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002246 I->error("Top-level forms in instruction pattern should have"
2247 " void types");
2248
2249 // Find inputs and outputs, and verify the structure of the uses/defs.
2250 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2251 InstImpInputs, InstImpResults);
2252 }
2253
2254 // Now that we have inputs and outputs of the pattern, inspect the operands
2255 // list for the instruction. This determines the order that operands are
2256 // added to the machine instruction the node corresponds to.
2257 unsigned NumResults = InstResults.size();
2258
2259 // Parse the operands list from the (ops) list, validating it.
2260 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002261 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002262
2263 // Check that all of the results occur first in the list.
2264 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002265 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002266 for (unsigned i = 0; i != NumResults; ++i) {
2267 if (i == CGI.OperandList.size())
2268 I->error("'" + InstResults.begin()->first +
2269 "' set but does not appear in operand list!");
2270 const std::string &OpName = CGI.OperandList[i].Name;
2271
2272 // Check that it exists in InstResults.
2273 TreePatternNode *RNode = InstResults[OpName];
2274 if (RNode == 0)
2275 I->error("Operand $" + OpName + " does not exist in operand list!");
2276
2277 if (i == 0)
2278 Res0Node = RNode;
2279 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2280 if (R == 0)
2281 I->error("Operand $" + OpName + " should be a set destination: all "
2282 "outputs must occur before inputs in operand list!");
2283
2284 if (CGI.OperandList[i].Rec != R)
2285 I->error("Operand $" + OpName + " class mismatch!");
2286
2287 // Remember the return type.
2288 Results.push_back(CGI.OperandList[i].Rec);
2289
2290 // Okay, this one checks out.
2291 InstResults.erase(OpName);
2292 }
2293
2294 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2295 // the copy while we're checking the inputs.
2296 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2297
2298 std::vector<TreePatternNode*> ResultNodeOperands;
2299 std::vector<Record*> Operands;
2300 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2301 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2302 const std::string &OpName = Op.Name;
2303 if (OpName.empty())
2304 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2305
2306 if (!InstInputsCheck.count(OpName)) {
2307 // If this is an predicate operand or optional def operand with an
2308 // DefaultOps set filled in, we can ignore this. When we codegen it,
2309 // we will do so as always executed.
2310 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2311 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2312 // Does it have a non-empty DefaultOps field? If so, ignore this
2313 // operand.
2314 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2315 continue;
2316 }
2317 I->error("Operand $" + OpName +
2318 " does not appear in the instruction pattern");
2319 }
2320 TreePatternNode *InVal = InstInputsCheck[OpName];
2321 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2322
2323 if (InVal->isLeaf() &&
2324 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2325 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2326 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2327 I->error("Operand $" + OpName + "'s register class disagrees"
2328 " between the operand and pattern");
2329 }
2330 Operands.push_back(Op.Rec);
2331
2332 // Construct the result for the dest-pattern operand list.
2333 TreePatternNode *OpNode = InVal->clone();
2334
2335 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002336 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002337
2338 // Promote the xform function to be an explicit node if set.
2339 if (Record *Xform = OpNode->getTransformFn()) {
2340 OpNode->setTransformFn(0);
2341 std::vector<TreePatternNode*> Children;
2342 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002343 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002344 }
2345
2346 ResultNodeOperands.push_back(OpNode);
2347 }
2348
2349 if (!InstInputsCheck.empty())
2350 I->error("Input operand $" + InstInputsCheck.begin()->first +
2351 " occurs in pattern but not in operands list!");
2352
2353 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002354 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2355 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002356 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002357 for (unsigned i = 0; i != NumResults; ++i)
2358 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002359
2360 // Create and insert the instruction.
2361 // FIXME: InstImpResults and InstImpInputs should not be part of
2362 // DAGInstruction.
2363 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2364 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2365
2366 // Use a temporary tree pattern to infer all types and make sure that the
2367 // constructed result is correct. This depends on the instruction already
2368 // being inserted into the Instructions map.
2369 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002370 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002371
2372 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2373 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2374
2375 DEBUG(I->dump());
2376 }
2377
2378 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002379 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2380 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002381 E = Instructions.end(); II != E; ++II) {
2382 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002383 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002384 if (I == 0) continue; // No pattern.
2385
2386 // FIXME: Assume only the first tree is the pattern. The others are clobber
2387 // nodes.
2388 TreePatternNode *Pattern = I->getTree(0);
2389 TreePatternNode *SrcPattern;
2390 if (Pattern->getOperator()->getName() == "set") {
2391 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2392 } else{
2393 // Not a set (store or something?)
2394 SrcPattern = Pattern;
2395 }
2396
Chris Lattner6cefb772008-01-05 22:25:12 +00002397 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002398 AddPatternToMatch(I,
2399 PatternToMatch(Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002400 SrcPattern,
2401 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002402 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002403 Instr->getValueAsInt("AddedComplexity"),
2404 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002405 }
2406}
2407
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002408
2409typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2410
Chris Lattner967d54a2010-02-23 06:35:45 +00002411static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002412 std::map<std::string, NameRecord> &Names,
2413 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002414 if (!P->getName().empty()) {
2415 NameRecord &Rec = Names[P->getName()];
2416 // If this is the first instance of the name, remember the node.
2417 if (Rec.second++ == 0)
2418 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002419 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002420 PatternTop->error("repetition of value: $" + P->getName() +
2421 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002422 }
Chris Lattner967d54a2010-02-23 06:35:45 +00002423
2424 if (!P->isLeaf()) {
2425 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002426 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002427 }
2428}
2429
Chris Lattner25b6f912010-02-23 06:16:51 +00002430void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2431 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002432 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002433 std::string Reason;
2434 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002435 Pattern->error("Pattern can never match: " + Reason);
Chris Lattner25b6f912010-02-23 06:16:51 +00002436
Chris Lattner405f1252010-03-01 22:29:19 +00002437 // If the source pattern's root is a complex pattern, that complex pattern
2438 // must specify the nodes it can potentially match.
2439 if (const ComplexPattern *CP =
2440 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2441 if (CP->getRootNodes().empty())
2442 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2443 " could match");
2444
2445
Chris Lattner967d54a2010-02-23 06:35:45 +00002446 // Find all of the named values in the input and output, ensure they have the
2447 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002448 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002449 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2450 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002451
2452 // Scan all of the named values in the destination pattern, rejecting them if
2453 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002454 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002455 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002456 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002457 Pattern->error("Pattern has input without matching name in output: $" +
2458 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002459 }
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002460
2461 // Scan all of the named values in the source pattern, rejecting them if the
2462 // name isn't used in the dest, and isn't used to tie two values together.
2463 for (std::map<std::string, NameRecord>::iterator
2464 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2465 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2466 Pattern->error("Pattern has dead named input: $" + I->first);
2467
Chris Lattner25b6f912010-02-23 06:16:51 +00002468 PatternsToMatch.push_back(PTM);
2469}
2470
2471
Dan Gohmanee4fa192008-04-03 00:02:49 +00002472
2473void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002474 const std::vector<const CodeGenInstruction*> &Instructions =
2475 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002476 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2477 CodeGenInstruction &InstInfo =
2478 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002479 // Determine properties of the instruction from its pattern.
Chris Lattner1e506312010-03-19 05:34:15 +00002480 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2481 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2482 *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002483 InstInfo.mayStore = MayStore;
2484 InstInfo.mayLoad = MayLoad;
2485 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002486 InstInfo.isVariadic = IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002487 }
2488}
2489
Chris Lattner2cacec52010-03-15 06:00:16 +00002490/// Given a pattern result with an unresolved type, see if we can find one
2491/// instruction with an unresolved result type. Force this result type to an
2492/// arbitrary element if it's possible types to converge results.
2493static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2494 if (N->isLeaf())
2495 return false;
2496
2497 // Analyze children.
2498 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2499 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2500 return true;
2501
2502 if (!N->getOperator()->isSubClassOf("Instruction"))
2503 return false;
2504
2505 // If this type is already concrete or completely unknown we can't do
2506 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00002507 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2508 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2509 continue;
Chris Lattner2cacec52010-03-15 06:00:16 +00002510
Chris Lattnerd7349192010-03-19 21:37:09 +00002511 // Otherwise, force its type to the first possibility (an arbitrary choice).
2512 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2513 return true;
2514 }
2515
2516 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00002517}
2518
Chris Lattnerfe718932008-01-06 01:10:31 +00002519void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002520 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2521
2522 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002523 Record *CurPattern = Patterns[i];
2524 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Chris Lattner310adf12010-03-27 02:53:27 +00002525 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002526
2527 // Inline pattern fragments into it.
2528 Pattern->InlinePatternFragments();
2529
Chris Lattnerd7349192010-03-19 21:37:09 +00002530 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00002531 if (LI->getSize() == 0) continue; // no pattern.
2532
2533 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00002534 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002535
2536 // Inline pattern fragments into it.
2537 Result->InlinePatternFragments();
2538
2539 if (Result->getNumTrees() != 1)
2540 Result->error("Cannot handle instructions producing instructions "
2541 "with temporaries yet!");
2542
2543 bool IterateInference;
2544 bool InferredAllPatternTypes, InferredAllResultTypes;
2545 do {
2546 // Infer as many types as possible. If we cannot infer all of them, we
2547 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002548 InferredAllPatternTypes =
2549 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002550
2551 // Infer as many types as possible. If we cannot infer all of them, we
2552 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002553 InferredAllResultTypes =
2554 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002555
Chris Lattner6c6ba362010-03-18 23:15:10 +00002556 IterateInference = false;
2557
Chris Lattner6cefb772008-01-05 22:25:12 +00002558 // Apply the type of the result to the source pattern. This helps us
2559 // resolve cases where the input type is known to be a pointer type (which
2560 // is considered resolved), but the result knows it needs to be 32- or
2561 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00002562 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2563 Pattern->getTree(0)->getNumTypes());
2564 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00002565 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002566 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002567 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002568 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002569 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002570
2571 // If our iteration has converged and the input pattern's types are fully
2572 // resolved but the result pattern is not fully resolved, we may have a
2573 // situation where we have two instructions in the result pattern and
2574 // the instructions require a common register class, but don't care about
2575 // what actual MVT is used. This is actually a bug in our modelling:
2576 // output patterns should have register classes, not MVTs.
2577 //
2578 // In any case, to handle this, we just go through and disambiguate some
2579 // arbitrary types to the result pattern's nodes.
2580 if (!IterateInference && InferredAllPatternTypes &&
2581 !InferredAllResultTypes)
2582 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2583 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002584 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002585
Chris Lattner6cefb772008-01-05 22:25:12 +00002586 // Verify that we inferred enough types that we can do something with the
2587 // pattern and result. If these fire the user has to add type casts.
2588 if (!InferredAllPatternTypes)
2589 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002590 if (!InferredAllResultTypes) {
2591 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002592 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002593 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002594
2595 // Validate that the input pattern is correct.
2596 std::map<std::string, TreePatternNode*> InstInputs;
2597 std::map<std::string, TreePatternNode*> InstResults;
2598 std::vector<Record*> InstImpInputs;
2599 std::vector<Record*> InstImpResults;
2600 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2601 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2602 InstInputs, InstResults,
2603 InstImpInputs, InstImpResults);
2604
2605 // Promote the xform function to be an explicit node if set.
2606 TreePatternNode *DstPattern = Result->getOnlyTree();
2607 std::vector<TreePatternNode*> ResultNodeOperands;
2608 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2609 TreePatternNode *OpNode = DstPattern->getChild(ii);
2610 if (Record *Xform = OpNode->getTransformFn()) {
2611 OpNode->setTransformFn(0);
2612 std::vector<TreePatternNode*> Children;
2613 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002614 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002615 }
2616 ResultNodeOperands.push_back(OpNode);
2617 }
2618 DstPattern = Result->getOnlyTree();
2619 if (!DstPattern->isLeaf())
2620 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00002621 ResultNodeOperands,
2622 DstPattern->getNumTypes());
2623
2624 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2625 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2626
Chris Lattner6cefb772008-01-05 22:25:12 +00002627 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2628 Temp.InferAllTypes();
2629
Chris Lattner6cefb772008-01-05 22:25:12 +00002630
Chris Lattner25b6f912010-02-23 06:16:51 +00002631 AddPatternToMatch(Pattern,
Chris Lattnerd7349192010-03-19 21:37:09 +00002632 PatternToMatch(CurPattern->getValueAsListInit("Predicates"),
2633 Pattern->getTree(0),
2634 Temp.getOnlyTree(), InstImpResults,
2635 CurPattern->getValueAsInt("AddedComplexity"),
2636 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002637 }
2638}
2639
2640/// CombineChildVariants - Given a bunch of permutations of each child of the
2641/// 'operator' node, put them together in all possible ways.
2642static void CombineChildVariants(TreePatternNode *Orig,
2643 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2644 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002645 CodeGenDAGPatterns &CDP,
2646 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002647 // Make sure that each operand has at least one variant to choose from.
2648 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2649 if (ChildVariants[i].empty())
2650 return;
2651
2652 // The end result is an all-pairs construction of the resultant pattern.
2653 std::vector<unsigned> Idxs;
2654 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002655 bool NotDone;
2656 do {
2657#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002658 DEBUG(if (!Idxs.empty()) {
2659 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2660 for (unsigned i = 0; i < Idxs.size(); ++i) {
2661 errs() << Idxs[i] << " ";
2662 }
2663 errs() << "]\n";
2664 });
Scott Michel327d0652008-03-05 17:49:05 +00002665#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002666 // Create the variant and add it to the output list.
2667 std::vector<TreePatternNode*> NewChildren;
2668 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2669 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00002670 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2671 Orig->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002672
2673 // Copy over properties.
2674 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002675 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002676 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00002677 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2678 R->setType(i, Orig->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002679
Scott Michel327d0652008-03-05 17:49:05 +00002680 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002681 std::string ErrString;
2682 if (!R->canPatternMatch(ErrString, CDP)) {
2683 delete R;
2684 } else {
2685 bool AlreadyExists = false;
2686
2687 // Scan to see if this pattern has already been emitted. We can get
2688 // duplication due to things like commuting:
2689 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2690 // which are the same pattern. Ignore the dups.
2691 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002692 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002693 AlreadyExists = true;
2694 break;
2695 }
2696
2697 if (AlreadyExists)
2698 delete R;
2699 else
2700 OutVariants.push_back(R);
2701 }
2702
Scott Michel327d0652008-03-05 17:49:05 +00002703 // Increment indices to the next permutation by incrementing the
2704 // indicies from last index backward, e.g., generate the sequence
2705 // [0, 0], [0, 1], [1, 0], [1, 1].
2706 int IdxsIdx;
2707 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2708 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2709 Idxs[IdxsIdx] = 0;
2710 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002711 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002712 }
Scott Michel327d0652008-03-05 17:49:05 +00002713 NotDone = (IdxsIdx >= 0);
2714 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002715}
2716
2717/// CombineChildVariants - A helper function for binary operators.
2718///
2719static void CombineChildVariants(TreePatternNode *Orig,
2720 const std::vector<TreePatternNode*> &LHS,
2721 const std::vector<TreePatternNode*> &RHS,
2722 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002723 CodeGenDAGPatterns &CDP,
2724 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002725 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2726 ChildVariants.push_back(LHS);
2727 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002728 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002729}
2730
2731
2732static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2733 std::vector<TreePatternNode *> &Children) {
2734 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2735 Record *Operator = N->getOperator();
2736
2737 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002738 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002739 N->getTransformFn()) {
2740 Children.push_back(N);
2741 return;
2742 }
2743
2744 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2745 Children.push_back(N->getChild(0));
2746 else
2747 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2748
2749 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2750 Children.push_back(N->getChild(1));
2751 else
2752 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2753}
2754
2755/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2756/// the (potentially recursive) pattern by using algebraic laws.
2757///
2758static void GenerateVariantsOf(TreePatternNode *N,
2759 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002760 CodeGenDAGPatterns &CDP,
2761 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002762 // We cannot permute leaves.
2763 if (N->isLeaf()) {
2764 OutVariants.push_back(N);
2765 return;
2766 }
2767
2768 // Look up interesting info about the node.
2769 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2770
Jim Grosbachda4231f2009-03-26 16:17:51 +00002771 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002772 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002773 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002774 std::vector<TreePatternNode*> MaximalChildren;
2775 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2776
2777 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2778 // permutations.
2779 if (MaximalChildren.size() == 3) {
2780 // Find the variants of all of our maximal children.
2781 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002782 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2783 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2784 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002785
2786 // There are only two ways we can permute the tree:
2787 // (A op B) op C and A op (B op C)
2788 // Within these forms, we can also permute A/B/C.
2789
2790 // Generate legal pair permutations of A/B/C.
2791 std::vector<TreePatternNode*> ABVariants;
2792 std::vector<TreePatternNode*> BAVariants;
2793 std::vector<TreePatternNode*> ACVariants;
2794 std::vector<TreePatternNode*> CAVariants;
2795 std::vector<TreePatternNode*> BCVariants;
2796 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002797 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2798 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2799 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2800 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2801 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2802 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002803
2804 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002805 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2806 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2807 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2808 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2809 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2810 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002811
2812 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002813 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2814 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2815 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2816 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2817 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2818 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002819 return;
2820 }
2821 }
2822
2823 // Compute permutations of all children.
2824 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2825 ChildVariants.resize(N->getNumChildren());
2826 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002827 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002828
2829 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002830 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002831
2832 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002833 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2834 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2835 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2836 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002837 // Don't count children which are actually register references.
2838 unsigned NC = 0;
2839 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2840 TreePatternNode *Child = N->getChild(i);
2841 if (Child->isLeaf())
2842 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2843 Record *RR = DI->getDef();
2844 if (RR->isSubClassOf("Register"))
2845 continue;
2846 }
2847 NC++;
2848 }
2849 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002850 if (isCommIntrinsic) {
2851 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2852 // operands are the commutative operands, and there might be more operands
2853 // after those.
2854 assert(NC >= 3 &&
2855 "Commutative intrinsic should have at least 3 childrean!");
2856 std::vector<std::vector<TreePatternNode*> > Variants;
2857 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2858 Variants.push_back(ChildVariants[2]);
2859 Variants.push_back(ChildVariants[1]);
2860 for (unsigned i = 3; i != NC; ++i)
2861 Variants.push_back(ChildVariants[i]);
2862 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2863 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002864 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002865 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002866 }
2867}
2868
2869
2870// GenerateVariants - Generate variants. For example, commutative patterns can
2871// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002872void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002873 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002874
2875 // Loop over all of the patterns we've collected, checking to see if we can
2876 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002877 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002878 // the .td file having to contain tons of variants of instructions.
2879 //
2880 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2881 // intentionally do not reconsider these. Any variants of added patterns have
2882 // already been added.
2883 //
2884 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002885 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002886 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002887 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002888 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002889 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002890 DEBUG(errs() << "\n");
Scott Michel327d0652008-03-05 17:49:05 +00002891 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002892
2893 assert(!Variants.empty() && "Must create at least original variant!");
2894 Variants.erase(Variants.begin()); // Remove the original pattern.
2895
2896 if (Variants.empty()) // No variants for this pattern.
2897 continue;
2898
Chris Lattner569f1212009-08-23 04:44:11 +00002899 DEBUG(errs() << "FOUND VARIANTS OF: ";
2900 PatternsToMatch[i].getSrcPattern()->dump();
2901 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002902
2903 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2904 TreePatternNode *Variant = Variants[v];
2905
Chris Lattner569f1212009-08-23 04:44:11 +00002906 DEBUG(errs() << " VAR#" << v << ": ";
2907 Variant->dump();
2908 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002909
2910 // Scan to see if an instruction or explicit pattern already matches this.
2911 bool AlreadyExists = false;
2912 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00002913 // Skip if the top level predicates do not match.
2914 if (PatternsToMatch[i].getPredicates() !=
2915 PatternsToMatch[p].getPredicates())
2916 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00002917 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002918 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00002919 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002920 AlreadyExists = true;
2921 break;
2922 }
2923 }
2924 // If we already have it, ignore the variant.
2925 if (AlreadyExists) continue;
2926
2927 // Otherwise, add it to the list of patterns we have.
2928 PatternsToMatch.
2929 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2930 Variant, PatternsToMatch[i].getDstPattern(),
2931 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002932 PatternsToMatch[i].getAddedComplexity(),
2933 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002934 }
2935
Chris Lattner569f1212009-08-23 04:44:11 +00002936 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002937 }
2938}
2939