blob: c32df743e2378355d19b36fb91c0958b6d280802 [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
64 // Remove duplicates.
65 array_pod_sort(TypeVec.begin(), TypeVec.end());
66 TypeVec.erase(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"));
527 } else if (R->isSubClassOf("SDTCisPtrTy")) {
528 ConstraintType = SDTCisPtrTy;
529 } else if (R->isSubClassOf("SDTCisInt")) {
530 ConstraintType = SDTCisInt;
531 } else if (R->isSubClassOf("SDTCisFP")) {
532 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000533 } else if (R->isSubClassOf("SDTCisVec")) {
534 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000535 } else if (R->isSubClassOf("SDTCisSameAs")) {
536 ConstraintType = SDTCisSameAs;
537 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
538 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
539 ConstraintType = SDTCisVTSmallerThanOp;
540 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
541 R->getValueAsInt("OtherOperandNum");
542 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
543 ConstraintType = SDTCisOpSmallerThanOp;
544 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
545 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000546 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
547 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000548 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000549 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000550 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000551 exit(1);
552 }
553}
554
555/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000556/// N, and the result number in ResNo.
557static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
558 const SDNodeInfo &NodeInfo,
559 unsigned &ResNo) {
560 unsigned NumResults = NodeInfo.getNumResults();
561 if (OpNo < NumResults) {
562 ResNo = OpNo;
563 return N;
564 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000565
Chris Lattner2e68a022010-03-19 21:56:21 +0000566 OpNo -= NumResults;
567
568 if (OpNo >= N->getNumChildren()) {
569 errs() << "Invalid operand number in type constraint "
570 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000571 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000572 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000573 exit(1);
574 }
575
Chris Lattner2e68a022010-03-19 21:56:21 +0000576 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000577}
578
579/// ApplyTypeConstraint - Given a node in a pattern, apply this type
580/// constraint to the nodes operands. This returns true if it makes a
581/// change, false otherwise. If a type contradiction is found, throw an
582/// exception.
583bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
584 const SDNodeInfo &NodeInfo,
585 TreePattern &TP) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000586 // Check that the number of operands is sane. Negative operands -> varargs.
587 if (NodeInfo.getNumOperands() >= 0) {
588 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
589 TP.error(N->getOperator()->getName() + " node requires exactly " +
590 itostr(NodeInfo.getNumOperands()) + " operands!");
591 }
592
Chris Lattner2e68a022010-03-19 21:56:21 +0000593 unsigned ResNo = 0; // The result number being referenced.
594 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000595
596 switch (ConstraintType) {
597 default: assert(0 && "Unknown constraint type!");
598 case SDTCisVT:
599 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000600 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000601 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000602 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000603 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000604 case SDTCisInt:
605 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000606 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000607 case SDTCisFP:
608 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000609 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000610 case SDTCisVec:
611 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000612 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000613 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000614 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000615 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000616 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000617 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
618 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000619 }
620 case SDTCisVTSmallerThanOp: {
621 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
622 // have an integer type that is smaller than the VT.
623 if (!NodeToApply->isLeaf() ||
624 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
625 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
626 ->isSubClassOf("ValueType"))
627 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000628 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000629 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Chris Lattnercc878302010-03-24 00:06:46 +0000630
631 EEVT::TypeSet TypeListTmp(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000632
Chris Lattner2e68a022010-03-19 21:56:21 +0000633 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000634 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000635 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
636 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000637
Chris Lattnercc878302010-03-24 00:06:46 +0000638 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000639 }
640 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000641 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000642 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000643 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
644 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000645 return NodeToApply->getExtType(ResNo).
646 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000647 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000648 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000649 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000650 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000651 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
652 VResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000653
Chris Lattner66fb9d22010-03-24 00:01:16 +0000654 // Filter vector types out of VecOperand that don't have the right element
655 // type.
656 return VecOperand->getExtType(VResNo).
657 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000658 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000659 }
660 return false;
661}
662
663//===----------------------------------------------------------------------===//
664// SDNodeInfo implementation
665//
666SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
667 EnumName = R->getValueAsString("Opcode");
668 SDClassName = R->getValueAsString("SDClass");
669 Record *TypeProfile = R->getValueAsDef("TypeProfile");
670 NumResults = TypeProfile->getValueAsInt("NumResults");
671 NumOperands = TypeProfile->getValueAsInt("NumOperands");
672
673 // Parse the properties.
674 Properties = 0;
675 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
676 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
677 if (PropList[i]->getName() == "SDNPCommutative") {
678 Properties |= 1 << SDNPCommutative;
679 } else if (PropList[i]->getName() == "SDNPAssociative") {
680 Properties |= 1 << SDNPAssociative;
681 } else if (PropList[i]->getName() == "SDNPHasChain") {
682 Properties |= 1 << SDNPHasChain;
683 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000684 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000685 } else if (PropList[i]->getName() == "SDNPInFlag") {
686 Properties |= 1 << SDNPInFlag;
687 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
688 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000689 } else if (PropList[i]->getName() == "SDNPMayStore") {
690 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000691 } else if (PropList[i]->getName() == "SDNPMayLoad") {
692 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000693 } else if (PropList[i]->getName() == "SDNPSideEffect") {
694 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000695 } else if (PropList[i]->getName() == "SDNPMemOperand") {
696 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000697 } else if (PropList[i]->getName() == "SDNPVariadic") {
698 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000699 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000700 errs() << "Unknown SD Node property '" << PropList[i]->getName()
701 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000702 exit(1);
703 }
704 }
705
706
707 // Parse the type constraints.
708 std::vector<Record*> ConstraintList =
709 TypeProfile->getValueAsListOfDefs("Constraints");
710 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
711}
712
Chris Lattner22579812010-02-28 00:22:30 +0000713/// getKnownType - If the type constraints on this node imply a fixed type
714/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000715/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000716MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +0000717 unsigned NumResults = getNumResults();
718 assert(NumResults <= 1 &&
719 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +0000720 assert(ResNo == 0 && "Only handles single result nodes so far");
Chris Lattner22579812010-02-28 00:22:30 +0000721
722 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
723 // Make sure that this applies to the correct node result.
724 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
725 continue;
726
727 switch (TypeConstraints[i].ConstraintType) {
728 default: break;
729 case SDTypeConstraint::SDTCisVT:
730 return TypeConstraints[i].x.SDTCisVT_Info.VT;
731 case SDTypeConstraint::SDTCisPtrTy:
732 return MVT::iPTR;
733 }
734 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000735 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000736}
737
Chris Lattner6cefb772008-01-05 22:25:12 +0000738//===----------------------------------------------------------------------===//
739// TreePatternNode implementation
740//
741
742TreePatternNode::~TreePatternNode() {
743#if 0 // FIXME: implement refcounted tree nodes!
744 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
745 delete getChild(i);
746#endif
747}
748
Chris Lattnerd7349192010-03-19 21:37:09 +0000749static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
750 if (Operator->getName() == "set" ||
751 Operator->getName() == "implicit" ||
752 Operator->getName() == "parallel")
753 return 0; // All return nothing.
754
Chris Lattner93dc92e2010-03-22 20:56:36 +0000755 if (Operator->isSubClassOf("Intrinsic"))
756 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Chris Lattner6cefb772008-01-05 22:25:12 +0000757
Chris Lattnerd7349192010-03-19 21:37:09 +0000758 if (Operator->isSubClassOf("SDNode"))
759 return CDP.getSDNodeInfo(Operator).getNumResults();
760
761 if (Operator->isSubClassOf("PatFrag")) {
762 // If we've already parsed this pattern fragment, get it. Otherwise, handle
763 // the forward reference case where one pattern fragment references another
764 // before it is processed.
765 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
766 return PFRec->getOnlyTree()->getNumTypes();
767
768 // Get the result tree.
769 DagInit *Tree = Operator->getValueAsDag("Fragment");
770 Record *Op = 0;
771 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
772 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
773 assert(Op && "Invalid Fragment");
774 return GetNumNodeResults(Op, CDP);
775 }
776
777 if (Operator->isSubClassOf("Instruction")) {
778 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
779
780 // FIXME: Handle implicit defs right.
781 if (InstInfo.NumDefs != 0)
782 return 1; // FIXME: Handle inst results right!
783
784 if (!InstInfo.ImplicitDefs.empty()) {
785 // Add on one implicit def if it has a resolvable type.
786 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
787 assert(FirstImplicitDef->isSubClassOf("Register"));
788 const std::vector<MVT::SimpleValueType> &RegVTs =
789 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
790 if (RegVTs.size() == 1)
791 return 1;
792 }
793 return 0;
794 }
795
796 if (Operator->isSubClassOf("SDNodeXForm"))
797 return 1; // FIXME: Generalize SDNodeXForm
798
799 Operator->dump();
800 errs() << "Unhandled node in GetNumNodeResults\n";
801 exit(1);
802}
803
804void TreePatternNode::print(raw_ostream &OS) const {
805 if (isLeaf())
806 OS << *getLeafValue();
807 else
808 OS << '(' << getOperator()->getName();
809
810 for (unsigned i = 0, e = Types.size(); i != e; ++i)
811 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000812
813 if (!isLeaf()) {
814 if (getNumChildren() != 0) {
815 OS << " ";
816 getChild(0)->print(OS);
817 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
818 OS << ", ";
819 getChild(i)->print(OS);
820 }
821 }
822 OS << ")";
823 }
824
Dan Gohman0540e172008-10-15 06:17:21 +0000825 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
826 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000827 if (TransformFn)
828 OS << "<<X:" << TransformFn->getName() << ">>";
829 if (!getName().empty())
830 OS << ":$" << getName();
831
832}
833void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000834 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000835}
836
Scott Michel327d0652008-03-05 17:49:05 +0000837/// isIsomorphicTo - Return true if this node is recursively
838/// isomorphic to the specified node. For this comparison, the node's
839/// entire state is considered. The assigned name is ignored, since
840/// nodes with differing names are considered isomorphic. However, if
841/// the assigned name is present in the dependent variable set, then
842/// the assigned name is considered significant and the node is
843/// isomorphic if the names match.
844bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
845 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000846 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +0000847 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000848 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000849 getTransformFn() != N->getTransformFn())
850 return false;
851
852 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000853 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
854 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000855 return ((DI->getDef() == NDI->getDef())
856 && (DepVars.find(getName()) == DepVars.end()
857 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000858 }
859 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000860 return getLeafValue() == N->getLeafValue();
861 }
862
863 if (N->getOperator() != getOperator() ||
864 N->getNumChildren() != getNumChildren()) return false;
865 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000866 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000867 return false;
868 return true;
869}
870
871/// clone - Make a copy of this tree and all of its children.
872///
873TreePatternNode *TreePatternNode::clone() const {
874 TreePatternNode *New;
875 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +0000876 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000877 } else {
878 std::vector<TreePatternNode*> CChildren;
879 CChildren.reserve(Children.size());
880 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
881 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +0000882 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000883 }
884 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +0000885 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +0000886 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000887 New->setTransformFn(getTransformFn());
888 return New;
889}
890
Chris Lattner47661322010-02-14 22:22:58 +0000891/// RemoveAllTypes - Recursively strip all the types of this tree.
892void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +0000893 for (unsigned i = 0, e = Types.size(); i != e; ++i)
894 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +0000895 if (isLeaf()) return;
896 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
897 getChild(i)->RemoveAllTypes();
898}
899
900
Chris Lattner6cefb772008-01-05 22:25:12 +0000901/// SubstituteFormalArguments - Replace the formal arguments in this tree
902/// with actual values specified by ArgMap.
903void TreePatternNode::
904SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
905 if (isLeaf()) return;
906
907 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
908 TreePatternNode *Child = getChild(i);
909 if (Child->isLeaf()) {
910 Init *Val = Child->getLeafValue();
911 if (dynamic_cast<DefInit*>(Val) &&
912 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
913 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000914 TreePatternNode *NewChild = ArgMap[Child->getName()];
915 assert(NewChild && "Couldn't find formal argument!");
916 assert((Child->getPredicateFns().empty() ||
917 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
918 "Non-empty child predicate clobbered!");
919 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000920 }
921 } else {
922 getChild(i)->SubstituteFormalArguments(ArgMap);
923 }
924 }
925}
926
927
928/// InlinePatternFragments - If this pattern refers to any pattern
929/// fragments, inline them into place, giving us a pattern without any
930/// PatFrag references.
931TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
932 if (isLeaf()) return this; // nothing to do.
933 Record *Op = getOperator();
934
935 if (!Op->isSubClassOf("PatFrag")) {
936 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000937 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
938 TreePatternNode *Child = getChild(i);
939 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
940
941 assert((Child->getPredicateFns().empty() ||
942 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
943 "Non-empty child predicate clobbered!");
944
945 setChild(i, NewChild);
946 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000947 return this;
948 }
949
950 // Otherwise, we found a reference to a fragment. First, look up its
951 // TreePattern record.
952 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
953
954 // Verify that we are passing the right number of operands.
955 if (Frag->getNumArgs() != Children.size())
956 TP.error("'" + Op->getName() + "' fragment requires " +
957 utostr(Frag->getNumArgs()) + " operands!");
958
959 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
960
Dan Gohman0540e172008-10-15 06:17:21 +0000961 std::string Code = Op->getValueAsCode("Predicate");
962 if (!Code.empty())
963 FragTree->addPredicateFn("Predicate_"+Op->getName());
964
Chris Lattner6cefb772008-01-05 22:25:12 +0000965 // Resolve formal arguments to their actual value.
966 if (Frag->getNumArgs()) {
967 // Compute the map of formal to actual arguments.
968 std::map<std::string, TreePatternNode*> ArgMap;
969 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
970 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
971
972 FragTree->SubstituteFormalArguments(ArgMap);
973 }
974
975 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +0000976 for (unsigned i = 0, e = Types.size(); i != e; ++i)
977 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000978
979 // Transfer in the old predicates.
980 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
981 FragTree->addPredicateFn(getPredicateFns()[i]);
982
Chris Lattner6cefb772008-01-05 22:25:12 +0000983 // Get a new copy of this fragment to stitch into here.
984 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000985
986 // The fragment we inlined could have recursive inlining that is needed. See
987 // if there are any pattern fragments in it and inline them as needed.
988 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000989}
990
991/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000992/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +0000993/// references from the register file information, for example.
994///
Chris Lattnerd7349192010-03-19 21:37:09 +0000995static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
996 bool NotRegisters, TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000997 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +0000998 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +0000999 assert(ResNo == 0 && "Regclass ref only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001000 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001001 return EEVT::TypeSet(); // Unknown.
1002 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1003 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001004 }
1005
1006 if (R->isSubClassOf("PatFrag")) {
1007 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001008 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001009 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001010 }
1011
1012 if (R->isSubClassOf("Register")) {
1013 assert(ResNo == 0 && "Registers only produce one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001014 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001015 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001016 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001017 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001018 }
1019
1020 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1021 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001022 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001023 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001024 }
1025
1026 if (R->isSubClassOf("ComplexPattern")) {
1027 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001028 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001029 return EEVT::TypeSet(); // Unknown.
1030 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1031 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001032 }
1033 if (R->isSubClassOf("PointerLikeRegClass")) {
1034 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001035 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001036 }
1037
1038 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1039 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001040 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001041 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001042 }
1043
1044 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001045 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001046}
1047
Chris Lattnere67bde52008-01-06 05:36:50 +00001048
1049/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1050/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1051const CodeGenIntrinsic *TreePatternNode::
1052getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1053 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1054 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1055 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1056 return 0;
1057
1058 unsigned IID =
1059 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1060 return &CDP.getIntrinsicInfo(IID);
1061}
1062
Chris Lattner47661322010-02-14 22:22:58 +00001063/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1064/// return the ComplexPattern information, otherwise return null.
1065const ComplexPattern *
1066TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1067 if (!isLeaf()) return 0;
1068
1069 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1070 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1071 return &CGP.getComplexPattern(DI->getDef());
1072 return 0;
1073}
1074
1075/// NodeHasProperty - Return true if this node has the specified property.
1076bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001077 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001078 if (isLeaf()) {
1079 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1080 return CP->hasProperty(Property);
1081 return false;
1082 }
1083
1084 Record *Operator = getOperator();
1085 if (!Operator->isSubClassOf("SDNode")) return false;
1086
1087 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1088}
1089
1090
1091
1092
1093/// TreeHasProperty - Return true if any node in this tree has the specified
1094/// property.
1095bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001096 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001097 if (NodeHasProperty(Property, CGP))
1098 return true;
1099 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1100 if (getChild(i)->TreeHasProperty(Property, CGP))
1101 return true;
1102 return false;
1103}
1104
Evan Cheng6bd95672008-06-16 20:29:38 +00001105/// isCommutativeIntrinsic - Return true if the node corresponds to a
1106/// commutative intrinsic.
1107bool
1108TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1109 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1110 return Int->isCommutative;
1111 return false;
1112}
1113
Chris Lattnere67bde52008-01-06 05:36:50 +00001114
Bob Wilson6c01ca92009-01-05 17:23:09 +00001115/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001116/// this node and its children in the tree. This returns true if it makes a
1117/// change, false otherwise. If a type contradiction is found, throw an
1118/// exception.
1119bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001120 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001121 if (isLeaf()) {
1122 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1123 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001124 bool MadeChange = false;
1125 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1126 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1127 NotRegisters, TP), TP);
1128 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001129 }
1130
1131 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001132 assert(Types.size() == 1 && "Invalid IntInit");
Chris Lattner6cefb772008-01-05 22:25:12 +00001133
Chris Lattnerd7349192010-03-19 21:37:09 +00001134 // Int inits are always integers. :)
1135 bool MadeChange = Types[0].EnforceInteger(TP);
1136
1137 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001138 return MadeChange;
1139
Chris Lattnerd7349192010-03-19 21:37:09 +00001140 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001141 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1142 return MadeChange;
1143
1144 unsigned Size = EVT(VT).getSizeInBits();
1145 // Make sure that the value is representable for this type.
1146 if (Size >= 32) return MadeChange;
1147
1148 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1149 if (Val == II->getValue()) return MadeChange;
1150
1151 // If sign-extended doesn't fit, does it fit as unsigned?
1152 unsigned ValueMask;
1153 unsigned UnsignedVal;
1154 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1155 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001156
Chris Lattner2cacec52010-03-15 06:00:16 +00001157 if ((ValueMask & UnsignedVal) == UnsignedVal)
1158 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001159
Chris Lattner2cacec52010-03-15 06:00:16 +00001160 TP.error("Integer value '" + itostr(II->getValue())+
Chris Lattnerd7349192010-03-19 21:37:09 +00001161 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001162 return MadeChange;
1163 }
1164 return false;
1165 }
1166
1167 // special handling for set, which isn't really an SDNode.
1168 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001169 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1170 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001171 unsigned NC = getNumChildren();
Chris Lattnerd7349192010-03-19 21:37:09 +00001172
1173 TreePatternNode *SetVal = getChild(NC-1);
1174 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1175
Chris Lattner6cefb772008-01-05 22:25:12 +00001176 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001177 TreePatternNode *Child = getChild(i);
1178 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001179
1180 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001181 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1182 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001183 }
1184 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001185 }
1186
1187 if (getOperator()->getName() == "implicit" ||
1188 getOperator()->getName() == "parallel") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001189 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1190
Chris Lattner6cefb772008-01-05 22:25:12 +00001191 bool MadeChange = false;
1192 for (unsigned i = 0; i < getNumChildren(); ++i)
1193 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001194 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001195 }
1196
1197 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001198 bool MadeChange = false;
1199 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1200 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner2cacec52010-03-15 06:00:16 +00001201
Chris Lattnerd7349192010-03-19 21:37:09 +00001202 assert(getChild(0)->getNumTypes() == 1 &&
1203 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1204
Chris Lattner2cacec52010-03-15 06:00:16 +00001205 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1206 // what type it gets, so if it didn't get a concrete type just give it the
1207 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001208 if (!getChild(1)->hasTypeSet(0) &&
1209 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1210 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1211 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001212 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001213 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001214 }
1215
1216 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001217 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001218
Chris Lattner6cefb772008-01-05 22:25:12 +00001219 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001220 unsigned NumRetVTs = Int->IS.RetVTs.size();
1221 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Chris Lattnerd7349192010-03-19 21:37:09 +00001222
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001223 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001224 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001225
Chris Lattnerd7349192010-03-19 21:37:09 +00001226 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001227 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001228 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001229 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001230
1231 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001232 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001233
Chris Lattnerd7349192010-03-19 21:37:09 +00001234 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1235 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1236
1237 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1238 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1239 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001240 }
1241 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001242 }
1243
1244 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001245 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1246
1247 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1248 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1249 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001250 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001251 }
1252
1253 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001254 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattnerd7349192010-03-19 21:37:09 +00001255 unsigned ResNo = 0;
Daniel Dunbar65f35d52010-03-19 03:18:20 +00001256 assert(Inst.getNumResults() <= 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001257 "FIXME: Only supports zero or one result instrs!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001258
1259 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001260 CDP.getTargetInfo().getInstruction(getOperator());
Chris Lattner6c6ba362010-03-18 23:15:10 +00001261
1262 EEVT::TypeSet ResultType;
1263
Chris Lattner6cefb772008-01-05 22:25:12 +00001264 // Apply the result type to the node
Chris Lattner6c6ba362010-03-18 23:15:10 +00001265 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
Chris Lattner6cefb772008-01-05 22:25:12 +00001266 Record *ResultNode = Inst.getResult(0);
1267
Chris Lattnera938ac62009-07-29 20:43:05 +00001268 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00001269 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001270 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001271 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001272 } else {
1273 assert(ResultNode->isSubClassOf("RegisterClass") &&
1274 "Operands should be register classes!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001275 const CodeGenRegisterClass &RC =
1276 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001277 ResultType = RC.getValueTypes();
Chris Lattner6cefb772008-01-05 22:25:12 +00001278 }
Chris Lattner6c6ba362010-03-18 23:15:10 +00001279 } else if (!InstInfo.ImplicitDefs.empty()) {
1280 // If the instruction has implicit defs, the first one defines the result
1281 // type.
Chris Lattner6c6ba362010-03-18 23:15:10 +00001282 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
Chris Lattner92879532010-03-18 23:57:40 +00001283 assert(FirstImplicitDef->isSubClassOf("Register"));
Chris Lattner6c6ba362010-03-18 23:15:10 +00001284 const std::vector<MVT::SimpleValueType> &RegVTs =
1285 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
Chris Lattnerd7349192010-03-19 21:37:09 +00001286 if (RegVTs.size() == 1) // FIXME: Generalize.
Chris Lattner6c6ba362010-03-18 23:15:10 +00001287 ResultType = EEVT::TypeSet(RegVTs);
1288 } else {
1289 // Otherwise, the instruction produces no value result.
Chris Lattner6cefb772008-01-05 22:25:12 +00001290 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001291
Chris Lattnerd7349192010-03-19 21:37:09 +00001292 bool MadeChange = false;
1293
1294 if (!ResultType.isCompletelyUnknown())
1295 MadeChange |= UpdateNodeType(ResNo, ResultType, TP);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001296
Chris Lattner2cacec52010-03-15 06:00:16 +00001297 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1298 // be the same.
1299 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001300 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1301 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1302 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001303 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001304
1305 unsigned ChildNo = 0;
1306 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1307 Record *OperandNode = Inst.getOperand(i);
1308
1309 // If the instruction expects a predicate or optional def operand, we
1310 // codegen this by setting the operand to it's default value if it has a
1311 // non-empty DefaultOps field.
1312 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1313 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1314 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1315 continue;
1316
1317 // Verify that we didn't run out of provided operands.
1318 if (ChildNo >= getNumChildren())
1319 TP.error("Instruction '" + getOperator()->getName() +
1320 "' expects more operands than were provided.");
1321
Owen Anderson825b72b2009-08-11 20:47:22 +00001322 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001323 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd7349192010-03-19 21:37:09 +00001324 assert(Child->getNumTypes() == 1 && "Unknown case?");
1325
Chris Lattner6cefb772008-01-05 22:25:12 +00001326 if (OperandNode->isSubClassOf("RegisterClass")) {
1327 const CodeGenRegisterClass &RC =
1328 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00001329 MadeChange |= Child->UpdateNodeType(0, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001330 } else if (OperandNode->isSubClassOf("Operand")) {
1331 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattnerd7349192010-03-19 21:37:09 +00001332 MadeChange |= Child->UpdateNodeType(0, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001333 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001334 MadeChange |= Child->UpdateNodeType(0, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001335 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001336 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001337 } else {
1338 assert(0 && "Unknown operand type!");
1339 abort();
1340 }
1341 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1342 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001343
Christopher Lamb02f69372008-03-10 04:16:09 +00001344 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001345 TP.error("Instruction '" + getOperator()->getName() +
1346 "' was provided too many operands!");
1347
1348 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001349 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001350
1351 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1352
1353 // Node transforms always take one operand.
1354 if (getNumChildren() != 1)
1355 TP.error("Node transform '" + getOperator()->getName() +
1356 "' requires one operand!");
1357
Chris Lattner2cacec52010-03-15 06:00:16 +00001358 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1359
1360
Chris Lattner6eb30122010-02-23 05:51:07 +00001361 // If either the output or input of the xform does not have exact
1362 // type info. We assume they must be the same. Otherwise, it is perfectly
1363 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001364#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001365 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001366 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1367 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001368 return MadeChange;
1369 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001370#endif
1371 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001372}
1373
1374/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1375/// RHS of a commutative operation, not the on LHS.
1376static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1377 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1378 return true;
1379 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1380 return true;
1381 return false;
1382}
1383
1384
1385/// canPatternMatch - If it is impossible for this pattern to match on this
1386/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001387/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001388/// that can never possibly work), and to prevent the pattern permuter from
1389/// generating stuff that is useless.
1390bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001391 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001392 if (isLeaf()) return true;
1393
1394 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1395 if (!getChild(i)->canPatternMatch(Reason, CDP))
1396 return false;
1397
1398 // If this is an intrinsic, handle cases that would make it not match. For
1399 // example, if an operand is required to be an immediate.
1400 if (getOperator()->isSubClassOf("Intrinsic")) {
1401 // TODO:
1402 return true;
1403 }
1404
1405 // If this node is a commutative operator, check that the LHS isn't an
1406 // immediate.
1407 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001408 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1409 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001410 // Scan all of the operands of the node and make sure that only the last one
1411 // is a constant node, unless the RHS also is.
1412 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001413 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1414 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001415 if (OnlyOnRHSOfCommutative(getChild(i))) {
1416 Reason="Immediate value must be on the RHS of commutative operators!";
1417 return false;
1418 }
1419 }
1420 }
1421
1422 return true;
1423}
1424
1425//===----------------------------------------------------------------------===//
1426// TreePattern implementation
1427//
1428
1429TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001430 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001431 isInputPattern = isInput;
1432 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1433 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001434}
1435
1436TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001437 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001438 isInputPattern = isInput;
1439 Trees.push_back(ParseTreePattern(Pat));
1440}
1441
1442TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001443 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001444 isInputPattern = isInput;
1445 Trees.push_back(Pat);
1446}
1447
Chris Lattner6cefb772008-01-05 22:25:12 +00001448void TreePattern::error(const std::string &Msg) const {
1449 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001450 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001451}
1452
Chris Lattner2cacec52010-03-15 06:00:16 +00001453void TreePattern::ComputeNamedNodes() {
1454 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1455 ComputeNamedNodes(Trees[i]);
1456}
1457
1458void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1459 if (!N->getName().empty())
1460 NamedNodes[N->getName()].push_back(N);
1461
1462 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1463 ComputeNamedNodes(N->getChild(i));
1464}
1465
Chris Lattnerd7349192010-03-19 21:37:09 +00001466
Chris Lattner6cefb772008-01-05 22:25:12 +00001467TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1468 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1469 if (!OpDef) error("Pattern has unexpected operator type!");
1470 Record *Operator = OpDef->getDef();
1471
1472 if (Operator->isSubClassOf("ValueType")) {
1473 // If the operator is a ValueType, then this must be "type cast" of a leaf
1474 // node.
1475 if (Dag->getNumArgs() != 1)
1476 error("Type cast only takes one operand!");
1477
1478 Init *Arg = Dag->getArg(0);
1479 TreePatternNode *New;
1480 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1481 Record *R = DI->getDef();
1482 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001483 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001484 std::vector<std::pair<Init*, std::string> >()));
1485 return ParseTreePattern(Dag);
1486 }
Chris Lattner43e47542010-03-08 18:36:19 +00001487
1488 // Input argument?
1489 if (R->getName() == "node") {
1490 if (Dag->getArgName(0).empty())
1491 error("'node' argument requires a name to match with operand list");
1492 Args.push_back(Dag->getArgName(0));
1493 }
1494
Chris Lattnerd7349192010-03-19 21:37:09 +00001495 New = new TreePatternNode(DI, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001496 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1497 New = ParseTreePattern(DI);
1498 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001499 New = new TreePatternNode(II, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001500 if (!Dag->getArgName(0).empty())
1501 error("Constant int argument should not have a name!");
1502 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1503 // Turn this into an IntInit.
1504 Init *II = BI->convertInitializerTo(new IntRecTy());
1505 if (II == 0 || !dynamic_cast<IntInit*>(II))
1506 error("Bits value must be constants!");
1507
Chris Lattnerd7349192010-03-19 21:37:09 +00001508 New = new TreePatternNode(dynamic_cast<IntInit*>(II), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001509 if (!Dag->getArgName(0).empty())
1510 error("Constant int argument should not have a name!");
1511 } else {
1512 Arg->dump();
1513 error("Unknown leaf value for tree pattern!");
1514 return 0;
1515 }
1516
1517 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001518 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1519 New->UpdateNodeType(0, getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001520 if (New->getNumChildren() == 0)
1521 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001522 return New;
1523 }
1524
1525 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001526 if (!Operator->isSubClassOf("PatFrag") &&
1527 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001528 !Operator->isSubClassOf("Instruction") &&
1529 !Operator->isSubClassOf("SDNodeXForm") &&
1530 !Operator->isSubClassOf("Intrinsic") &&
1531 Operator->getName() != "set" &&
1532 Operator->getName() != "implicit" &&
1533 Operator->getName() != "parallel")
1534 error("Unrecognized node '" + Operator->getName() + "'!");
1535
1536 // Check to see if this is something that is illegal in an input pattern.
1537 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1538 Operator->isSubClassOf("SDNodeXForm")))
1539 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1540
1541 std::vector<TreePatternNode*> Children;
1542
1543 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1544 Init *Arg = Dag->getArg(i);
1545 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1546 Children.push_back(ParseTreePattern(DI));
1547 if (Children.back()->getName().empty())
1548 Children.back()->setName(Dag->getArgName(i));
1549 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1550 Record *R = DefI->getDef();
1551 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1552 // TreePatternNode if its own.
1553 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001554 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001555 std::vector<std::pair<Init*, std::string> >()));
1556 --i; // Revisit this node...
1557 } else {
Chris Lattnerd7349192010-03-19 21:37:09 +00001558 TreePatternNode *Node = new TreePatternNode(DefI, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001559 Node->setName(Dag->getArgName(i));
1560 Children.push_back(Node);
1561
1562 // Input argument?
1563 if (R->getName() == "node") {
1564 if (Dag->getArgName(i).empty())
1565 error("'node' argument requires a name to match with operand list");
1566 Args.push_back(Dag->getArgName(i));
1567 }
1568 }
1569 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001570 TreePatternNode *Node = new TreePatternNode(II, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001571 if (!Dag->getArgName(i).empty())
1572 error("Constant int argument should not have a name!");
1573 Children.push_back(Node);
1574 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1575 // Turn this into an IntInit.
1576 Init *II = BI->convertInitializerTo(new IntRecTy());
1577 if (II == 0 || !dynamic_cast<IntInit*>(II))
1578 error("Bits value must be constants!");
1579
Chris Lattnerd7349192010-03-19 21:37:09 +00001580 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II),1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001581 if (!Dag->getArgName(i).empty())
1582 error("Constant int argument should not have a name!");
1583 Children.push_back(Node);
1584 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001585 errs() << '"';
Chris Lattner6cefb772008-01-05 22:25:12 +00001586 Arg->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001587 errs() << "\": ";
Chris Lattner6cefb772008-01-05 22:25:12 +00001588 error("Unknown leaf value for tree pattern!");
1589 }
1590 }
1591
1592 // If the operator is an intrinsic, then this is just syntactic sugar for for
1593 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1594 // convert the intrinsic name to a number.
1595 if (Operator->isSubClassOf("Intrinsic")) {
1596 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1597 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1598
1599 // If this intrinsic returns void, it must have side-effects and thus a
1600 // chain.
Chris Lattner93dc92e2010-03-22 20:56:36 +00001601 if (Int.IS.RetVTs.empty()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001602 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1603 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1604 // Has side-effects, requires chain.
1605 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1606 } else {
1607 // Otherwise, no chain.
1608 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1609 }
1610
Chris Lattnerd7349192010-03-19 21:37:09 +00001611 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001612 Children.insert(Children.begin(), IIDNode);
1613 }
1614
Chris Lattnerd7349192010-03-19 21:37:09 +00001615 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1616 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Nate Begeman7cee8172009-03-19 05:21:56 +00001617 Result->setName(Dag->getName());
1618 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001619}
1620
1621/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001622/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001623/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001624bool TreePattern::
1625InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1626 if (NamedNodes.empty())
1627 ComputeNamedNodes();
1628
Chris Lattner6cefb772008-01-05 22:25:12 +00001629 bool MadeChange = true;
1630 while (MadeChange) {
1631 MadeChange = false;
1632 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1633 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner2cacec52010-03-15 06:00:16 +00001634
1635 // If there are constraints on our named nodes, apply them.
1636 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1637 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1638 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1639
1640 // If we have input named node types, propagate their types to the named
1641 // values here.
1642 if (InNamedTypes) {
1643 // FIXME: Should be error?
1644 assert(InNamedTypes->count(I->getKey()) &&
1645 "Named node in output pattern but not input pattern?");
1646
1647 const SmallVectorImpl<TreePatternNode*> &InNodes =
1648 InNamedTypes->find(I->getKey())->second;
1649
1650 // The input types should be fully resolved by now.
1651 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1652 // If this node is a register class, and it is the root of the pattern
1653 // then we're mapping something onto an input register. We allow
1654 // changing the type of the input register in this case. This allows
1655 // us to match things like:
1656 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1657 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1658 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1659 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1660 continue;
1661 }
1662
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001663 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001664 InNodes[0]->getNumTypes() == 1 &&
1665 "FIXME: cannot name multiple result nodes yet");
1666 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1667 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001668 }
1669 }
1670
1671 // If there are multiple nodes with the same name, they must all have the
1672 // same type.
1673 if (I->second.size() > 1) {
1674 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001675 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001676 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001677 "FIXME: cannot name multiple result nodes yet");
1678
1679 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1680 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001681 }
1682 }
1683 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001684 }
1685
1686 bool HasUnresolvedTypes = false;
1687 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1688 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1689 return !HasUnresolvedTypes;
1690}
1691
Daniel Dunbar1a551802009-07-03 00:10:29 +00001692void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001693 OS << getRecord()->getName();
1694 if (!Args.empty()) {
1695 OS << "(" << Args[0];
1696 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1697 OS << ", " << Args[i];
1698 OS << ")";
1699 }
1700 OS << ": ";
1701
1702 if (Trees.size() > 1)
1703 OS << "[\n";
1704 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1705 OS << "\t";
1706 Trees[i]->print(OS);
1707 OS << "\n";
1708 }
1709
1710 if (Trees.size() > 1)
1711 OS << "]\n";
1712}
1713
Daniel Dunbar1a551802009-07-03 00:10:29 +00001714void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001715
1716//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001717// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001718//
1719
Chris Lattnerfe718932008-01-06 01:10:31 +00001720CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001721 Intrinsics = LoadIntrinsics(Records, false);
1722 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001723 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001724 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001725 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001726 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001727 ParseDefaultOperands();
1728 ParseInstructions();
1729 ParsePatterns();
1730
1731 // Generate variants. For example, commutative patterns can match
1732 // multiple ways. Add them to PatternsToMatch as well.
1733 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001734
1735 // Infer instruction flags. For example, we can detect loads,
1736 // stores, and side effects in many cases by examining an
1737 // instruction's pattern.
1738 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001739}
1740
Chris Lattnerfe718932008-01-06 01:10:31 +00001741CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001742 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001743 E = PatternFragments.end(); I != E; ++I)
1744 delete I->second;
1745}
1746
1747
Chris Lattnerfe718932008-01-06 01:10:31 +00001748Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001749 Record *N = Records.getDef(Name);
1750 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001751 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001752 exit(1);
1753 }
1754 return N;
1755}
1756
1757// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001758void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001759 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1760 while (!Nodes.empty()) {
1761 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1762 Nodes.pop_back();
1763 }
1764
Jim Grosbachda4231f2009-03-26 16:17:51 +00001765 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001766 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1767 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1768 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1769}
1770
1771/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1772/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001773void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001774 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1775 while (!Xforms.empty()) {
1776 Record *XFormNode = Xforms.back();
1777 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1778 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001779 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001780
1781 Xforms.pop_back();
1782 }
1783}
1784
Chris Lattnerfe718932008-01-06 01:10:31 +00001785void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001786 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1787 while (!AMs.empty()) {
1788 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1789 AMs.pop_back();
1790 }
1791}
1792
1793
1794/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1795/// file, building up the PatternFragments map. After we've collected them all,
1796/// inline fragments together as necessary, so that there are no references left
1797/// inside a pattern fragment to a pattern fragment.
1798///
Chris Lattnerfe718932008-01-06 01:10:31 +00001799void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001800 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1801
Chris Lattnerdc32f982008-01-05 22:43:57 +00001802 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001803 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1804 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1805 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1806 PatternFragments[Fragments[i]] = P;
1807
Chris Lattnerdc32f982008-01-05 22:43:57 +00001808 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001809 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001810 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001811
Chris Lattnerdc32f982008-01-05 22:43:57 +00001812 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001813 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1814
1815 // Parse the operands list.
1816 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1817 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1818 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001819 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001820 if (!OpsOp ||
1821 (OpsOp->getDef()->getName() != "ops" &&
1822 OpsOp->getDef()->getName() != "outs" &&
1823 OpsOp->getDef()->getName() != "ins"))
1824 P->error("Operands list should start with '(ops ... '!");
1825
1826 // Copy over the arguments.
1827 Args.clear();
1828 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1829 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1830 static_cast<DefInit*>(OpsList->getArg(j))->
1831 getDef()->getName() != "node")
1832 P->error("Operands list should all be 'node' values.");
1833 if (OpsList->getArgName(j).empty())
1834 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001835 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001836 P->error("'" + OpsList->getArgName(j) +
1837 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001838 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001839 Args.push_back(OpsList->getArgName(j));
1840 }
1841
Chris Lattnerdc32f982008-01-05 22:43:57 +00001842 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001843 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001844 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001845
Chris Lattnerdc32f982008-01-05 22:43:57 +00001846 // If there is a code init for this fragment, keep track of the fact that
1847 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001848 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001849 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001850 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001851
1852 // If there is a node transformation corresponding to this, keep track of
1853 // it.
1854 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1855 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1856 P->getOnlyTree()->setTransformFn(Transform);
1857 }
1858
Chris Lattner6cefb772008-01-05 22:25:12 +00001859 // Now that we've parsed all of the tree fragments, do a closure on them so
1860 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001861 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1862 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001863 ThePat->InlinePatternFragments();
1864
1865 // Infer as many types as possible. Don't worry about it if we don't infer
1866 // all of them, some may depend on the inputs of the pattern.
1867 try {
1868 ThePat->InferAllTypes();
1869 } catch (...) {
1870 // If this pattern fragment is not supported by this target (no types can
1871 // satisfy its constraints), just ignore it. If the bogus pattern is
1872 // actually used by instructions, the type consistency error will be
1873 // reported there.
1874 }
1875
1876 // If debugging, print out the pattern fragment result.
1877 DEBUG(ThePat->dump());
1878 }
1879}
1880
Chris Lattnerfe718932008-01-06 01:10:31 +00001881void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001882 std::vector<Record*> DefaultOps[2];
1883 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1884 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1885
1886 // Find some SDNode.
1887 assert(!SDNodes.empty() && "No SDNodes parsed?");
1888 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1889
1890 for (unsigned iter = 0; iter != 2; ++iter) {
1891 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1892 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1893
1894 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1895 // SomeSDnode so that we can parse this.
1896 std::vector<std::pair<Init*, std::string> > Ops;
1897 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1898 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1899 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001900 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001901
1902 // Create a TreePattern to parse this.
1903 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1904 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1905
1906 // Copy the operands over into a DAGDefaultOperand.
1907 DAGDefaultOperand DefaultOpInfo;
1908
1909 TreePatternNode *T = P.getTree(0);
1910 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1911 TreePatternNode *TPN = T->getChild(op);
1912 while (TPN->ApplyTypeConstraints(P, false))
1913 /* Resolve all types */;
1914
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001915 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001916 if (iter == 0)
1917 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001918 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00001919 else
1920 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001921 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001922 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001923 DefaultOpInfo.DefaultOps.push_back(TPN);
1924 }
1925
1926 // Insert it into the DefaultOperands map so we can find it later.
1927 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1928 }
1929 }
1930}
1931
1932/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1933/// instruction input. Return true if this is a real use.
1934static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1935 std::map<std::string, TreePatternNode*> &InstInputs,
1936 std::vector<Record*> &InstImpInputs) {
1937 // No name -> not interesting.
1938 if (Pat->getName().empty()) {
1939 if (Pat->isLeaf()) {
1940 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1941 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1942 I->error("Input " + DI->getDef()->getName() + " must be named!");
1943 else if (DI && DI->getDef()->isSubClassOf("Register"))
1944 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001945 }
1946 return false;
1947 }
1948
1949 Record *Rec;
1950 if (Pat->isLeaf()) {
1951 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1952 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1953 Rec = DI->getDef();
1954 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001955 Rec = Pat->getOperator();
1956 }
1957
1958 // SRCVALUE nodes are ignored.
1959 if (Rec->getName() == "srcvalue")
1960 return false;
1961
1962 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1963 if (!Slot) {
1964 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00001965 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00001966 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00001967 Record *SlotRec;
1968 if (Slot->isLeaf()) {
1969 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1970 } else {
1971 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1972 SlotRec = Slot->getOperator();
1973 }
1974
1975 // Ensure that the inputs agree if we've already seen this input.
1976 if (Rec != SlotRec)
1977 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00001978 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00001979 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00001980 return true;
1981}
1982
1983/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1984/// part of "I", the instruction), computing the set of inputs and outputs of
1985/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001986void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001987FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1988 std::map<std::string, TreePatternNode*> &InstInputs,
1989 std::map<std::string, TreePatternNode*>&InstResults,
1990 std::vector<Record*> &InstImpInputs,
1991 std::vector<Record*> &InstImpResults) {
1992 if (Pat->isLeaf()) {
1993 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1994 if (!isUse && Pat->getTransformFn())
1995 I->error("Cannot specify a transform function for a non-input value!");
1996 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001997 }
1998
1999 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002000 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2001 TreePatternNode *Dest = Pat->getChild(i);
2002 if (!Dest->isLeaf())
2003 I->error("implicitly defined value should be a register!");
2004
2005 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2006 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2007 I->error("implicitly defined value should be a register!");
2008 InstImpResults.push_back(Val->getDef());
2009 }
2010 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002011 }
2012
2013 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002014 // If this is not a set, verify that the children nodes are not void typed,
2015 // and recurse.
2016 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002017 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002018 I->error("Cannot have void nodes inside of patterns!");
2019 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2020 InstImpInputs, InstImpResults);
2021 }
2022
2023 // If this is a non-leaf node with no children, treat it basically as if
2024 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00002025 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002026
2027 if (!isUse && Pat->getTransformFn())
2028 I->error("Cannot specify a transform function for a non-input value!");
2029 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002030 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002031
2032 // Otherwise, this is a set, validate and collect instruction results.
2033 if (Pat->getNumChildren() == 0)
2034 I->error("set requires operands!");
2035
2036 if (Pat->getTransformFn())
2037 I->error("Cannot specify a transform function on a set node!");
2038
2039 // Check the set destinations.
2040 unsigned NumDests = Pat->getNumChildren()-1;
2041 for (unsigned i = 0; i != NumDests; ++i) {
2042 TreePatternNode *Dest = Pat->getChild(i);
2043 if (!Dest->isLeaf())
2044 I->error("set destination should be a register!");
2045
2046 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2047 if (!Val)
2048 I->error("set destination should be a register!");
2049
2050 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002051 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002052 if (Dest->getName().empty())
2053 I->error("set destination must have a name!");
2054 if (InstResults.count(Dest->getName()))
2055 I->error("cannot set '" + Dest->getName() +"' multiple times");
2056 InstResults[Dest->getName()] = Dest;
2057 } else if (Val->getDef()->isSubClassOf("Register")) {
2058 InstImpResults.push_back(Val->getDef());
2059 } else {
2060 I->error("set destination should be a register!");
2061 }
2062 }
2063
2064 // Verify and collect info from the computation.
2065 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2066 InstInputs, InstResults,
2067 InstImpInputs, InstImpResults);
2068}
2069
Dan Gohmanee4fa192008-04-03 00:02:49 +00002070//===----------------------------------------------------------------------===//
2071// Instruction Analysis
2072//===----------------------------------------------------------------------===//
2073
2074class InstAnalyzer {
2075 const CodeGenDAGPatterns &CDP;
2076 bool &mayStore;
2077 bool &mayLoad;
2078 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002079 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002080public:
2081 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Chris Lattner1e506312010-03-19 05:34:15 +00002082 bool &maystore, bool &mayload, bool &hse, bool &isv)
2083 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
2084 IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002085 }
2086
2087 /// Analyze - Analyze the specified instruction, returning true if the
2088 /// instruction had a pattern.
2089 bool Analyze(Record *InstRecord) {
2090 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2091 if (Pattern == 0) {
2092 HasSideEffects = 1;
2093 return false; // No pattern.
2094 }
2095
2096 // FIXME: Assume only the first tree is the pattern. The others are clobber
2097 // nodes.
2098 AnalyzeNode(Pattern->getTree(0));
2099 return true;
2100 }
2101
2102private:
2103 void AnalyzeNode(const TreePatternNode *N) {
2104 if (N->isLeaf()) {
2105 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2106 Record *LeafRec = DI->getDef();
2107 // Handle ComplexPattern leaves.
2108 if (LeafRec->isSubClassOf("ComplexPattern")) {
2109 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2110 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2111 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2112 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2113 }
2114 }
2115 return;
2116 }
2117
2118 // Analyze children.
2119 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2120 AnalyzeNode(N->getChild(i));
2121
2122 // Ignore set nodes, which are not SDNodes.
2123 if (N->getOperator()->getName() == "set")
2124 return;
2125
2126 // Get information about the SDNode for the operator.
2127 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2128
2129 // Notice properties of the node.
2130 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2131 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2132 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002133 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002134
2135 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2136 // If this is an intrinsic, analyze it.
2137 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2138 mayLoad = true;// These may load memory.
2139
2140 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2141 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2142
2143 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2144 // WriteMem intrinsics can have other strange effects.
2145 HasSideEffects = true;
2146 }
2147 }
2148
2149};
2150
2151static void InferFromPattern(const CodeGenInstruction &Inst,
2152 bool &MayStore, bool &MayLoad,
Chris Lattner1e506312010-03-19 05:34:15 +00002153 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002154 const CodeGenDAGPatterns &CDP) {
Chris Lattner1e506312010-03-19 05:34:15 +00002155 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002156
2157 bool HadPattern =
Chris Lattner1e506312010-03-19 05:34:15 +00002158 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2159 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002160
2161 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2162 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2163 // If we decided that this is a store from the pattern, then the .td file
2164 // entry is redundant.
2165 if (MayStore)
2166 fprintf(stderr,
2167 "Warning: mayStore flag explicitly set on instruction '%s'"
2168 " but flag already inferred from pattern.\n",
2169 Inst.TheDef->getName().c_str());
2170 MayStore = true;
2171 }
2172
2173 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2174 // If we decided that this is a load from the pattern, then the .td file
2175 // entry is redundant.
2176 if (MayLoad)
2177 fprintf(stderr,
2178 "Warning: mayLoad flag explicitly set on instruction '%s'"
2179 " but flag already inferred from pattern.\n",
2180 Inst.TheDef->getName().c_str());
2181 MayLoad = true;
2182 }
2183
2184 if (Inst.neverHasSideEffects) {
2185 if (HadPattern)
2186 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2187 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2188 HasSideEffects = false;
2189 }
2190
2191 if (Inst.hasSideEffects) {
2192 if (HasSideEffects)
2193 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2194 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2195 HasSideEffects = true;
2196 }
Chris Lattner1e506312010-03-19 05:34:15 +00002197
2198 if (Inst.isVariadic)
2199 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002200}
2201
Chris Lattner6cefb772008-01-05 22:25:12 +00002202/// ParseInstructions - Parse all of the instructions, inlining and resolving
2203/// any fragments involved. This populates the Instructions list with fully
2204/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002205void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002206 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2207
2208 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2209 ListInit *LI = 0;
2210
2211 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2212 LI = Instrs[i]->getValueAsListInit("Pattern");
2213
2214 // If there is no pattern, only collect minimal information about the
2215 // instruction for its operand list. We have to assume that there is one
2216 // result, as we have no detailed info.
2217 if (!LI || LI->getSize() == 0) {
2218 std::vector<Record*> Results;
2219 std::vector<Record*> Operands;
2220
Chris Lattnerf30187a2010-03-19 00:07:20 +00002221 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002222
2223 if (InstInfo.OperandList.size() != 0) {
2224 if (InstInfo.NumDefs == 0) {
2225 // These produce no results
2226 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2227 Operands.push_back(InstInfo.OperandList[j].Rec);
2228 } else {
2229 // Assume the first operand is the result.
2230 Results.push_back(InstInfo.OperandList[0].Rec);
2231
2232 // The rest are inputs.
2233 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2234 Operands.push_back(InstInfo.OperandList[j].Rec);
2235 }
2236 }
2237
2238 // Create and insert the instruction.
2239 std::vector<Record*> ImpResults;
2240 std::vector<Record*> ImpOperands;
2241 Instructions.insert(std::make_pair(Instrs[i],
2242 DAGInstruction(0, Results, Operands, ImpResults,
2243 ImpOperands)));
2244 continue; // no pattern.
2245 }
2246
2247 // Parse the instruction.
2248 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2249 // Inline pattern fragments into it.
2250 I->InlinePatternFragments();
2251
2252 // Infer as many types as possible. If we cannot infer all of them, we can
2253 // never do anything with this instruction pattern: report it to the user.
2254 if (!I->InferAllTypes())
2255 I->error("Could not infer all types in pattern!");
2256
2257 // InstInputs - Keep track of all of the inputs of the instruction, along
2258 // with the record they are declared as.
2259 std::map<std::string, TreePatternNode*> InstInputs;
2260
2261 // InstResults - Keep track of all the virtual registers that are 'set'
2262 // in the instruction, including what reg class they are.
2263 std::map<std::string, TreePatternNode*> InstResults;
2264
2265 std::vector<Record*> InstImpInputs;
2266 std::vector<Record*> InstImpResults;
2267
2268 // Verify that the top-level forms in the instruction are of void type, and
2269 // fill in the InstResults map.
2270 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2271 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002272 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002273 I->error("Top-level forms in instruction pattern should have"
2274 " void types");
2275
2276 // Find inputs and outputs, and verify the structure of the uses/defs.
2277 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2278 InstImpInputs, InstImpResults);
2279 }
2280
2281 // Now that we have inputs and outputs of the pattern, inspect the operands
2282 // list for the instruction. This determines the order that operands are
2283 // added to the machine instruction the node corresponds to.
2284 unsigned NumResults = InstResults.size();
2285
2286 // Parse the operands list from the (ops) list, validating it.
2287 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002288 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002289
2290 // Check that all of the results occur first in the list.
2291 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002292 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002293 for (unsigned i = 0; i != NumResults; ++i) {
2294 if (i == CGI.OperandList.size())
2295 I->error("'" + InstResults.begin()->first +
2296 "' set but does not appear in operand list!");
2297 const std::string &OpName = CGI.OperandList[i].Name;
2298
2299 // Check that it exists in InstResults.
2300 TreePatternNode *RNode = InstResults[OpName];
2301 if (RNode == 0)
2302 I->error("Operand $" + OpName + " does not exist in operand list!");
2303
2304 if (i == 0)
2305 Res0Node = RNode;
2306 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2307 if (R == 0)
2308 I->error("Operand $" + OpName + " should be a set destination: all "
2309 "outputs must occur before inputs in operand list!");
2310
2311 if (CGI.OperandList[i].Rec != R)
2312 I->error("Operand $" + OpName + " class mismatch!");
2313
2314 // Remember the return type.
2315 Results.push_back(CGI.OperandList[i].Rec);
2316
2317 // Okay, this one checks out.
2318 InstResults.erase(OpName);
2319 }
2320
2321 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2322 // the copy while we're checking the inputs.
2323 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2324
2325 std::vector<TreePatternNode*> ResultNodeOperands;
2326 std::vector<Record*> Operands;
2327 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2328 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2329 const std::string &OpName = Op.Name;
2330 if (OpName.empty())
2331 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2332
2333 if (!InstInputsCheck.count(OpName)) {
2334 // If this is an predicate operand or optional def operand with an
2335 // DefaultOps set filled in, we can ignore this. When we codegen it,
2336 // we will do so as always executed.
2337 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2338 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2339 // Does it have a non-empty DefaultOps field? If so, ignore this
2340 // operand.
2341 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2342 continue;
2343 }
2344 I->error("Operand $" + OpName +
2345 " does not appear in the instruction pattern");
2346 }
2347 TreePatternNode *InVal = InstInputsCheck[OpName];
2348 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2349
2350 if (InVal->isLeaf() &&
2351 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2352 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2353 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2354 I->error("Operand $" + OpName + "'s register class disagrees"
2355 " between the operand and pattern");
2356 }
2357 Operands.push_back(Op.Rec);
2358
2359 // Construct the result for the dest-pattern operand list.
2360 TreePatternNode *OpNode = InVal->clone();
2361
2362 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002363 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002364
2365 // Promote the xform function to be an explicit node if set.
2366 if (Record *Xform = OpNode->getTransformFn()) {
2367 OpNode->setTransformFn(0);
2368 std::vector<TreePatternNode*> Children;
2369 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002370 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002371 }
2372
2373 ResultNodeOperands.push_back(OpNode);
2374 }
2375
2376 if (!InstInputsCheck.empty())
2377 I->error("Input operand $" + InstInputsCheck.begin()->first +
2378 " occurs in pattern but not in operands list!");
2379
2380 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002381 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2382 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002383 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002384 for (unsigned i = 0; i != NumResults; ++i)
2385 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002386
2387 // Create and insert the instruction.
2388 // FIXME: InstImpResults and InstImpInputs should not be part of
2389 // DAGInstruction.
2390 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2391 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2392
2393 // Use a temporary tree pattern to infer all types and make sure that the
2394 // constructed result is correct. This depends on the instruction already
2395 // being inserted into the Instructions map.
2396 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002397 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002398
2399 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2400 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2401
2402 DEBUG(I->dump());
2403 }
2404
2405 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002406 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2407 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002408 E = Instructions.end(); II != E; ++II) {
2409 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002410 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002411 if (I == 0) continue; // No pattern.
2412
2413 // FIXME: Assume only the first tree is the pattern. The others are clobber
2414 // nodes.
2415 TreePatternNode *Pattern = I->getTree(0);
2416 TreePatternNode *SrcPattern;
2417 if (Pattern->getOperator()->getName() == "set") {
2418 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2419 } else{
2420 // Not a set (store or something?)
2421 SrcPattern = Pattern;
2422 }
2423
Chris Lattner6cefb772008-01-05 22:25:12 +00002424 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002425 AddPatternToMatch(I,
2426 PatternToMatch(Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002427 SrcPattern,
2428 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002429 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002430 Instr->getValueAsInt("AddedComplexity"),
2431 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002432 }
2433}
2434
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002435
2436typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2437
Chris Lattner967d54a2010-02-23 06:35:45 +00002438static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002439 std::map<std::string, NameRecord> &Names,
2440 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002441 if (!P->getName().empty()) {
2442 NameRecord &Rec = Names[P->getName()];
2443 // If this is the first instance of the name, remember the node.
2444 if (Rec.second++ == 0)
2445 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002446 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002447 PatternTop->error("repetition of value: $" + P->getName() +
2448 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002449 }
Chris Lattner967d54a2010-02-23 06:35:45 +00002450
2451 if (!P->isLeaf()) {
2452 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002453 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002454 }
2455}
2456
Chris Lattner25b6f912010-02-23 06:16:51 +00002457void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2458 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002459 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002460 std::string Reason;
2461 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002462 Pattern->error("Pattern can never match: " + Reason);
Chris Lattner25b6f912010-02-23 06:16:51 +00002463
Chris Lattner405f1252010-03-01 22:29:19 +00002464 // If the source pattern's root is a complex pattern, that complex pattern
2465 // must specify the nodes it can potentially match.
2466 if (const ComplexPattern *CP =
2467 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2468 if (CP->getRootNodes().empty())
2469 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2470 " could match");
2471
2472
Chris Lattner967d54a2010-02-23 06:35:45 +00002473 // Find all of the named values in the input and output, ensure they have the
2474 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002475 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002476 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2477 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002478
2479 // Scan all of the named values in the destination pattern, rejecting them if
2480 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002481 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002482 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002483 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002484 Pattern->error("Pattern has input without matching name in output: $" +
2485 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002486 }
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002487
2488 // Scan all of the named values in the source pattern, rejecting them if the
2489 // name isn't used in the dest, and isn't used to tie two values together.
2490 for (std::map<std::string, NameRecord>::iterator
2491 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2492 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2493 Pattern->error("Pattern has dead named input: $" + I->first);
2494
Chris Lattner25b6f912010-02-23 06:16:51 +00002495 PatternsToMatch.push_back(PTM);
2496}
2497
2498
Dan Gohmanee4fa192008-04-03 00:02:49 +00002499
2500void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002501 const std::vector<const CodeGenInstruction*> &Instructions =
2502 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002503 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2504 CodeGenInstruction &InstInfo =
2505 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002506 // Determine properties of the instruction from its pattern.
Chris Lattner1e506312010-03-19 05:34:15 +00002507 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2508 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2509 *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002510 InstInfo.mayStore = MayStore;
2511 InstInfo.mayLoad = MayLoad;
2512 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002513 InstInfo.isVariadic = IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002514 }
2515}
2516
Chris Lattner2cacec52010-03-15 06:00:16 +00002517/// Given a pattern result with an unresolved type, see if we can find one
2518/// instruction with an unresolved result type. Force this result type to an
2519/// arbitrary element if it's possible types to converge results.
2520static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2521 if (N->isLeaf())
2522 return false;
2523
2524 // Analyze children.
2525 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2526 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2527 return true;
2528
2529 if (!N->getOperator()->isSubClassOf("Instruction"))
2530 return false;
2531
2532 // If this type is already concrete or completely unknown we can't do
2533 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00002534 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2535 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2536 continue;
Chris Lattner2cacec52010-03-15 06:00:16 +00002537
Chris Lattnerd7349192010-03-19 21:37:09 +00002538 // Otherwise, force its type to the first possibility (an arbitrary choice).
2539 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2540 return true;
2541 }
2542
2543 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00002544}
2545
Chris Lattnerfe718932008-01-06 01:10:31 +00002546void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002547 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2548
2549 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002550 Record *CurPattern = Patterns[i];
2551 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Chris Lattner6cefb772008-01-05 22:25:12 +00002552 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2553 Record *Operator = OpDef->getDef();
2554 TreePattern *Pattern;
2555 if (Operator->getName() != "parallel")
Chris Lattnerd7349192010-03-19 21:37:09 +00002556 Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002557 else {
2558 std::vector<Init*> Values;
David Greenee1b46912009-06-08 20:23:18 +00002559 RecTy *ListTy = 0;
2560 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002561 Values.push_back(Tree->getArg(j));
David Greenee1b46912009-06-08 20:23:18 +00002562 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2563 if (TArg == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002564 errs() << "In dag: " << Tree->getAsString();
2565 errs() << " -- Untyped argument in pattern\n";
David Greenee1b46912009-06-08 20:23:18 +00002566 assert(0 && "Untyped argument in pattern");
2567 }
2568 if (ListTy != 0) {
2569 ListTy = resolveTypes(ListTy, TArg->getType());
2570 if (ListTy == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002571 errs() << "In dag: " << Tree->getAsString();
2572 errs() << " -- Incompatible types in pattern arguments\n";
David Greenee1b46912009-06-08 20:23:18 +00002573 assert(0 && "Incompatible types in pattern arguments");
2574 }
2575 }
2576 else {
Bill Wendlingee1f6b02009-06-09 18:49:42 +00002577 ListTy = TArg->getType();
David Greenee1b46912009-06-08 20:23:18 +00002578 }
2579 }
2580 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
Chris Lattnerd7349192010-03-19 21:37:09 +00002581 Pattern = new TreePattern(CurPattern, LI, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002582 }
2583
2584 // Inline pattern fragments into it.
2585 Pattern->InlinePatternFragments();
2586
Chris Lattnerd7349192010-03-19 21:37:09 +00002587 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00002588 if (LI->getSize() == 0) continue; // no pattern.
2589
2590 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00002591 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002592
2593 // Inline pattern fragments into it.
2594 Result->InlinePatternFragments();
2595
2596 if (Result->getNumTrees() != 1)
2597 Result->error("Cannot handle instructions producing instructions "
2598 "with temporaries yet!");
2599
2600 bool IterateInference;
2601 bool InferredAllPatternTypes, InferredAllResultTypes;
2602 do {
2603 // Infer as many types as possible. If we cannot infer all of them, we
2604 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002605 InferredAllPatternTypes =
2606 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002607
2608 // Infer as many types as possible. If we cannot infer all of them, we
2609 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002610 InferredAllResultTypes =
2611 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002612
Chris Lattner6c6ba362010-03-18 23:15:10 +00002613 IterateInference = false;
2614
Chris Lattner6cefb772008-01-05 22:25:12 +00002615 // Apply the type of the result to the source pattern. This helps us
2616 // resolve cases where the input type is known to be a pointer type (which
2617 // is considered resolved), but the result knows it needs to be 32- or
2618 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00002619 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2620 Pattern->getTree(0)->getNumTypes());
2621 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00002622 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002623 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002624 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002625 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002626 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002627
2628 // If our iteration has converged and the input pattern's types are fully
2629 // resolved but the result pattern is not fully resolved, we may have a
2630 // situation where we have two instructions in the result pattern and
2631 // the instructions require a common register class, but don't care about
2632 // what actual MVT is used. This is actually a bug in our modelling:
2633 // output patterns should have register classes, not MVTs.
2634 //
2635 // In any case, to handle this, we just go through and disambiguate some
2636 // arbitrary types to the result pattern's nodes.
2637 if (!IterateInference && InferredAllPatternTypes &&
2638 !InferredAllResultTypes)
2639 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2640 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002641 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002642
Chris Lattner6cefb772008-01-05 22:25:12 +00002643 // Verify that we inferred enough types that we can do something with the
2644 // pattern and result. If these fire the user has to add type casts.
2645 if (!InferredAllPatternTypes)
2646 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002647 if (!InferredAllResultTypes) {
2648 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002649 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002650 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002651
2652 // Validate that the input pattern is correct.
2653 std::map<std::string, TreePatternNode*> InstInputs;
2654 std::map<std::string, TreePatternNode*> InstResults;
2655 std::vector<Record*> InstImpInputs;
2656 std::vector<Record*> InstImpResults;
2657 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2658 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2659 InstInputs, InstResults,
2660 InstImpInputs, InstImpResults);
2661
2662 // Promote the xform function to be an explicit node if set.
2663 TreePatternNode *DstPattern = Result->getOnlyTree();
2664 std::vector<TreePatternNode*> ResultNodeOperands;
2665 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2666 TreePatternNode *OpNode = DstPattern->getChild(ii);
2667 if (Record *Xform = OpNode->getTransformFn()) {
2668 OpNode->setTransformFn(0);
2669 std::vector<TreePatternNode*> Children;
2670 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002671 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002672 }
2673 ResultNodeOperands.push_back(OpNode);
2674 }
2675 DstPattern = Result->getOnlyTree();
2676 if (!DstPattern->isLeaf())
2677 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00002678 ResultNodeOperands,
2679 DstPattern->getNumTypes());
2680
2681 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2682 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2683
Chris Lattner6cefb772008-01-05 22:25:12 +00002684 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2685 Temp.InferAllTypes();
2686
Chris Lattner6cefb772008-01-05 22:25:12 +00002687
Chris Lattner25b6f912010-02-23 06:16:51 +00002688 AddPatternToMatch(Pattern,
Chris Lattnerd7349192010-03-19 21:37:09 +00002689 PatternToMatch(CurPattern->getValueAsListInit("Predicates"),
2690 Pattern->getTree(0),
2691 Temp.getOnlyTree(), InstImpResults,
2692 CurPattern->getValueAsInt("AddedComplexity"),
2693 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002694 }
2695}
2696
2697/// CombineChildVariants - Given a bunch of permutations of each child of the
2698/// 'operator' node, put them together in all possible ways.
2699static void CombineChildVariants(TreePatternNode *Orig,
2700 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2701 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002702 CodeGenDAGPatterns &CDP,
2703 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002704 // Make sure that each operand has at least one variant to choose from.
2705 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2706 if (ChildVariants[i].empty())
2707 return;
2708
2709 // The end result is an all-pairs construction of the resultant pattern.
2710 std::vector<unsigned> Idxs;
2711 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002712 bool NotDone;
2713 do {
2714#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002715 DEBUG(if (!Idxs.empty()) {
2716 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2717 for (unsigned i = 0; i < Idxs.size(); ++i) {
2718 errs() << Idxs[i] << " ";
2719 }
2720 errs() << "]\n";
2721 });
Scott Michel327d0652008-03-05 17:49:05 +00002722#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002723 // Create the variant and add it to the output list.
2724 std::vector<TreePatternNode*> NewChildren;
2725 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2726 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00002727 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2728 Orig->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002729
2730 // Copy over properties.
2731 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002732 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002733 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00002734 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2735 R->setType(i, Orig->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002736
Scott Michel327d0652008-03-05 17:49:05 +00002737 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002738 std::string ErrString;
2739 if (!R->canPatternMatch(ErrString, CDP)) {
2740 delete R;
2741 } else {
2742 bool AlreadyExists = false;
2743
2744 // Scan to see if this pattern has already been emitted. We can get
2745 // duplication due to things like commuting:
2746 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2747 // which are the same pattern. Ignore the dups.
2748 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002749 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002750 AlreadyExists = true;
2751 break;
2752 }
2753
2754 if (AlreadyExists)
2755 delete R;
2756 else
2757 OutVariants.push_back(R);
2758 }
2759
Scott Michel327d0652008-03-05 17:49:05 +00002760 // Increment indices to the next permutation by incrementing the
2761 // indicies from last index backward, e.g., generate the sequence
2762 // [0, 0], [0, 1], [1, 0], [1, 1].
2763 int IdxsIdx;
2764 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2765 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2766 Idxs[IdxsIdx] = 0;
2767 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002768 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002769 }
Scott Michel327d0652008-03-05 17:49:05 +00002770 NotDone = (IdxsIdx >= 0);
2771 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002772}
2773
2774/// CombineChildVariants - A helper function for binary operators.
2775///
2776static void CombineChildVariants(TreePatternNode *Orig,
2777 const std::vector<TreePatternNode*> &LHS,
2778 const std::vector<TreePatternNode*> &RHS,
2779 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002780 CodeGenDAGPatterns &CDP,
2781 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002782 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2783 ChildVariants.push_back(LHS);
2784 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002785 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002786}
2787
2788
2789static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2790 std::vector<TreePatternNode *> &Children) {
2791 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2792 Record *Operator = N->getOperator();
2793
2794 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002795 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002796 N->getTransformFn()) {
2797 Children.push_back(N);
2798 return;
2799 }
2800
2801 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2802 Children.push_back(N->getChild(0));
2803 else
2804 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2805
2806 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2807 Children.push_back(N->getChild(1));
2808 else
2809 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2810}
2811
2812/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2813/// the (potentially recursive) pattern by using algebraic laws.
2814///
2815static void GenerateVariantsOf(TreePatternNode *N,
2816 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002817 CodeGenDAGPatterns &CDP,
2818 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002819 // We cannot permute leaves.
2820 if (N->isLeaf()) {
2821 OutVariants.push_back(N);
2822 return;
2823 }
2824
2825 // Look up interesting info about the node.
2826 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2827
Jim Grosbachda4231f2009-03-26 16:17:51 +00002828 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002829 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002830 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002831 std::vector<TreePatternNode*> MaximalChildren;
2832 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2833
2834 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2835 // permutations.
2836 if (MaximalChildren.size() == 3) {
2837 // Find the variants of all of our maximal children.
2838 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002839 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2840 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2841 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002842
2843 // There are only two ways we can permute the tree:
2844 // (A op B) op C and A op (B op C)
2845 // Within these forms, we can also permute A/B/C.
2846
2847 // Generate legal pair permutations of A/B/C.
2848 std::vector<TreePatternNode*> ABVariants;
2849 std::vector<TreePatternNode*> BAVariants;
2850 std::vector<TreePatternNode*> ACVariants;
2851 std::vector<TreePatternNode*> CAVariants;
2852 std::vector<TreePatternNode*> BCVariants;
2853 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002854 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2855 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2856 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2857 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2858 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2859 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002860
2861 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002862 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2863 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2864 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2865 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2866 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2867 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002868
2869 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002870 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2871 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2872 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2873 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2874 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2875 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002876 return;
2877 }
2878 }
2879
2880 // Compute permutations of all children.
2881 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2882 ChildVariants.resize(N->getNumChildren());
2883 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002884 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002885
2886 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002887 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002888
2889 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002890 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2891 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2892 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2893 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002894 // Don't count children which are actually register references.
2895 unsigned NC = 0;
2896 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2897 TreePatternNode *Child = N->getChild(i);
2898 if (Child->isLeaf())
2899 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2900 Record *RR = DI->getDef();
2901 if (RR->isSubClassOf("Register"))
2902 continue;
2903 }
2904 NC++;
2905 }
2906 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002907 if (isCommIntrinsic) {
2908 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2909 // operands are the commutative operands, and there might be more operands
2910 // after those.
2911 assert(NC >= 3 &&
2912 "Commutative intrinsic should have at least 3 childrean!");
2913 std::vector<std::vector<TreePatternNode*> > Variants;
2914 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2915 Variants.push_back(ChildVariants[2]);
2916 Variants.push_back(ChildVariants[1]);
2917 for (unsigned i = 3; i != NC; ++i)
2918 Variants.push_back(ChildVariants[i]);
2919 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2920 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002921 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002922 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002923 }
2924}
2925
2926
2927// GenerateVariants - Generate variants. For example, commutative patterns can
2928// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002929void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002930 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002931
2932 // Loop over all of the patterns we've collected, checking to see if we can
2933 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002934 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002935 // the .td file having to contain tons of variants of instructions.
2936 //
2937 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2938 // intentionally do not reconsider these. Any variants of added patterns have
2939 // already been added.
2940 //
2941 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002942 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002943 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002944 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002945 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002946 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002947 DEBUG(errs() << "\n");
Scott Michel327d0652008-03-05 17:49:05 +00002948 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002949
2950 assert(!Variants.empty() && "Must create at least original variant!");
2951 Variants.erase(Variants.begin()); // Remove the original pattern.
2952
2953 if (Variants.empty()) // No variants for this pattern.
2954 continue;
2955
Chris Lattner569f1212009-08-23 04:44:11 +00002956 DEBUG(errs() << "FOUND VARIANTS OF: ";
2957 PatternsToMatch[i].getSrcPattern()->dump();
2958 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002959
2960 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2961 TreePatternNode *Variant = Variants[v];
2962
Chris Lattner569f1212009-08-23 04:44:11 +00002963 DEBUG(errs() << " VAR#" << v << ": ";
2964 Variant->dump();
2965 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002966
2967 // Scan to see if an instruction or explicit pattern already matches this.
2968 bool AlreadyExists = false;
2969 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00002970 // Skip if the top level predicates do not match.
2971 if (PatternsToMatch[i].getPredicates() !=
2972 PatternsToMatch[p].getPredicates())
2973 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00002974 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002975 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00002976 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002977 AlreadyExists = true;
2978 break;
2979 }
2980 }
2981 // If we already have it, ignore the variant.
2982 if (AlreadyExists) continue;
2983
2984 // Otherwise, add it to the list of patterns we have.
2985 PatternsToMatch.
2986 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2987 Variant, PatternsToMatch[i].getDstPattern(),
2988 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002989 PatternsToMatch[i].getAddedComplexity(),
2990 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002991 }
2992
Chris Lattner569f1212009-08-23 04:44:11 +00002993 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002994 }
2995}
2996