blob: da439ba7134c442ad2c2b8fc458bf458ade6ae70 [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
397/// whose element is VT.
398bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
399 TreePattern &TP) {
400 TypeSet InputSet(*this);
401 bool MadeChange = false;
402
403 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000404 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000405 MadeChange = FillWithPossibleTypes(TP, isVector, "vector");
Chris Lattner2cacec52010-03-15 06:00:16 +0000406
407 // Filter out all the non-vector types and types which don't have the right
408 // element type.
409 for (unsigned i = 0; i != TypeVec.size(); ++i)
410 if (!isVector(TypeVec[i]) ||
411 EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
412 TypeVec.erase(TypeVec.begin()+i--);
413 MadeChange = true;
414 }
415
416 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
417 TP.error("Type inference contradiction found, forcing '" +
418 InputSet.getName() + "' to have a vector element");
419 return MadeChange;
420}
421
422//===----------------------------------------------------------------------===//
423// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000424
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000425bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
426 return LHS->getID() < RHS->getID();
427}
Scott Michel327d0652008-03-05 17:49:05 +0000428
429/// Dependent variable map for CodeGenDAGPattern variant generation
430typedef std::map<std::string, int> DepVarMap;
431
432/// Const iterator shorthand for DepVarMap
433typedef DepVarMap::const_iterator DepVarMap_citer;
434
435namespace {
436void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
437 if (N->isLeaf()) {
438 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
439 DepMap[N->getName()]++;
440 }
441 } else {
442 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
443 FindDepVarsOf(N->getChild(i), DepMap);
444 }
445}
446
447//! Find dependent variables within child patterns
448/*!
449 */
450void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
451 DepVarMap depcounts;
452 FindDepVarsOf(N, depcounts);
453 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
454 if (i->second > 1) { // std::pair<std::string, int>
455 DepVars.insert(i->first);
456 }
457 }
458}
459
460//! Dump the dependent variable set:
461void DumpDepVars(MultipleUseVarSet &DepVars) {
462 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000463 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000464 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000465 DEBUG(errs() << "[ ");
Scott Michel327d0652008-03-05 17:49:05 +0000466 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
467 i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000468 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000469 }
Chris Lattner569f1212009-08-23 04:44:11 +0000470 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000471 }
472}
473}
474
Chris Lattner6cefb772008-01-05 22:25:12 +0000475//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000476// PatternToMatch implementation
477//
478
479/// getPredicateCheck - Return a single string containing all of this
480/// pattern's predicates concatenated with "&&" operators.
481///
482std::string PatternToMatch::getPredicateCheck() const {
483 std::string PredicateCheck;
484 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
485 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
486 Record *Def = Pred->getDef();
487 if (!Def->isSubClassOf("Predicate")) {
488#ifndef NDEBUG
489 Def->dump();
490#endif
491 assert(0 && "Unknown predicate type!");
492 }
493 if (!PredicateCheck.empty())
494 PredicateCheck += " && ";
495 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
496 }
497 }
498
499 return PredicateCheck;
500}
501
502//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000503// SDTypeConstraint implementation
504//
505
506SDTypeConstraint::SDTypeConstraint(Record *R) {
507 OperandNo = R->getValueAsInt("OperandNum");
508
509 if (R->isSubClassOf("SDTCisVT")) {
510 ConstraintType = SDTCisVT;
511 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
512 } else if (R->isSubClassOf("SDTCisPtrTy")) {
513 ConstraintType = SDTCisPtrTy;
514 } else if (R->isSubClassOf("SDTCisInt")) {
515 ConstraintType = SDTCisInt;
516 } else if (R->isSubClassOf("SDTCisFP")) {
517 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000518 } else if (R->isSubClassOf("SDTCisVec")) {
519 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000520 } else if (R->isSubClassOf("SDTCisSameAs")) {
521 ConstraintType = SDTCisSameAs;
522 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
523 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
524 ConstraintType = SDTCisVTSmallerThanOp;
525 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
526 R->getValueAsInt("OtherOperandNum");
527 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
528 ConstraintType = SDTCisOpSmallerThanOp;
529 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
530 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000531 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
532 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000533 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000534 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000535 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000536 exit(1);
537 }
538}
539
540/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000541/// N, and the result number in ResNo.
542static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
543 const SDNodeInfo &NodeInfo,
544 unsigned &ResNo) {
545 unsigned NumResults = NodeInfo.getNumResults();
546 if (OpNo < NumResults) {
547 ResNo = OpNo;
548 return N;
549 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000550
Chris Lattner2e68a022010-03-19 21:56:21 +0000551 OpNo -= NumResults;
552
553 if (OpNo >= N->getNumChildren()) {
554 errs() << "Invalid operand number in type constraint "
555 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000556 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000557 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000558 exit(1);
559 }
560
Chris Lattner2e68a022010-03-19 21:56:21 +0000561 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000562}
563
564/// ApplyTypeConstraint - Given a node in a pattern, apply this type
565/// constraint to the nodes operands. This returns true if it makes a
566/// change, false otherwise. If a type contradiction is found, throw an
567/// exception.
568bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
569 const SDNodeInfo &NodeInfo,
570 TreePattern &TP) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000571 // Check that the number of operands is sane. Negative operands -> varargs.
572 if (NodeInfo.getNumOperands() >= 0) {
573 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
574 TP.error(N->getOperator()->getName() + " node requires exactly " +
575 itostr(NodeInfo.getNumOperands()) + " operands!");
576 }
577
Chris Lattner2e68a022010-03-19 21:56:21 +0000578 unsigned ResNo = 0; // The result number being referenced.
579 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000580
581 switch (ConstraintType) {
582 default: assert(0 && "Unknown constraint type!");
583 case SDTCisVT:
584 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000585 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000586 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000587 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000588 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000589 case SDTCisInt:
590 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000591 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000592 case SDTCisFP:
593 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000594 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000595 case SDTCisVec:
596 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000597 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000598 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000599 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000600 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000601 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000602 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
603 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000604 }
605 case SDTCisVTSmallerThanOp: {
606 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
607 // have an integer type that is smaller than the VT.
608 if (!NodeToApply->isLeaf() ||
609 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
610 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
611 ->isSubClassOf("ValueType"))
612 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000613 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000614 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Duncan Sands83ec4b62008-06-06 12:08:01 +0000615 if (!isInteger(VT))
Chris Lattner6cefb772008-01-05 22:25:12 +0000616 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
617
Chris Lattner2e68a022010-03-19 21:56:21 +0000618 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000619 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000620 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
621 OResNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000622
623 // It must be integer.
Chris Lattnerd7349192010-03-19 21:37:09 +0000624 bool MadeChange = OtherNode->getExtType(OResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000625
626 // This doesn't try to enforce any information on the OtherNode, it just
627 // validates it when information is determined.
Chris Lattnerd7349192010-03-19 21:37:09 +0000628 if (OtherNode->hasTypeSet(OResNo) && OtherNode->getType(OResNo) <= VT)
629 OtherNode->UpdateNodeType(OResNo, MVT::Other, TP); // Throw an error.
Bill Wendling7529ece2009-12-25 13:35:40 +0000630 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +0000631 }
632 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000633 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000634 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000635 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
636 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000637 return NodeToApply->getExtType(ResNo).
638 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000639 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000640 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000641 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000642 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000643 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
644 VResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000645 if (VecOperand->hasTypeSet(VResNo)) {
646 if (!isVector(VecOperand->getType(VResNo)))
Nate Begemanb5af3342008-02-09 01:37:05 +0000647 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Chris Lattnerd7349192010-03-19 21:37:09 +0000648 EVT IVT = VecOperand->getType(VResNo);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000649 IVT = IVT.getVectorElementType();
Chris Lattnerd7349192010-03-19 21:37:09 +0000650 return NodeToApply->UpdateNodeType(ResNo, IVT.getSimpleVT().SimpleTy, TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000651 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000652
Chris Lattnerd7349192010-03-19 21:37:09 +0000653 if (NodeToApply->hasTypeSet(ResNo) &&
654 VecOperand->getExtType(VResNo).hasVectorTypes()){
Chris Lattner2cacec52010-03-15 06:00:16 +0000655 // Filter vector types out of VecOperand that don't have the right element
656 // type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000657 return VecOperand->getExtType(VResNo).
658 EnforceVectorEltTypeIs(NodeToApply->getType(ResNo), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000659 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000660 return false;
661 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000662 }
663 return false;
664}
665
666//===----------------------------------------------------------------------===//
667// SDNodeInfo implementation
668//
669SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
670 EnumName = R->getValueAsString("Opcode");
671 SDClassName = R->getValueAsString("SDClass");
672 Record *TypeProfile = R->getValueAsDef("TypeProfile");
673 NumResults = TypeProfile->getValueAsInt("NumResults");
674 NumOperands = TypeProfile->getValueAsInt("NumOperands");
675
676 // Parse the properties.
677 Properties = 0;
678 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
679 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
680 if (PropList[i]->getName() == "SDNPCommutative") {
681 Properties |= 1 << SDNPCommutative;
682 } else if (PropList[i]->getName() == "SDNPAssociative") {
683 Properties |= 1 << SDNPAssociative;
684 } else if (PropList[i]->getName() == "SDNPHasChain") {
685 Properties |= 1 << SDNPHasChain;
686 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000687 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000688 } else if (PropList[i]->getName() == "SDNPInFlag") {
689 Properties |= 1 << SDNPInFlag;
690 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
691 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000692 } else if (PropList[i]->getName() == "SDNPMayStore") {
693 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000694 } else if (PropList[i]->getName() == "SDNPMayLoad") {
695 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000696 } else if (PropList[i]->getName() == "SDNPSideEffect") {
697 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000698 } else if (PropList[i]->getName() == "SDNPMemOperand") {
699 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000700 } else if (PropList[i]->getName() == "SDNPVariadic") {
701 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000702 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000703 errs() << "Unknown SD Node property '" << PropList[i]->getName()
704 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000705 exit(1);
706 }
707 }
708
709
710 // Parse the type constraints.
711 std::vector<Record*> ConstraintList =
712 TypeProfile->getValueAsListOfDefs("Constraints");
713 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
714}
715
Chris Lattner22579812010-02-28 00:22:30 +0000716/// getKnownType - If the type constraints on this node imply a fixed type
717/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000718/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
719MVT::SimpleValueType SDNodeInfo::getKnownType() const {
Chris Lattner22579812010-02-28 00:22:30 +0000720 unsigned NumResults = getNumResults();
721 assert(NumResults <= 1 &&
722 "We only work with nodes with zero or one result so far!");
723
724 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
725 // Make sure that this applies to the correct node result.
726 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
727 continue;
728
729 switch (TypeConstraints[i].ConstraintType) {
730 default: break;
731 case SDTypeConstraint::SDTCisVT:
732 return TypeConstraints[i].x.SDTCisVT_Info.VT;
733 case SDTypeConstraint::SDTCisPtrTy:
734 return MVT::iPTR;
735 }
736 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000737 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000738}
739
Chris Lattner6cefb772008-01-05 22:25:12 +0000740//===----------------------------------------------------------------------===//
741// TreePatternNode implementation
742//
743
744TreePatternNode::~TreePatternNode() {
745#if 0 // FIXME: implement refcounted tree nodes!
746 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
747 delete getChild(i);
748#endif
749}
750
Chris Lattnerd7349192010-03-19 21:37:09 +0000751static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
752 if (Operator->getName() == "set" ||
753 Operator->getName() == "implicit" ||
754 Operator->getName() == "parallel")
755 return 0; // All return nothing.
756
Chris Lattner93dc92e2010-03-22 20:56:36 +0000757 if (Operator->isSubClassOf("Intrinsic"))
758 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Chris Lattner6cefb772008-01-05 22:25:12 +0000759
Chris Lattnerd7349192010-03-19 21:37:09 +0000760 if (Operator->isSubClassOf("SDNode"))
761 return CDP.getSDNodeInfo(Operator).getNumResults();
762
763 if (Operator->isSubClassOf("PatFrag")) {
764 // If we've already parsed this pattern fragment, get it. Otherwise, handle
765 // the forward reference case where one pattern fragment references another
766 // before it is processed.
767 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
768 return PFRec->getOnlyTree()->getNumTypes();
769
770 // Get the result tree.
771 DagInit *Tree = Operator->getValueAsDag("Fragment");
772 Record *Op = 0;
773 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
774 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
775 assert(Op && "Invalid Fragment");
776 return GetNumNodeResults(Op, CDP);
777 }
778
779 if (Operator->isSubClassOf("Instruction")) {
780 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
781
782 // FIXME: Handle implicit defs right.
783 if (InstInfo.NumDefs != 0)
784 return 1; // FIXME: Handle inst results right!
785
786 if (!InstInfo.ImplicitDefs.empty()) {
787 // Add on one implicit def if it has a resolvable type.
788 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
789 assert(FirstImplicitDef->isSubClassOf("Register"));
790 const std::vector<MVT::SimpleValueType> &RegVTs =
791 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
792 if (RegVTs.size() == 1)
793 return 1;
794 }
795 return 0;
796 }
797
798 if (Operator->isSubClassOf("SDNodeXForm"))
799 return 1; // FIXME: Generalize SDNodeXForm
800
801 Operator->dump();
802 errs() << "Unhandled node in GetNumNodeResults\n";
803 exit(1);
804}
805
806void TreePatternNode::print(raw_ostream &OS) const {
807 if (isLeaf())
808 OS << *getLeafValue();
809 else
810 OS << '(' << getOperator()->getName();
811
812 for (unsigned i = 0, e = Types.size(); i != e; ++i)
813 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000814
815 if (!isLeaf()) {
816 if (getNumChildren() != 0) {
817 OS << " ";
818 getChild(0)->print(OS);
819 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
820 OS << ", ";
821 getChild(i)->print(OS);
822 }
823 }
824 OS << ")";
825 }
826
Dan Gohman0540e172008-10-15 06:17:21 +0000827 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
828 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000829 if (TransformFn)
830 OS << "<<X:" << TransformFn->getName() << ">>";
831 if (!getName().empty())
832 OS << ":$" << getName();
833
834}
835void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000836 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000837}
838
Scott Michel327d0652008-03-05 17:49:05 +0000839/// isIsomorphicTo - Return true if this node is recursively
840/// isomorphic to the specified node. For this comparison, the node's
841/// entire state is considered. The assigned name is ignored, since
842/// nodes with differing names are considered isomorphic. However, if
843/// the assigned name is present in the dependent variable set, then
844/// the assigned name is considered significant and the node is
845/// isomorphic if the names match.
846bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
847 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000848 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +0000849 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000850 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000851 getTransformFn() != N->getTransformFn())
852 return false;
853
854 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000855 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
856 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000857 return ((DI->getDef() == NDI->getDef())
858 && (DepVars.find(getName()) == DepVars.end()
859 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000860 }
861 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000862 return getLeafValue() == N->getLeafValue();
863 }
864
865 if (N->getOperator() != getOperator() ||
866 N->getNumChildren() != getNumChildren()) return false;
867 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000868 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000869 return false;
870 return true;
871}
872
873/// clone - Make a copy of this tree and all of its children.
874///
875TreePatternNode *TreePatternNode::clone() const {
876 TreePatternNode *New;
877 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +0000878 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000879 } else {
880 std::vector<TreePatternNode*> CChildren;
881 CChildren.reserve(Children.size());
882 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
883 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +0000884 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000885 }
886 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +0000887 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +0000888 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000889 New->setTransformFn(getTransformFn());
890 return New;
891}
892
Chris Lattner47661322010-02-14 22:22:58 +0000893/// RemoveAllTypes - Recursively strip all the types of this tree.
894void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +0000895 for (unsigned i = 0, e = Types.size(); i != e; ++i)
896 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +0000897 if (isLeaf()) return;
898 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
899 getChild(i)->RemoveAllTypes();
900}
901
902
Chris Lattner6cefb772008-01-05 22:25:12 +0000903/// SubstituteFormalArguments - Replace the formal arguments in this tree
904/// with actual values specified by ArgMap.
905void TreePatternNode::
906SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
907 if (isLeaf()) return;
908
909 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
910 TreePatternNode *Child = getChild(i);
911 if (Child->isLeaf()) {
912 Init *Val = Child->getLeafValue();
913 if (dynamic_cast<DefInit*>(Val) &&
914 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
915 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000916 TreePatternNode *NewChild = ArgMap[Child->getName()];
917 assert(NewChild && "Couldn't find formal argument!");
918 assert((Child->getPredicateFns().empty() ||
919 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
920 "Non-empty child predicate clobbered!");
921 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000922 }
923 } else {
924 getChild(i)->SubstituteFormalArguments(ArgMap);
925 }
926 }
927}
928
929
930/// InlinePatternFragments - If this pattern refers to any pattern
931/// fragments, inline them into place, giving us a pattern without any
932/// PatFrag references.
933TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
934 if (isLeaf()) return this; // nothing to do.
935 Record *Op = getOperator();
936
937 if (!Op->isSubClassOf("PatFrag")) {
938 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000939 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
940 TreePatternNode *Child = getChild(i);
941 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
942
943 assert((Child->getPredicateFns().empty() ||
944 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
945 "Non-empty child predicate clobbered!");
946
947 setChild(i, NewChild);
948 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000949 return this;
950 }
951
952 // Otherwise, we found a reference to a fragment. First, look up its
953 // TreePattern record.
954 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
955
956 // Verify that we are passing the right number of operands.
957 if (Frag->getNumArgs() != Children.size())
958 TP.error("'" + Op->getName() + "' fragment requires " +
959 utostr(Frag->getNumArgs()) + " operands!");
960
961 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
962
Dan Gohman0540e172008-10-15 06:17:21 +0000963 std::string Code = Op->getValueAsCode("Predicate");
964 if (!Code.empty())
965 FragTree->addPredicateFn("Predicate_"+Op->getName());
966
Chris Lattner6cefb772008-01-05 22:25:12 +0000967 // Resolve formal arguments to their actual value.
968 if (Frag->getNumArgs()) {
969 // Compute the map of formal to actual arguments.
970 std::map<std::string, TreePatternNode*> ArgMap;
971 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
972 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
973
974 FragTree->SubstituteFormalArguments(ArgMap);
975 }
976
977 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +0000978 for (unsigned i = 0, e = Types.size(); i != e; ++i)
979 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000980
981 // Transfer in the old predicates.
982 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
983 FragTree->addPredicateFn(getPredicateFns()[i]);
984
Chris Lattner6cefb772008-01-05 22:25:12 +0000985 // Get a new copy of this fragment to stitch into here.
986 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000987
988 // The fragment we inlined could have recursive inlining that is needed. See
989 // if there are any pattern fragments in it and inline them as needed.
990 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000991}
992
993/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000994/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +0000995/// references from the register file information, for example.
996///
Chris Lattnerd7349192010-03-19 21:37:09 +0000997static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
998 bool NotRegisters, TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000999 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00001000 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001001 assert(ResNo == 0 && "Regclass ref only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001002 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001003 return EEVT::TypeSet(); // Unknown.
1004 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1005 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001006 }
1007
1008 if (R->isSubClassOf("PatFrag")) {
1009 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001010 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001011 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001012 }
1013
1014 if (R->isSubClassOf("Register")) {
1015 assert(ResNo == 0 && "Registers only produce one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001016 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001017 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001018 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001019 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001020 }
1021
1022 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1023 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001024 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001025 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001026 }
1027
1028 if (R->isSubClassOf("ComplexPattern")) {
1029 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001030 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001031 return EEVT::TypeSet(); // Unknown.
1032 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1033 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001034 }
1035 if (R->isSubClassOf("PointerLikeRegClass")) {
1036 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001037 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001038 }
1039
1040 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1041 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001042 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001043 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001044 }
1045
1046 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001047 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001048}
1049
Chris Lattnere67bde52008-01-06 05:36:50 +00001050
1051/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1052/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1053const CodeGenIntrinsic *TreePatternNode::
1054getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1055 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1056 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1057 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1058 return 0;
1059
1060 unsigned IID =
1061 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1062 return &CDP.getIntrinsicInfo(IID);
1063}
1064
Chris Lattner47661322010-02-14 22:22:58 +00001065/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1066/// return the ComplexPattern information, otherwise return null.
1067const ComplexPattern *
1068TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1069 if (!isLeaf()) return 0;
1070
1071 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1072 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1073 return &CGP.getComplexPattern(DI->getDef());
1074 return 0;
1075}
1076
1077/// NodeHasProperty - Return true if this node has the specified property.
1078bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001079 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001080 if (isLeaf()) {
1081 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1082 return CP->hasProperty(Property);
1083 return false;
1084 }
1085
1086 Record *Operator = getOperator();
1087 if (!Operator->isSubClassOf("SDNode")) return false;
1088
1089 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1090}
1091
1092
1093
1094
1095/// TreeHasProperty - Return true if any node in this tree has the specified
1096/// property.
1097bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001098 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001099 if (NodeHasProperty(Property, CGP))
1100 return true;
1101 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1102 if (getChild(i)->TreeHasProperty(Property, CGP))
1103 return true;
1104 return false;
1105}
1106
Evan Cheng6bd95672008-06-16 20:29:38 +00001107/// isCommutativeIntrinsic - Return true if the node corresponds to a
1108/// commutative intrinsic.
1109bool
1110TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1111 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1112 return Int->isCommutative;
1113 return false;
1114}
1115
Chris Lattnere67bde52008-01-06 05:36:50 +00001116
Bob Wilson6c01ca92009-01-05 17:23:09 +00001117/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001118/// this node and its children in the tree. This returns true if it makes a
1119/// change, false otherwise. If a type contradiction is found, throw an
1120/// exception.
1121bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001122 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001123 if (isLeaf()) {
1124 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1125 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001126 bool MadeChange = false;
1127 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1128 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1129 NotRegisters, TP), TP);
1130 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001131 }
1132
1133 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001134 assert(Types.size() == 1 && "Invalid IntInit");
Chris Lattner6cefb772008-01-05 22:25:12 +00001135
Chris Lattnerd7349192010-03-19 21:37:09 +00001136 // Int inits are always integers. :)
1137 bool MadeChange = Types[0].EnforceInteger(TP);
1138
1139 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001140 return MadeChange;
1141
Chris Lattnerd7349192010-03-19 21:37:09 +00001142 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001143 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1144 return MadeChange;
1145
1146 unsigned Size = EVT(VT).getSizeInBits();
1147 // Make sure that the value is representable for this type.
1148 if (Size >= 32) return MadeChange;
1149
1150 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1151 if (Val == II->getValue()) return MadeChange;
1152
1153 // If sign-extended doesn't fit, does it fit as unsigned?
1154 unsigned ValueMask;
1155 unsigned UnsignedVal;
1156 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1157 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001158
Chris Lattner2cacec52010-03-15 06:00:16 +00001159 if ((ValueMask & UnsignedVal) == UnsignedVal)
1160 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001161
Chris Lattner2cacec52010-03-15 06:00:16 +00001162 TP.error("Integer value '" + itostr(II->getValue())+
Chris Lattnerd7349192010-03-19 21:37:09 +00001163 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001164 return MadeChange;
1165 }
1166 return false;
1167 }
1168
1169 // special handling for set, which isn't really an SDNode.
1170 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001171 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1172 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001173 unsigned NC = getNumChildren();
Chris Lattnerd7349192010-03-19 21:37:09 +00001174
1175 TreePatternNode *SetVal = getChild(NC-1);
1176 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1177
Chris Lattner6cefb772008-01-05 22:25:12 +00001178 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001179 TreePatternNode *Child = getChild(i);
1180 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001181
1182 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001183 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1184 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001185 }
1186 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001187 }
1188
1189 if (getOperator()->getName() == "implicit" ||
1190 getOperator()->getName() == "parallel") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001191 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1192
Chris Lattner6cefb772008-01-05 22:25:12 +00001193 bool MadeChange = false;
1194 for (unsigned i = 0; i < getNumChildren(); ++i)
1195 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001196 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001197 }
1198
1199 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001200 bool MadeChange = false;
1201 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1202 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner2cacec52010-03-15 06:00:16 +00001203
Chris Lattnerd7349192010-03-19 21:37:09 +00001204 assert(getChild(0)->getNumTypes() == 1 &&
1205 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1206
Chris Lattner2cacec52010-03-15 06:00:16 +00001207 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1208 // what type it gets, so if it didn't get a concrete type just give it the
1209 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001210 if (!getChild(1)->hasTypeSet(0) &&
1211 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1212 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1213 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001214 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001215 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001216 }
1217
1218 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001219 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001220
Chris Lattner6cefb772008-01-05 22:25:12 +00001221 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001222 unsigned NumRetVTs = Int->IS.RetVTs.size();
1223 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Chris Lattnerd7349192010-03-19 21:37:09 +00001224
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001225 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001226 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001227
Chris Lattnerd7349192010-03-19 21:37:09 +00001228 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001229 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001230 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001231 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001232
1233 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001234 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001235
Chris Lattnerd7349192010-03-19 21:37:09 +00001236 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1237 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1238
1239 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1240 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1241 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001242 }
1243 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001244 }
1245
1246 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001247 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1248
1249 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1250 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1251 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001252 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001253 }
1254
1255 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001256 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattnerd7349192010-03-19 21:37:09 +00001257 unsigned ResNo = 0;
Daniel Dunbar65f35d52010-03-19 03:18:20 +00001258 assert(Inst.getNumResults() <= 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001259 "FIXME: Only supports zero or one result instrs!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001260
1261 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001262 CDP.getTargetInfo().getInstruction(getOperator());
Chris Lattner6c6ba362010-03-18 23:15:10 +00001263
1264 EEVT::TypeSet ResultType;
1265
Chris Lattner6cefb772008-01-05 22:25:12 +00001266 // Apply the result type to the node
Chris Lattner6c6ba362010-03-18 23:15:10 +00001267 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
Chris Lattner6cefb772008-01-05 22:25:12 +00001268 Record *ResultNode = Inst.getResult(0);
1269
Chris Lattnera938ac62009-07-29 20:43:05 +00001270 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00001271 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001272 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001273 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001274 } else {
1275 assert(ResultNode->isSubClassOf("RegisterClass") &&
1276 "Operands should be register classes!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001277 const CodeGenRegisterClass &RC =
1278 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001279 ResultType = RC.getValueTypes();
Chris Lattner6cefb772008-01-05 22:25:12 +00001280 }
Chris Lattner6c6ba362010-03-18 23:15:10 +00001281 } else if (!InstInfo.ImplicitDefs.empty()) {
1282 // If the instruction has implicit defs, the first one defines the result
1283 // type.
Chris Lattner6c6ba362010-03-18 23:15:10 +00001284 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
Chris Lattner92879532010-03-18 23:57:40 +00001285 assert(FirstImplicitDef->isSubClassOf("Register"));
Chris Lattner6c6ba362010-03-18 23:15:10 +00001286 const std::vector<MVT::SimpleValueType> &RegVTs =
1287 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
Chris Lattnerd7349192010-03-19 21:37:09 +00001288 if (RegVTs.size() == 1) // FIXME: Generalize.
Chris Lattner6c6ba362010-03-18 23:15:10 +00001289 ResultType = EEVT::TypeSet(RegVTs);
1290 } else {
1291 // Otherwise, the instruction produces no value result.
Chris Lattner6cefb772008-01-05 22:25:12 +00001292 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001293
Chris Lattnerd7349192010-03-19 21:37:09 +00001294 bool MadeChange = false;
1295
1296 if (!ResultType.isCompletelyUnknown())
1297 MadeChange |= UpdateNodeType(ResNo, ResultType, TP);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001298
Chris Lattner2cacec52010-03-15 06:00:16 +00001299 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1300 // be the same.
1301 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001302 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1303 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1304 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001305 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001306
1307 unsigned ChildNo = 0;
1308 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1309 Record *OperandNode = Inst.getOperand(i);
1310
1311 // If the instruction expects a predicate or optional def operand, we
1312 // codegen this by setting the operand to it's default value if it has a
1313 // non-empty DefaultOps field.
1314 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1315 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1316 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1317 continue;
1318
1319 // Verify that we didn't run out of provided operands.
1320 if (ChildNo >= getNumChildren())
1321 TP.error("Instruction '" + getOperator()->getName() +
1322 "' expects more operands than were provided.");
1323
Owen Anderson825b72b2009-08-11 20:47:22 +00001324 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001325 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd7349192010-03-19 21:37:09 +00001326 assert(Child->getNumTypes() == 1 && "Unknown case?");
1327
Chris Lattner6cefb772008-01-05 22:25:12 +00001328 if (OperandNode->isSubClassOf("RegisterClass")) {
1329 const CodeGenRegisterClass &RC =
1330 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00001331 MadeChange |= Child->UpdateNodeType(0, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001332 } else if (OperandNode->isSubClassOf("Operand")) {
1333 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattnerd7349192010-03-19 21:37:09 +00001334 MadeChange |= Child->UpdateNodeType(0, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001335 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001336 MadeChange |= Child->UpdateNodeType(0, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001337 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001338 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001339 } else {
1340 assert(0 && "Unknown operand type!");
1341 abort();
1342 }
1343 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1344 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001345
Christopher Lamb02f69372008-03-10 04:16:09 +00001346 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001347 TP.error("Instruction '" + getOperator()->getName() +
1348 "' was provided too many operands!");
1349
1350 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001351 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001352
1353 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1354
1355 // Node transforms always take one operand.
1356 if (getNumChildren() != 1)
1357 TP.error("Node transform '" + getOperator()->getName() +
1358 "' requires one operand!");
1359
Chris Lattner2cacec52010-03-15 06:00:16 +00001360 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1361
1362
Chris Lattner6eb30122010-02-23 05:51:07 +00001363 // If either the output or input of the xform does not have exact
1364 // type info. We assume they must be the same. Otherwise, it is perfectly
1365 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001366#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001367 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001368 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1369 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001370 return MadeChange;
1371 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001372#endif
1373 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001374}
1375
1376/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1377/// RHS of a commutative operation, not the on LHS.
1378static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1379 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1380 return true;
1381 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1382 return true;
1383 return false;
1384}
1385
1386
1387/// canPatternMatch - If it is impossible for this pattern to match on this
1388/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001389/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001390/// that can never possibly work), and to prevent the pattern permuter from
1391/// generating stuff that is useless.
1392bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001393 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001394 if (isLeaf()) return true;
1395
1396 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1397 if (!getChild(i)->canPatternMatch(Reason, CDP))
1398 return false;
1399
1400 // If this is an intrinsic, handle cases that would make it not match. For
1401 // example, if an operand is required to be an immediate.
1402 if (getOperator()->isSubClassOf("Intrinsic")) {
1403 // TODO:
1404 return true;
1405 }
1406
1407 // If this node is a commutative operator, check that the LHS isn't an
1408 // immediate.
1409 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001410 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1411 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001412 // Scan all of the operands of the node and make sure that only the last one
1413 // is a constant node, unless the RHS also is.
1414 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001415 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1416 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001417 if (OnlyOnRHSOfCommutative(getChild(i))) {
1418 Reason="Immediate value must be on the RHS of commutative operators!";
1419 return false;
1420 }
1421 }
1422 }
1423
1424 return true;
1425}
1426
1427//===----------------------------------------------------------------------===//
1428// TreePattern implementation
1429//
1430
1431TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001432 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001433 isInputPattern = isInput;
1434 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1435 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001436}
1437
1438TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001439 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001440 isInputPattern = isInput;
1441 Trees.push_back(ParseTreePattern(Pat));
1442}
1443
1444TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001445 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001446 isInputPattern = isInput;
1447 Trees.push_back(Pat);
1448}
1449
Chris Lattner6cefb772008-01-05 22:25:12 +00001450void TreePattern::error(const std::string &Msg) const {
1451 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001452 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001453}
1454
Chris Lattner2cacec52010-03-15 06:00:16 +00001455void TreePattern::ComputeNamedNodes() {
1456 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1457 ComputeNamedNodes(Trees[i]);
1458}
1459
1460void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1461 if (!N->getName().empty())
1462 NamedNodes[N->getName()].push_back(N);
1463
1464 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1465 ComputeNamedNodes(N->getChild(i));
1466}
1467
Chris Lattnerd7349192010-03-19 21:37:09 +00001468
Chris Lattner6cefb772008-01-05 22:25:12 +00001469TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1470 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1471 if (!OpDef) error("Pattern has unexpected operator type!");
1472 Record *Operator = OpDef->getDef();
1473
1474 if (Operator->isSubClassOf("ValueType")) {
1475 // If the operator is a ValueType, then this must be "type cast" of a leaf
1476 // node.
1477 if (Dag->getNumArgs() != 1)
1478 error("Type cast only takes one operand!");
1479
1480 Init *Arg = Dag->getArg(0);
1481 TreePatternNode *New;
1482 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1483 Record *R = DI->getDef();
1484 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001485 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001486 std::vector<std::pair<Init*, std::string> >()));
1487 return ParseTreePattern(Dag);
1488 }
Chris Lattner43e47542010-03-08 18:36:19 +00001489
1490 // Input argument?
1491 if (R->getName() == "node") {
1492 if (Dag->getArgName(0).empty())
1493 error("'node' argument requires a name to match with operand list");
1494 Args.push_back(Dag->getArgName(0));
1495 }
1496
Chris Lattnerd7349192010-03-19 21:37:09 +00001497 New = new TreePatternNode(DI, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001498 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1499 New = ParseTreePattern(DI);
1500 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001501 New = new TreePatternNode(II, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001502 if (!Dag->getArgName(0).empty())
1503 error("Constant int argument should not have a name!");
1504 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1505 // Turn this into an IntInit.
1506 Init *II = BI->convertInitializerTo(new IntRecTy());
1507 if (II == 0 || !dynamic_cast<IntInit*>(II))
1508 error("Bits value must be constants!");
1509
Chris Lattnerd7349192010-03-19 21:37:09 +00001510 New = new TreePatternNode(dynamic_cast<IntInit*>(II), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001511 if (!Dag->getArgName(0).empty())
1512 error("Constant int argument should not have a name!");
1513 } else {
1514 Arg->dump();
1515 error("Unknown leaf value for tree pattern!");
1516 return 0;
1517 }
1518
1519 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001520 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1521 New->UpdateNodeType(0, getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001522 if (New->getNumChildren() == 0)
1523 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001524 return New;
1525 }
1526
1527 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001528 if (!Operator->isSubClassOf("PatFrag") &&
1529 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001530 !Operator->isSubClassOf("Instruction") &&
1531 !Operator->isSubClassOf("SDNodeXForm") &&
1532 !Operator->isSubClassOf("Intrinsic") &&
1533 Operator->getName() != "set" &&
1534 Operator->getName() != "implicit" &&
1535 Operator->getName() != "parallel")
1536 error("Unrecognized node '" + Operator->getName() + "'!");
1537
1538 // Check to see if this is something that is illegal in an input pattern.
1539 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1540 Operator->isSubClassOf("SDNodeXForm")))
1541 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1542
1543 std::vector<TreePatternNode*> Children;
1544
1545 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1546 Init *Arg = Dag->getArg(i);
1547 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1548 Children.push_back(ParseTreePattern(DI));
1549 if (Children.back()->getName().empty())
1550 Children.back()->setName(Dag->getArgName(i));
1551 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1552 Record *R = DefI->getDef();
1553 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1554 // TreePatternNode if its own.
1555 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001556 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001557 std::vector<std::pair<Init*, std::string> >()));
1558 --i; // Revisit this node...
1559 } else {
Chris Lattnerd7349192010-03-19 21:37:09 +00001560 TreePatternNode *Node = new TreePatternNode(DefI, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001561 Node->setName(Dag->getArgName(i));
1562 Children.push_back(Node);
1563
1564 // Input argument?
1565 if (R->getName() == "node") {
1566 if (Dag->getArgName(i).empty())
1567 error("'node' argument requires a name to match with operand list");
1568 Args.push_back(Dag->getArgName(i));
1569 }
1570 }
1571 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001572 TreePatternNode *Node = new TreePatternNode(II, 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001573 if (!Dag->getArgName(i).empty())
1574 error("Constant int argument should not have a name!");
1575 Children.push_back(Node);
1576 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1577 // Turn this into an IntInit.
1578 Init *II = BI->convertInitializerTo(new IntRecTy());
1579 if (II == 0 || !dynamic_cast<IntInit*>(II))
1580 error("Bits value must be constants!");
1581
Chris Lattnerd7349192010-03-19 21:37:09 +00001582 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II),1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001583 if (!Dag->getArgName(i).empty())
1584 error("Constant int argument should not have a name!");
1585 Children.push_back(Node);
1586 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001587 errs() << '"';
Chris Lattner6cefb772008-01-05 22:25:12 +00001588 Arg->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001589 errs() << "\": ";
Chris Lattner6cefb772008-01-05 22:25:12 +00001590 error("Unknown leaf value for tree pattern!");
1591 }
1592 }
1593
1594 // If the operator is an intrinsic, then this is just syntactic sugar for for
1595 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1596 // convert the intrinsic name to a number.
1597 if (Operator->isSubClassOf("Intrinsic")) {
1598 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1599 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1600
1601 // If this intrinsic returns void, it must have side-effects and thus a
1602 // chain.
Chris Lattner93dc92e2010-03-22 20:56:36 +00001603 if (Int.IS.RetVTs.empty()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001604 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1605 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1606 // Has side-effects, requires chain.
1607 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1608 } else {
1609 // Otherwise, no chain.
1610 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1611 }
1612
Chris Lattnerd7349192010-03-19 21:37:09 +00001613 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001614 Children.insert(Children.begin(), IIDNode);
1615 }
1616
Chris Lattnerd7349192010-03-19 21:37:09 +00001617 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1618 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Nate Begeman7cee8172009-03-19 05:21:56 +00001619 Result->setName(Dag->getName());
1620 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001621}
1622
1623/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001624/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001625/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001626bool TreePattern::
1627InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1628 if (NamedNodes.empty())
1629 ComputeNamedNodes();
1630
Chris Lattner6cefb772008-01-05 22:25:12 +00001631 bool MadeChange = true;
1632 while (MadeChange) {
1633 MadeChange = false;
1634 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1635 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner2cacec52010-03-15 06:00:16 +00001636
1637 // If there are constraints on our named nodes, apply them.
1638 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1639 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1640 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1641
1642 // If we have input named node types, propagate their types to the named
1643 // values here.
1644 if (InNamedTypes) {
1645 // FIXME: Should be error?
1646 assert(InNamedTypes->count(I->getKey()) &&
1647 "Named node in output pattern but not input pattern?");
1648
1649 const SmallVectorImpl<TreePatternNode*> &InNodes =
1650 InNamedTypes->find(I->getKey())->second;
1651
1652 // The input types should be fully resolved by now.
1653 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1654 // If this node is a register class, and it is the root of the pattern
1655 // then we're mapping something onto an input register. We allow
1656 // changing the type of the input register in this case. This allows
1657 // us to match things like:
1658 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1659 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1660 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1661 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1662 continue;
1663 }
1664
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001665 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001666 InNodes[0]->getNumTypes() == 1 &&
1667 "FIXME: cannot name multiple result nodes yet");
1668 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1669 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001670 }
1671 }
1672
1673 // If there are multiple nodes with the same name, they must all have the
1674 // same type.
1675 if (I->second.size() > 1) {
1676 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001677 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001678 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001679 "FIXME: cannot name multiple result nodes yet");
1680
1681 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1682 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001683 }
1684 }
1685 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001686 }
1687
1688 bool HasUnresolvedTypes = false;
1689 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1690 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1691 return !HasUnresolvedTypes;
1692}
1693
Daniel Dunbar1a551802009-07-03 00:10:29 +00001694void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001695 OS << getRecord()->getName();
1696 if (!Args.empty()) {
1697 OS << "(" << Args[0];
1698 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1699 OS << ", " << Args[i];
1700 OS << ")";
1701 }
1702 OS << ": ";
1703
1704 if (Trees.size() > 1)
1705 OS << "[\n";
1706 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1707 OS << "\t";
1708 Trees[i]->print(OS);
1709 OS << "\n";
1710 }
1711
1712 if (Trees.size() > 1)
1713 OS << "]\n";
1714}
1715
Daniel Dunbar1a551802009-07-03 00:10:29 +00001716void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001717
1718//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001719// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001720//
1721
Chris Lattnerfe718932008-01-06 01:10:31 +00001722CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001723 Intrinsics = LoadIntrinsics(Records, false);
1724 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001725 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001726 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001727 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001728 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001729 ParseDefaultOperands();
1730 ParseInstructions();
1731 ParsePatterns();
1732
1733 // Generate variants. For example, commutative patterns can match
1734 // multiple ways. Add them to PatternsToMatch as well.
1735 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001736
1737 // Infer instruction flags. For example, we can detect loads,
1738 // stores, and side effects in many cases by examining an
1739 // instruction's pattern.
1740 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001741}
1742
Chris Lattnerfe718932008-01-06 01:10:31 +00001743CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001744 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001745 E = PatternFragments.end(); I != E; ++I)
1746 delete I->second;
1747}
1748
1749
Chris Lattnerfe718932008-01-06 01:10:31 +00001750Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001751 Record *N = Records.getDef(Name);
1752 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001753 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001754 exit(1);
1755 }
1756 return N;
1757}
1758
1759// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001760void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001761 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1762 while (!Nodes.empty()) {
1763 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1764 Nodes.pop_back();
1765 }
1766
Jim Grosbachda4231f2009-03-26 16:17:51 +00001767 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001768 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1769 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1770 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1771}
1772
1773/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1774/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001775void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001776 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1777 while (!Xforms.empty()) {
1778 Record *XFormNode = Xforms.back();
1779 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1780 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001781 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001782
1783 Xforms.pop_back();
1784 }
1785}
1786
Chris Lattnerfe718932008-01-06 01:10:31 +00001787void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001788 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1789 while (!AMs.empty()) {
1790 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1791 AMs.pop_back();
1792 }
1793}
1794
1795
1796/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1797/// file, building up the PatternFragments map. After we've collected them all,
1798/// inline fragments together as necessary, so that there are no references left
1799/// inside a pattern fragment to a pattern fragment.
1800///
Chris Lattnerfe718932008-01-06 01:10:31 +00001801void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001802 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1803
Chris Lattnerdc32f982008-01-05 22:43:57 +00001804 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001805 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1806 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1807 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1808 PatternFragments[Fragments[i]] = P;
1809
Chris Lattnerdc32f982008-01-05 22:43:57 +00001810 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001811 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001812 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001813
Chris Lattnerdc32f982008-01-05 22:43:57 +00001814 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001815 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1816
1817 // Parse the operands list.
1818 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1819 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1820 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001821 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001822 if (!OpsOp ||
1823 (OpsOp->getDef()->getName() != "ops" &&
1824 OpsOp->getDef()->getName() != "outs" &&
1825 OpsOp->getDef()->getName() != "ins"))
1826 P->error("Operands list should start with '(ops ... '!");
1827
1828 // Copy over the arguments.
1829 Args.clear();
1830 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1831 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1832 static_cast<DefInit*>(OpsList->getArg(j))->
1833 getDef()->getName() != "node")
1834 P->error("Operands list should all be 'node' values.");
1835 if (OpsList->getArgName(j).empty())
1836 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001837 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001838 P->error("'" + OpsList->getArgName(j) +
1839 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001840 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001841 Args.push_back(OpsList->getArgName(j));
1842 }
1843
Chris Lattnerdc32f982008-01-05 22:43:57 +00001844 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001845 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001846 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001847
Chris Lattnerdc32f982008-01-05 22:43:57 +00001848 // If there is a code init for this fragment, keep track of the fact that
1849 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001850 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001851 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001852 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001853
1854 // If there is a node transformation corresponding to this, keep track of
1855 // it.
1856 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1857 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1858 P->getOnlyTree()->setTransformFn(Transform);
1859 }
1860
Chris Lattner6cefb772008-01-05 22:25:12 +00001861 // Now that we've parsed all of the tree fragments, do a closure on them so
1862 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001863 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1864 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001865 ThePat->InlinePatternFragments();
1866
1867 // Infer as many types as possible. Don't worry about it if we don't infer
1868 // all of them, some may depend on the inputs of the pattern.
1869 try {
1870 ThePat->InferAllTypes();
1871 } catch (...) {
1872 // If this pattern fragment is not supported by this target (no types can
1873 // satisfy its constraints), just ignore it. If the bogus pattern is
1874 // actually used by instructions, the type consistency error will be
1875 // reported there.
1876 }
1877
1878 // If debugging, print out the pattern fragment result.
1879 DEBUG(ThePat->dump());
1880 }
1881}
1882
Chris Lattnerfe718932008-01-06 01:10:31 +00001883void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001884 std::vector<Record*> DefaultOps[2];
1885 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1886 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1887
1888 // Find some SDNode.
1889 assert(!SDNodes.empty() && "No SDNodes parsed?");
1890 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1891
1892 for (unsigned iter = 0; iter != 2; ++iter) {
1893 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1894 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1895
1896 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1897 // SomeSDnode so that we can parse this.
1898 std::vector<std::pair<Init*, std::string> > Ops;
1899 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1900 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1901 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001902 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001903
1904 // Create a TreePattern to parse this.
1905 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1906 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1907
1908 // Copy the operands over into a DAGDefaultOperand.
1909 DAGDefaultOperand DefaultOpInfo;
1910
1911 TreePatternNode *T = P.getTree(0);
1912 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1913 TreePatternNode *TPN = T->getChild(op);
1914 while (TPN->ApplyTypeConstraints(P, false))
1915 /* Resolve all types */;
1916
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001917 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001918 if (iter == 0)
1919 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001920 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00001921 else
1922 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001923 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001924 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001925 DefaultOpInfo.DefaultOps.push_back(TPN);
1926 }
1927
1928 // Insert it into the DefaultOperands map so we can find it later.
1929 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1930 }
1931 }
1932}
1933
1934/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1935/// instruction input. Return true if this is a real use.
1936static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1937 std::map<std::string, TreePatternNode*> &InstInputs,
1938 std::vector<Record*> &InstImpInputs) {
1939 // No name -> not interesting.
1940 if (Pat->getName().empty()) {
1941 if (Pat->isLeaf()) {
1942 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1943 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1944 I->error("Input " + DI->getDef()->getName() + " must be named!");
1945 else if (DI && DI->getDef()->isSubClassOf("Register"))
1946 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001947 }
1948 return false;
1949 }
1950
1951 Record *Rec;
1952 if (Pat->isLeaf()) {
1953 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1954 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1955 Rec = DI->getDef();
1956 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001957 Rec = Pat->getOperator();
1958 }
1959
1960 // SRCVALUE nodes are ignored.
1961 if (Rec->getName() == "srcvalue")
1962 return false;
1963
1964 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1965 if (!Slot) {
1966 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00001967 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00001968 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00001969 Record *SlotRec;
1970 if (Slot->isLeaf()) {
1971 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1972 } else {
1973 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1974 SlotRec = Slot->getOperator();
1975 }
1976
1977 // Ensure that the inputs agree if we've already seen this input.
1978 if (Rec != SlotRec)
1979 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00001980 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00001981 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00001982 return true;
1983}
1984
1985/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1986/// part of "I", the instruction), computing the set of inputs and outputs of
1987/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001988void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001989FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1990 std::map<std::string, TreePatternNode*> &InstInputs,
1991 std::map<std::string, TreePatternNode*>&InstResults,
1992 std::vector<Record*> &InstImpInputs,
1993 std::vector<Record*> &InstImpResults) {
1994 if (Pat->isLeaf()) {
1995 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1996 if (!isUse && Pat->getTransformFn())
1997 I->error("Cannot specify a transform function for a non-input value!");
1998 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001999 }
2000
2001 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002002 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2003 TreePatternNode *Dest = Pat->getChild(i);
2004 if (!Dest->isLeaf())
2005 I->error("implicitly defined value should be a register!");
2006
2007 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2008 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2009 I->error("implicitly defined value should be a register!");
2010 InstImpResults.push_back(Val->getDef());
2011 }
2012 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002013 }
2014
2015 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002016 // If this is not a set, verify that the children nodes are not void typed,
2017 // and recurse.
2018 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002019 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002020 I->error("Cannot have void nodes inside of patterns!");
2021 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2022 InstImpInputs, InstImpResults);
2023 }
2024
2025 // If this is a non-leaf node with no children, treat it basically as if
2026 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00002027 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002028
2029 if (!isUse && Pat->getTransformFn())
2030 I->error("Cannot specify a transform function for a non-input value!");
2031 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002032 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002033
2034 // Otherwise, this is a set, validate and collect instruction results.
2035 if (Pat->getNumChildren() == 0)
2036 I->error("set requires operands!");
2037
2038 if (Pat->getTransformFn())
2039 I->error("Cannot specify a transform function on a set node!");
2040
2041 // Check the set destinations.
2042 unsigned NumDests = Pat->getNumChildren()-1;
2043 for (unsigned i = 0; i != NumDests; ++i) {
2044 TreePatternNode *Dest = Pat->getChild(i);
2045 if (!Dest->isLeaf())
2046 I->error("set destination should be a register!");
2047
2048 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2049 if (!Val)
2050 I->error("set destination should be a register!");
2051
2052 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002053 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002054 if (Dest->getName().empty())
2055 I->error("set destination must have a name!");
2056 if (InstResults.count(Dest->getName()))
2057 I->error("cannot set '" + Dest->getName() +"' multiple times");
2058 InstResults[Dest->getName()] = Dest;
2059 } else if (Val->getDef()->isSubClassOf("Register")) {
2060 InstImpResults.push_back(Val->getDef());
2061 } else {
2062 I->error("set destination should be a register!");
2063 }
2064 }
2065
2066 // Verify and collect info from the computation.
2067 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2068 InstInputs, InstResults,
2069 InstImpInputs, InstImpResults);
2070}
2071
Dan Gohmanee4fa192008-04-03 00:02:49 +00002072//===----------------------------------------------------------------------===//
2073// Instruction Analysis
2074//===----------------------------------------------------------------------===//
2075
2076class InstAnalyzer {
2077 const CodeGenDAGPatterns &CDP;
2078 bool &mayStore;
2079 bool &mayLoad;
2080 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002081 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002082public:
2083 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Chris Lattner1e506312010-03-19 05:34:15 +00002084 bool &maystore, bool &mayload, bool &hse, bool &isv)
2085 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
2086 IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002087 }
2088
2089 /// Analyze - Analyze the specified instruction, returning true if the
2090 /// instruction had a pattern.
2091 bool Analyze(Record *InstRecord) {
2092 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2093 if (Pattern == 0) {
2094 HasSideEffects = 1;
2095 return false; // No pattern.
2096 }
2097
2098 // FIXME: Assume only the first tree is the pattern. The others are clobber
2099 // nodes.
2100 AnalyzeNode(Pattern->getTree(0));
2101 return true;
2102 }
2103
2104private:
2105 void AnalyzeNode(const TreePatternNode *N) {
2106 if (N->isLeaf()) {
2107 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2108 Record *LeafRec = DI->getDef();
2109 // Handle ComplexPattern leaves.
2110 if (LeafRec->isSubClassOf("ComplexPattern")) {
2111 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2112 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2113 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2114 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2115 }
2116 }
2117 return;
2118 }
2119
2120 // Analyze children.
2121 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2122 AnalyzeNode(N->getChild(i));
2123
2124 // Ignore set nodes, which are not SDNodes.
2125 if (N->getOperator()->getName() == "set")
2126 return;
2127
2128 // Get information about the SDNode for the operator.
2129 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2130
2131 // Notice properties of the node.
2132 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2133 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2134 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002135 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002136
2137 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2138 // If this is an intrinsic, analyze it.
2139 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2140 mayLoad = true;// These may load memory.
2141
2142 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2143 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2144
2145 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2146 // WriteMem intrinsics can have other strange effects.
2147 HasSideEffects = true;
2148 }
2149 }
2150
2151};
2152
2153static void InferFromPattern(const CodeGenInstruction &Inst,
2154 bool &MayStore, bool &MayLoad,
Chris Lattner1e506312010-03-19 05:34:15 +00002155 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002156 const CodeGenDAGPatterns &CDP) {
Chris Lattner1e506312010-03-19 05:34:15 +00002157 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002158
2159 bool HadPattern =
Chris Lattner1e506312010-03-19 05:34:15 +00002160 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2161 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002162
2163 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2164 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2165 // If we decided that this is a store from the pattern, then the .td file
2166 // entry is redundant.
2167 if (MayStore)
2168 fprintf(stderr,
2169 "Warning: mayStore flag explicitly set on instruction '%s'"
2170 " but flag already inferred from pattern.\n",
2171 Inst.TheDef->getName().c_str());
2172 MayStore = true;
2173 }
2174
2175 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2176 // If we decided that this is a load from the pattern, then the .td file
2177 // entry is redundant.
2178 if (MayLoad)
2179 fprintf(stderr,
2180 "Warning: mayLoad flag explicitly set on instruction '%s'"
2181 " but flag already inferred from pattern.\n",
2182 Inst.TheDef->getName().c_str());
2183 MayLoad = true;
2184 }
2185
2186 if (Inst.neverHasSideEffects) {
2187 if (HadPattern)
2188 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2189 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2190 HasSideEffects = false;
2191 }
2192
2193 if (Inst.hasSideEffects) {
2194 if (HasSideEffects)
2195 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2196 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2197 HasSideEffects = true;
2198 }
Chris Lattner1e506312010-03-19 05:34:15 +00002199
2200 if (Inst.isVariadic)
2201 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002202}
2203
Chris Lattner6cefb772008-01-05 22:25:12 +00002204/// ParseInstructions - Parse all of the instructions, inlining and resolving
2205/// any fragments involved. This populates the Instructions list with fully
2206/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002207void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002208 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2209
2210 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2211 ListInit *LI = 0;
2212
2213 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2214 LI = Instrs[i]->getValueAsListInit("Pattern");
2215
2216 // If there is no pattern, only collect minimal information about the
2217 // instruction for its operand list. We have to assume that there is one
2218 // result, as we have no detailed info.
2219 if (!LI || LI->getSize() == 0) {
2220 std::vector<Record*> Results;
2221 std::vector<Record*> Operands;
2222
Chris Lattnerf30187a2010-03-19 00:07:20 +00002223 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002224
2225 if (InstInfo.OperandList.size() != 0) {
2226 if (InstInfo.NumDefs == 0) {
2227 // These produce no results
2228 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2229 Operands.push_back(InstInfo.OperandList[j].Rec);
2230 } else {
2231 // Assume the first operand is the result.
2232 Results.push_back(InstInfo.OperandList[0].Rec);
2233
2234 // The rest are inputs.
2235 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2236 Operands.push_back(InstInfo.OperandList[j].Rec);
2237 }
2238 }
2239
2240 // Create and insert the instruction.
2241 std::vector<Record*> ImpResults;
2242 std::vector<Record*> ImpOperands;
2243 Instructions.insert(std::make_pair(Instrs[i],
2244 DAGInstruction(0, Results, Operands, ImpResults,
2245 ImpOperands)));
2246 continue; // no pattern.
2247 }
2248
2249 // Parse the instruction.
2250 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2251 // Inline pattern fragments into it.
2252 I->InlinePatternFragments();
2253
2254 // Infer as many types as possible. If we cannot infer all of them, we can
2255 // never do anything with this instruction pattern: report it to the user.
2256 if (!I->InferAllTypes())
2257 I->error("Could not infer all types in pattern!");
2258
2259 // InstInputs - Keep track of all of the inputs of the instruction, along
2260 // with the record they are declared as.
2261 std::map<std::string, TreePatternNode*> InstInputs;
2262
2263 // InstResults - Keep track of all the virtual registers that are 'set'
2264 // in the instruction, including what reg class they are.
2265 std::map<std::string, TreePatternNode*> InstResults;
2266
2267 std::vector<Record*> InstImpInputs;
2268 std::vector<Record*> InstImpResults;
2269
2270 // Verify that the top-level forms in the instruction are of void type, and
2271 // fill in the InstResults map.
2272 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2273 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002274 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002275 I->error("Top-level forms in instruction pattern should have"
2276 " void types");
2277
2278 // Find inputs and outputs, and verify the structure of the uses/defs.
2279 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2280 InstImpInputs, InstImpResults);
2281 }
2282
2283 // Now that we have inputs and outputs of the pattern, inspect the operands
2284 // list for the instruction. This determines the order that operands are
2285 // added to the machine instruction the node corresponds to.
2286 unsigned NumResults = InstResults.size();
2287
2288 // Parse the operands list from the (ops) list, validating it.
2289 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002290 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002291
2292 // Check that all of the results occur first in the list.
2293 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002294 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002295 for (unsigned i = 0; i != NumResults; ++i) {
2296 if (i == CGI.OperandList.size())
2297 I->error("'" + InstResults.begin()->first +
2298 "' set but does not appear in operand list!");
2299 const std::string &OpName = CGI.OperandList[i].Name;
2300
2301 // Check that it exists in InstResults.
2302 TreePatternNode *RNode = InstResults[OpName];
2303 if (RNode == 0)
2304 I->error("Operand $" + OpName + " does not exist in operand list!");
2305
2306 if (i == 0)
2307 Res0Node = RNode;
2308 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2309 if (R == 0)
2310 I->error("Operand $" + OpName + " should be a set destination: all "
2311 "outputs must occur before inputs in operand list!");
2312
2313 if (CGI.OperandList[i].Rec != R)
2314 I->error("Operand $" + OpName + " class mismatch!");
2315
2316 // Remember the return type.
2317 Results.push_back(CGI.OperandList[i].Rec);
2318
2319 // Okay, this one checks out.
2320 InstResults.erase(OpName);
2321 }
2322
2323 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2324 // the copy while we're checking the inputs.
2325 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2326
2327 std::vector<TreePatternNode*> ResultNodeOperands;
2328 std::vector<Record*> Operands;
2329 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2330 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2331 const std::string &OpName = Op.Name;
2332 if (OpName.empty())
2333 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2334
2335 if (!InstInputsCheck.count(OpName)) {
2336 // If this is an predicate operand or optional def operand with an
2337 // DefaultOps set filled in, we can ignore this. When we codegen it,
2338 // we will do so as always executed.
2339 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2340 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2341 // Does it have a non-empty DefaultOps field? If so, ignore this
2342 // operand.
2343 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2344 continue;
2345 }
2346 I->error("Operand $" + OpName +
2347 " does not appear in the instruction pattern");
2348 }
2349 TreePatternNode *InVal = InstInputsCheck[OpName];
2350 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2351
2352 if (InVal->isLeaf() &&
2353 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2354 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2355 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2356 I->error("Operand $" + OpName + "'s register class disagrees"
2357 " between the operand and pattern");
2358 }
2359 Operands.push_back(Op.Rec);
2360
2361 // Construct the result for the dest-pattern operand list.
2362 TreePatternNode *OpNode = InVal->clone();
2363
2364 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002365 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002366
2367 // Promote the xform function to be an explicit node if set.
2368 if (Record *Xform = OpNode->getTransformFn()) {
2369 OpNode->setTransformFn(0);
2370 std::vector<TreePatternNode*> Children;
2371 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002372 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002373 }
2374
2375 ResultNodeOperands.push_back(OpNode);
2376 }
2377
2378 if (!InstInputsCheck.empty())
2379 I->error("Input operand $" + InstInputsCheck.begin()->first +
2380 " occurs in pattern but not in operands list!");
2381
2382 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002383 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2384 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002385 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002386 for (unsigned i = 0; i != NumResults; ++i)
2387 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002388
2389 // Create and insert the instruction.
2390 // FIXME: InstImpResults and InstImpInputs should not be part of
2391 // DAGInstruction.
2392 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2393 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2394
2395 // Use a temporary tree pattern to infer all types and make sure that the
2396 // constructed result is correct. This depends on the instruction already
2397 // being inserted into the Instructions map.
2398 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002399 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002400
2401 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2402 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2403
2404 DEBUG(I->dump());
2405 }
2406
2407 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002408 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2409 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002410 E = Instructions.end(); II != E; ++II) {
2411 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002412 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002413 if (I == 0) continue; // No pattern.
2414
2415 // FIXME: Assume only the first tree is the pattern. The others are clobber
2416 // nodes.
2417 TreePatternNode *Pattern = I->getTree(0);
2418 TreePatternNode *SrcPattern;
2419 if (Pattern->getOperator()->getName() == "set") {
2420 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2421 } else{
2422 // Not a set (store or something?)
2423 SrcPattern = Pattern;
2424 }
2425
Chris Lattner6cefb772008-01-05 22:25:12 +00002426 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002427 AddPatternToMatch(I,
2428 PatternToMatch(Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002429 SrcPattern,
2430 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002431 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002432 Instr->getValueAsInt("AddedComplexity"),
2433 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002434 }
2435}
2436
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002437
2438typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2439
Chris Lattner967d54a2010-02-23 06:35:45 +00002440static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002441 std::map<std::string, NameRecord> &Names,
2442 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002443 if (!P->getName().empty()) {
2444 NameRecord &Rec = Names[P->getName()];
2445 // If this is the first instance of the name, remember the node.
2446 if (Rec.second++ == 0)
2447 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002448 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002449 PatternTop->error("repetition of value: $" + P->getName() +
2450 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002451 }
Chris Lattner967d54a2010-02-23 06:35:45 +00002452
2453 if (!P->isLeaf()) {
2454 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002455 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002456 }
2457}
2458
Chris Lattner25b6f912010-02-23 06:16:51 +00002459void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2460 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002461 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002462 std::string Reason;
2463 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002464 Pattern->error("Pattern can never match: " + Reason);
Chris Lattner25b6f912010-02-23 06:16:51 +00002465
Chris Lattner405f1252010-03-01 22:29:19 +00002466 // If the source pattern's root is a complex pattern, that complex pattern
2467 // must specify the nodes it can potentially match.
2468 if (const ComplexPattern *CP =
2469 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2470 if (CP->getRootNodes().empty())
2471 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2472 " could match");
2473
2474
Chris Lattner967d54a2010-02-23 06:35:45 +00002475 // Find all of the named values in the input and output, ensure they have the
2476 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002477 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002478 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2479 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002480
2481 // Scan all of the named values in the destination pattern, rejecting them if
2482 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002483 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002484 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002485 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002486 Pattern->error("Pattern has input without matching name in output: $" +
2487 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002488 }
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002489
2490 // Scan all of the named values in the source pattern, rejecting them if the
2491 // name isn't used in the dest, and isn't used to tie two values together.
2492 for (std::map<std::string, NameRecord>::iterator
2493 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2494 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2495 Pattern->error("Pattern has dead named input: $" + I->first);
2496
Chris Lattner25b6f912010-02-23 06:16:51 +00002497 PatternsToMatch.push_back(PTM);
2498}
2499
2500
Dan Gohmanee4fa192008-04-03 00:02:49 +00002501
2502void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002503 const std::vector<const CodeGenInstruction*> &Instructions =
2504 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002505 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2506 CodeGenInstruction &InstInfo =
2507 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002508 // Determine properties of the instruction from its pattern.
Chris Lattner1e506312010-03-19 05:34:15 +00002509 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2510 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2511 *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002512 InstInfo.mayStore = MayStore;
2513 InstInfo.mayLoad = MayLoad;
2514 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002515 InstInfo.isVariadic = IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002516 }
2517}
2518
Chris Lattner2cacec52010-03-15 06:00:16 +00002519/// Given a pattern result with an unresolved type, see if we can find one
2520/// instruction with an unresolved result type. Force this result type to an
2521/// arbitrary element if it's possible types to converge results.
2522static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2523 if (N->isLeaf())
2524 return false;
2525
2526 // Analyze children.
2527 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2528 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2529 return true;
2530
2531 if (!N->getOperator()->isSubClassOf("Instruction"))
2532 return false;
2533
2534 // If this type is already concrete or completely unknown we can't do
2535 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00002536 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2537 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2538 continue;
Chris Lattner2cacec52010-03-15 06:00:16 +00002539
Chris Lattnerd7349192010-03-19 21:37:09 +00002540 // Otherwise, force its type to the first possibility (an arbitrary choice).
2541 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2542 return true;
2543 }
2544
2545 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00002546}
2547
Chris Lattnerfe718932008-01-06 01:10:31 +00002548void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002549 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2550
2551 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002552 Record *CurPattern = Patterns[i];
2553 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Chris Lattner6cefb772008-01-05 22:25:12 +00002554 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2555 Record *Operator = OpDef->getDef();
2556 TreePattern *Pattern;
2557 if (Operator->getName() != "parallel")
Chris Lattnerd7349192010-03-19 21:37:09 +00002558 Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002559 else {
2560 std::vector<Init*> Values;
David Greenee1b46912009-06-08 20:23:18 +00002561 RecTy *ListTy = 0;
2562 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002563 Values.push_back(Tree->getArg(j));
David Greenee1b46912009-06-08 20:23:18 +00002564 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2565 if (TArg == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002566 errs() << "In dag: " << Tree->getAsString();
2567 errs() << " -- Untyped argument in pattern\n";
David Greenee1b46912009-06-08 20:23:18 +00002568 assert(0 && "Untyped argument in pattern");
2569 }
2570 if (ListTy != 0) {
2571 ListTy = resolveTypes(ListTy, TArg->getType());
2572 if (ListTy == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002573 errs() << "In dag: " << Tree->getAsString();
2574 errs() << " -- Incompatible types in pattern arguments\n";
David Greenee1b46912009-06-08 20:23:18 +00002575 assert(0 && "Incompatible types in pattern arguments");
2576 }
2577 }
2578 else {
Bill Wendlingee1f6b02009-06-09 18:49:42 +00002579 ListTy = TArg->getType();
David Greenee1b46912009-06-08 20:23:18 +00002580 }
2581 }
2582 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
Chris Lattnerd7349192010-03-19 21:37:09 +00002583 Pattern = new TreePattern(CurPattern, LI, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002584 }
2585
2586 // Inline pattern fragments into it.
2587 Pattern->InlinePatternFragments();
2588
Chris Lattnerd7349192010-03-19 21:37:09 +00002589 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00002590 if (LI->getSize() == 0) continue; // no pattern.
2591
2592 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00002593 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002594
2595 // Inline pattern fragments into it.
2596 Result->InlinePatternFragments();
2597
2598 if (Result->getNumTrees() != 1)
2599 Result->error("Cannot handle instructions producing instructions "
2600 "with temporaries yet!");
2601
2602 bool IterateInference;
2603 bool InferredAllPatternTypes, InferredAllResultTypes;
2604 do {
2605 // Infer as many types as possible. If we cannot infer all of them, we
2606 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002607 InferredAllPatternTypes =
2608 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002609
2610 // Infer as many types as possible. If we cannot infer all of them, we
2611 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002612 InferredAllResultTypes =
2613 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002614
Chris Lattner6c6ba362010-03-18 23:15:10 +00002615 IterateInference = false;
2616
Chris Lattner6cefb772008-01-05 22:25:12 +00002617 // Apply the type of the result to the source pattern. This helps us
2618 // resolve cases where the input type is known to be a pointer type (which
2619 // is considered resolved), but the result knows it needs to be 32- or
2620 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00002621 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2622 Pattern->getTree(0)->getNumTypes());
2623 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00002624 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002625 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002626 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002627 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002628 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002629
2630 // If our iteration has converged and the input pattern's types are fully
2631 // resolved but the result pattern is not fully resolved, we may have a
2632 // situation where we have two instructions in the result pattern and
2633 // the instructions require a common register class, but don't care about
2634 // what actual MVT is used. This is actually a bug in our modelling:
2635 // output patterns should have register classes, not MVTs.
2636 //
2637 // In any case, to handle this, we just go through and disambiguate some
2638 // arbitrary types to the result pattern's nodes.
2639 if (!IterateInference && InferredAllPatternTypes &&
2640 !InferredAllResultTypes)
2641 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2642 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002643 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002644
Chris Lattner6cefb772008-01-05 22:25:12 +00002645 // Verify that we inferred enough types that we can do something with the
2646 // pattern and result. If these fire the user has to add type casts.
2647 if (!InferredAllPatternTypes)
2648 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002649 if (!InferredAllResultTypes) {
2650 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002651 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002652 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002653
2654 // Validate that the input pattern is correct.
2655 std::map<std::string, TreePatternNode*> InstInputs;
2656 std::map<std::string, TreePatternNode*> InstResults;
2657 std::vector<Record*> InstImpInputs;
2658 std::vector<Record*> InstImpResults;
2659 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2660 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2661 InstInputs, InstResults,
2662 InstImpInputs, InstImpResults);
2663
2664 // Promote the xform function to be an explicit node if set.
2665 TreePatternNode *DstPattern = Result->getOnlyTree();
2666 std::vector<TreePatternNode*> ResultNodeOperands;
2667 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2668 TreePatternNode *OpNode = DstPattern->getChild(ii);
2669 if (Record *Xform = OpNode->getTransformFn()) {
2670 OpNode->setTransformFn(0);
2671 std::vector<TreePatternNode*> Children;
2672 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002673 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002674 }
2675 ResultNodeOperands.push_back(OpNode);
2676 }
2677 DstPattern = Result->getOnlyTree();
2678 if (!DstPattern->isLeaf())
2679 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00002680 ResultNodeOperands,
2681 DstPattern->getNumTypes());
2682
2683 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2684 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2685
Chris Lattner6cefb772008-01-05 22:25:12 +00002686 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2687 Temp.InferAllTypes();
2688
Chris Lattner6cefb772008-01-05 22:25:12 +00002689
Chris Lattner25b6f912010-02-23 06:16:51 +00002690 AddPatternToMatch(Pattern,
Chris Lattnerd7349192010-03-19 21:37:09 +00002691 PatternToMatch(CurPattern->getValueAsListInit("Predicates"),
2692 Pattern->getTree(0),
2693 Temp.getOnlyTree(), InstImpResults,
2694 CurPattern->getValueAsInt("AddedComplexity"),
2695 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002696 }
2697}
2698
2699/// CombineChildVariants - Given a bunch of permutations of each child of the
2700/// 'operator' node, put them together in all possible ways.
2701static void CombineChildVariants(TreePatternNode *Orig,
2702 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2703 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002704 CodeGenDAGPatterns &CDP,
2705 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002706 // Make sure that each operand has at least one variant to choose from.
2707 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2708 if (ChildVariants[i].empty())
2709 return;
2710
2711 // The end result is an all-pairs construction of the resultant pattern.
2712 std::vector<unsigned> Idxs;
2713 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002714 bool NotDone;
2715 do {
2716#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002717 DEBUG(if (!Idxs.empty()) {
2718 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2719 for (unsigned i = 0; i < Idxs.size(); ++i) {
2720 errs() << Idxs[i] << " ";
2721 }
2722 errs() << "]\n";
2723 });
Scott Michel327d0652008-03-05 17:49:05 +00002724#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002725 // Create the variant and add it to the output list.
2726 std::vector<TreePatternNode*> NewChildren;
2727 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2728 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00002729 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2730 Orig->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002731
2732 // Copy over properties.
2733 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002734 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002735 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00002736 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2737 R->setType(i, Orig->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002738
Scott Michel327d0652008-03-05 17:49:05 +00002739 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002740 std::string ErrString;
2741 if (!R->canPatternMatch(ErrString, CDP)) {
2742 delete R;
2743 } else {
2744 bool AlreadyExists = false;
2745
2746 // Scan to see if this pattern has already been emitted. We can get
2747 // duplication due to things like commuting:
2748 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2749 // which are the same pattern. Ignore the dups.
2750 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002751 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002752 AlreadyExists = true;
2753 break;
2754 }
2755
2756 if (AlreadyExists)
2757 delete R;
2758 else
2759 OutVariants.push_back(R);
2760 }
2761
Scott Michel327d0652008-03-05 17:49:05 +00002762 // Increment indices to the next permutation by incrementing the
2763 // indicies from last index backward, e.g., generate the sequence
2764 // [0, 0], [0, 1], [1, 0], [1, 1].
2765 int IdxsIdx;
2766 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2767 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2768 Idxs[IdxsIdx] = 0;
2769 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002770 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002771 }
Scott Michel327d0652008-03-05 17:49:05 +00002772 NotDone = (IdxsIdx >= 0);
2773 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002774}
2775
2776/// CombineChildVariants - A helper function for binary operators.
2777///
2778static void CombineChildVariants(TreePatternNode *Orig,
2779 const std::vector<TreePatternNode*> &LHS,
2780 const std::vector<TreePatternNode*> &RHS,
2781 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002782 CodeGenDAGPatterns &CDP,
2783 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002784 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2785 ChildVariants.push_back(LHS);
2786 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002787 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002788}
2789
2790
2791static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2792 std::vector<TreePatternNode *> &Children) {
2793 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2794 Record *Operator = N->getOperator();
2795
2796 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002797 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002798 N->getTransformFn()) {
2799 Children.push_back(N);
2800 return;
2801 }
2802
2803 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2804 Children.push_back(N->getChild(0));
2805 else
2806 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2807
2808 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2809 Children.push_back(N->getChild(1));
2810 else
2811 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2812}
2813
2814/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2815/// the (potentially recursive) pattern by using algebraic laws.
2816///
2817static void GenerateVariantsOf(TreePatternNode *N,
2818 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002819 CodeGenDAGPatterns &CDP,
2820 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002821 // We cannot permute leaves.
2822 if (N->isLeaf()) {
2823 OutVariants.push_back(N);
2824 return;
2825 }
2826
2827 // Look up interesting info about the node.
2828 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2829
Jim Grosbachda4231f2009-03-26 16:17:51 +00002830 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002831 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002832 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002833 std::vector<TreePatternNode*> MaximalChildren;
2834 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2835
2836 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2837 // permutations.
2838 if (MaximalChildren.size() == 3) {
2839 // Find the variants of all of our maximal children.
2840 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002841 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2842 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2843 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002844
2845 // There are only two ways we can permute the tree:
2846 // (A op B) op C and A op (B op C)
2847 // Within these forms, we can also permute A/B/C.
2848
2849 // Generate legal pair permutations of A/B/C.
2850 std::vector<TreePatternNode*> ABVariants;
2851 std::vector<TreePatternNode*> BAVariants;
2852 std::vector<TreePatternNode*> ACVariants;
2853 std::vector<TreePatternNode*> CAVariants;
2854 std::vector<TreePatternNode*> BCVariants;
2855 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002856 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2857 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2858 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2859 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2860 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2861 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002862
2863 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002864 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2865 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2866 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2867 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2868 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2869 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002870
2871 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002872 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2873 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2874 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2875 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2876 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2877 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002878 return;
2879 }
2880 }
2881
2882 // Compute permutations of all children.
2883 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2884 ChildVariants.resize(N->getNumChildren());
2885 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002886 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002887
2888 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002889 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002890
2891 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002892 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2893 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2894 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2895 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002896 // Don't count children which are actually register references.
2897 unsigned NC = 0;
2898 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2899 TreePatternNode *Child = N->getChild(i);
2900 if (Child->isLeaf())
2901 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2902 Record *RR = DI->getDef();
2903 if (RR->isSubClassOf("Register"))
2904 continue;
2905 }
2906 NC++;
2907 }
2908 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002909 if (isCommIntrinsic) {
2910 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2911 // operands are the commutative operands, and there might be more operands
2912 // after those.
2913 assert(NC >= 3 &&
2914 "Commutative intrinsic should have at least 3 childrean!");
2915 std::vector<std::vector<TreePatternNode*> > Variants;
2916 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2917 Variants.push_back(ChildVariants[2]);
2918 Variants.push_back(ChildVariants[1]);
2919 for (unsigned i = 3; i != NC; ++i)
2920 Variants.push_back(ChildVariants[i]);
2921 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2922 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002923 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002924 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002925 }
2926}
2927
2928
2929// GenerateVariants - Generate variants. For example, commutative patterns can
2930// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002931void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002932 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002933
2934 // Loop over all of the patterns we've collected, checking to see if we can
2935 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002936 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002937 // the .td file having to contain tons of variants of instructions.
2938 //
2939 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2940 // intentionally do not reconsider these. Any variants of added patterns have
2941 // already been added.
2942 //
2943 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002944 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002945 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002946 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002947 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002948 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002949 DEBUG(errs() << "\n");
Scott Michel327d0652008-03-05 17:49:05 +00002950 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002951
2952 assert(!Variants.empty() && "Must create at least original variant!");
2953 Variants.erase(Variants.begin()); // Remove the original pattern.
2954
2955 if (Variants.empty()) // No variants for this pattern.
2956 continue;
2957
Chris Lattner569f1212009-08-23 04:44:11 +00002958 DEBUG(errs() << "FOUND VARIANTS OF: ";
2959 PatternsToMatch[i].getSrcPattern()->dump();
2960 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002961
2962 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2963 TreePatternNode *Variant = Variants[v];
2964
Chris Lattner569f1212009-08-23 04:44:11 +00002965 DEBUG(errs() << " VAR#" << v << ": ";
2966 Variant->dump();
2967 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002968
2969 // Scan to see if an instruction or explicit pattern already matches this.
2970 bool AlreadyExists = false;
2971 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00002972 // Skip if the top level predicates do not match.
2973 if (PatternsToMatch[i].getPredicates() !=
2974 PatternsToMatch[p].getPredicates())
2975 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00002976 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002977 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00002978 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002979 AlreadyExists = true;
2980 break;
2981 }
2982 }
2983 // If we already have it, ignore the variant.
2984 if (AlreadyExists) continue;
2985
2986 // Otherwise, add it to the list of patterns we have.
2987 PatternsToMatch.
2988 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2989 Variant, PatternsToMatch[i].getDstPattern(),
2990 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002991 PatternsToMatch[i].getAddedComplexity(),
2992 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002993 }
2994
Chris Lattner569f1212009-08-23 04:44:11 +00002995 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002996 }
2997}
2998