blob: 4a9ac2d53a831322c795455749e8cafb8187c4db [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner6cefb772008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfe718932008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner93c7e412008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
Chris Lattner2cacec52010-03-15 06:00:16 +000018#include "llvm/ADT/STLExtras.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include "llvm/Support/Debug.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000020#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000021#include <algorithm>
Chris Lattner6cefb772008-01-05 22:25:12 +000022using namespace llvm;
23
24//===----------------------------------------------------------------------===//
Chris Lattner2cacec52010-03-15 06:00:16 +000025// EEVT::TypeSet Implementation
26//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +000027
Owen Anderson825b72b2009-08-11 20:47:22 +000028static inline bool isInteger(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000029 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000030}
Owen Anderson825b72b2009-08-11 20:47:22 +000031static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000032 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000033}
Owen Anderson825b72b2009-08-11 20:47:22 +000034static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000035 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000036}
Chris Lattner774ce292010-03-19 17:41:26 +000037static inline bool isScalar(MVT::SimpleValueType VT) {
38 return !EVT(VT).isVector();
39}
Duncan Sands83ec4b62008-06-06 12:08:01 +000040
Chris Lattner2cacec52010-03-15 06:00:16 +000041EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
42 if (VT == MVT::iAny)
43 EnforceInteger(TP);
44 else if (VT == MVT::fAny)
45 EnforceFloatingPoint(TP);
46 else if (VT == MVT::vAny)
47 EnforceVector(TP);
48 else {
49 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
50 VT == MVT::iPTRAny) && "Not a concrete type!");
51 TypeVec.push_back(VT);
52 }
Chris Lattner6cefb772008-01-05 22:25:12 +000053}
54
Chris Lattner2cacec52010-03-15 06:00:16 +000055
56EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
57 assert(!VTList.empty() && "empty list?");
58 TypeVec.append(VTList.begin(), VTList.end());
59
60 if (!VTList.empty())
61 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62 VTList[0] != MVT::fAny);
63
Chris Lattner0d7952e2010-03-27 20:32:26 +000064 // Verify no duplicates.
Chris Lattner2cacec52010-03-15 06:00:16 +000065 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner0d7952e2010-03-27 20:32:26 +000066 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner6cefb772008-01-05 22:25:12 +000067}
68
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000069/// FillWithPossibleTypes - Set to all legal types and return true, only valid
70/// on completely unknown type sets.
Chris Lattner774ce292010-03-19 17:41:26 +000071bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
72 bool (*Pred)(MVT::SimpleValueType),
73 const char *PredicateName) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000074 assert(isCompletelyUnknown());
Chris Lattner774ce292010-03-19 17:41:26 +000075 const std::vector<MVT::SimpleValueType> &LegalTypes =
76 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
77
78 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
79 if (Pred == 0 || Pred(LegalTypes[i]))
80 TypeVec.push_back(LegalTypes[i]);
81
82 // If we have nothing that matches the predicate, bail out.
83 if (TypeVec.empty())
84 TP.error("Type inference contradiction found, no " +
85 std::string(PredicateName) + " types found");
86 // No need to sort with one element.
87 if (TypeVec.size() == 1) return true;
88
89 // Remove duplicates.
90 array_pod_sort(TypeVec.begin(), TypeVec.end());
91 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
92
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000093 return true;
94}
Chris Lattner2cacec52010-03-15 06:00:16 +000095
96/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
97/// integer value type.
98bool EEVT::TypeSet::hasIntegerTypes() const {
99 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
100 if (isInteger(TypeVec[i]))
101 return true;
102 return false;
103}
104
105/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
106/// a floating point value type.
107bool EEVT::TypeSet::hasFloatingPointTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isFloatingPoint(TypeVec[i]))
110 return true;
111 return false;
112}
113
114/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
115/// value type.
116bool EEVT::TypeSet::hasVectorTypes() const {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isVector(TypeVec[i]))
119 return true;
120 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +0000121}
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000122
Chris Lattner2cacec52010-03-15 06:00:16 +0000123
124std::string EEVT::TypeSet::getName() const {
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000125 if (TypeVec.empty()) return "<empty>";
Chris Lattner2cacec52010-03-15 06:00:16 +0000126
127 std::string Result;
128
129 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
130 std::string VTName = llvm::getEnumName(TypeVec[i]);
131 // Strip off MVT:: prefix if present.
132 if (VTName.substr(0,5) == "MVT::")
133 VTName = VTName.substr(5);
134 if (i) Result += ':';
135 Result += VTName;
136 }
137
138 if (TypeVec.size() == 1)
139 return Result;
140 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000141}
Chris Lattner2cacec52010-03-15 06:00:16 +0000142
143/// MergeInTypeInfo - This merges in type information from the specified
144/// argument. If 'this' changes, it returns true. If the two types are
145/// contradictory (e.g. merge f32 into i32) then this throws an exception.
146bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
147 if (InVT.isCompletelyUnknown() || *this == InVT)
148 return false;
149
150 if (isCompletelyUnknown()) {
151 *this = InVT;
152 return true;
153 }
154
155 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
156
157 // Handle the abstract cases, seeing if we can resolve them better.
158 switch (TypeVec[0]) {
159 default: break;
160 case MVT::iPTR:
161 case MVT::iPTRAny:
162 if (InVT.hasIntegerTypes()) {
163 EEVT::TypeSet InCopy(InVT);
164 InCopy.EnforceInteger(TP);
165 InCopy.EnforceScalar(TP);
166
167 if (InCopy.isConcrete()) {
168 // If the RHS has one integer type, upgrade iPTR to i32.
169 TypeVec[0] = InVT.TypeVec[0];
170 return true;
171 }
172
173 // If the input has multiple scalar integers, this doesn't add any info.
174 if (!InCopy.isCompletelyUnknown())
175 return false;
176 }
177 break;
178 }
179
180 // If the input constraint is iAny/iPTR and this is an integer type list,
181 // remove non-integer types from the list.
182 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
183 hasIntegerTypes()) {
184 bool MadeChange = EnforceInteger(TP);
185
186 // If we're merging in iPTR/iPTRAny and the node currently has a list of
187 // multiple different integer types, replace them with a single iPTR.
188 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
189 TypeVec.size() != 1) {
190 TypeVec.resize(1);
191 TypeVec[0] = InVT.TypeVec[0];
192 MadeChange = true;
193 }
194
195 return MadeChange;
196 }
197
198 // If this is a type list and the RHS is a typelist as well, eliminate entries
199 // from this list that aren't in the other one.
200 bool MadeChange = false;
201 TypeSet InputSet(*this);
202
203 for (unsigned i = 0; i != TypeVec.size(); ++i) {
204 bool InInVT = false;
205 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
206 if (TypeVec[i] == InVT.TypeVec[j]) {
207 InInVT = true;
208 break;
209 }
210
211 if (InInVT) continue;
212 TypeVec.erase(TypeVec.begin()+i--);
213 MadeChange = true;
214 }
215
216 // If we removed all of our types, we have a type contradiction.
217 if (!TypeVec.empty())
218 return MadeChange;
219
220 // FIXME: Really want an SMLoc here!
221 TP.error("Type inference contradiction found, merging '" +
222 InVT.getName() + "' into '" + InputSet.getName() + "'");
223 return true; // unreachable
224}
225
226/// EnforceInteger - Remove all non-integer types from this set.
227bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000228 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000229 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000230 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattner2cacec52010-03-15 06:00:16 +0000231 if (!hasFloatingPointTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000232 return false;
233
234 TypeSet InputSet(*this);
Chris Lattner2cacec52010-03-15 06:00:16 +0000235
236 // Filter out all the fp types.
237 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000238 if (!isInteger(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000239 TypeVec.erase(TypeVec.begin()+i--);
240
241 if (TypeVec.empty())
242 TP.error("Type inference contradiction found, '" +
243 InputSet.getName() + "' needs to be integer");
Chris Lattner774ce292010-03-19 17:41:26 +0000244 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000245}
246
247/// EnforceFloatingPoint - Remove all integer types from this set.
248bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000249 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000250 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000251 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
252
Chris Lattner2cacec52010-03-15 06:00:16 +0000253 if (!hasIntegerTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000254 return false;
255
256 TypeSet InputSet(*this);
Chris Lattner2cacec52010-03-15 06:00:16 +0000257
258 // Filter out all the fp types.
259 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000260 if (!isFloatingPoint(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000261 TypeVec.erase(TypeVec.begin()+i--);
262
263 if (TypeVec.empty())
264 TP.error("Type inference contradiction found, '" +
265 InputSet.getName() + "' needs to be floating point");
Chris Lattner774ce292010-03-19 17:41:26 +0000266 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000267}
268
269/// EnforceScalar - Remove all vector types from this.
270bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000271 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000272 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000273 return FillWithPossibleTypes(TP, isScalar, "scalar");
274
Chris Lattner2cacec52010-03-15 06:00:16 +0000275 if (!hasVectorTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000276 return false;
277
278 TypeSet InputSet(*this);
Chris Lattner2cacec52010-03-15 06:00:16 +0000279
280 // Filter out all the vector types.
281 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000282 if (!isScalar(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000283 TypeVec.erase(TypeVec.begin()+i--);
284
285 if (TypeVec.empty())
286 TP.error("Type inference contradiction found, '" +
287 InputSet.getName() + "' needs to be scalar");
Chris Lattner774ce292010-03-19 17:41:26 +0000288 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000289}
290
291/// EnforceVector - Remove all vector types from this.
292bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Chris Lattner774ce292010-03-19 17:41:26 +0000293 // If we know nothing, then get the full set.
294 if (TypeVec.empty())
295 return FillWithPossibleTypes(TP, isVector, "vector");
296
Chris Lattner2cacec52010-03-15 06:00:16 +0000297 TypeSet InputSet(*this);
298 bool MadeChange = false;
299
Chris Lattner2cacec52010-03-15 06:00:16 +0000300 // Filter out all the scalar types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000302 if (!isVector(TypeVec[i])) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000303 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner774ce292010-03-19 17:41:26 +0000304 MadeChange = true;
305 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000306
307 if (TypeVec.empty())
308 TP.error("Type inference contradiction found, '" +
309 InputSet.getName() + "' needs to be a vector");
310 return MadeChange;
311}
312
313
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000314
Chris Lattner2cacec52010-03-15 06:00:16 +0000315/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
316/// this an other based on this information.
317bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
318 // Both operands must be integer or FP, but we don't care which.
319 bool MadeChange = false;
320
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000321 if (isCompletelyUnknown())
322 MadeChange = FillWithPossibleTypes(TP);
323
324 if (Other.isCompletelyUnknown())
325 MadeChange = Other.FillWithPossibleTypes(TP);
326
327 // If one side is known to be integer or known to be FP but the other side has
328 // no information, get at least the type integrality info in there.
329 if (!hasFloatingPointTypes())
330 MadeChange |= Other.EnforceInteger(TP);
331 else if (!hasIntegerTypes())
332 MadeChange |= Other.EnforceFloatingPoint(TP);
333 if (!Other.hasFloatingPointTypes())
334 MadeChange |= EnforceInteger(TP);
335 else if (!Other.hasIntegerTypes())
336 MadeChange |= EnforceFloatingPoint(TP);
337
338 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339 "Should have a type list now");
340
341 // If one contains vectors but the other doesn't pull vectors out.
342 if (!hasVectorTypes())
343 MadeChange |= Other.EnforceScalar(TP);
344 if (!hasVectorTypes())
345 MadeChange |= EnforceScalar(TP);
346
Chris Lattner2cacec52010-03-15 06:00:16 +0000347 // This code does not currently handle nodes which have multiple types,
348 // where some types are integer, and some are fp. Assert that this is not
349 // the case.
350 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
351 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
352 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000353
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000354 // Okay, find the smallest type from the current set and remove it from the
355 // largest set.
356 MVT::SimpleValueType Smallest = TypeVec[0];
357 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
358 if (TypeVec[i] < Smallest)
359 Smallest = TypeVec[i];
Chris Lattner2cacec52010-03-15 06:00:16 +0000360
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000361 // If this is the only type in the large set, the constraint can never be
362 // satisfied.
363 if (Other.TypeVec.size() == 1 && Other.TypeVec[0] == Smallest)
364 TP.error("Type inference contradiction found, '" +
365 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000366
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000367 SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
368 std::find(Other.TypeVec.begin(), Other.TypeVec.end(), Smallest);
369 if (TVI != Other.TypeVec.end()) {
370 Other.TypeVec.erase(TVI);
371 MadeChange = true;
372 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000373
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000374 // Okay, find the largest type in the Other set and remove it from the
375 // current set.
376 MVT::SimpleValueType Largest = Other.TypeVec[0];
377 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
378 if (Other.TypeVec[i] > Largest)
379 Largest = Other.TypeVec[i];
Chris Lattner2cacec52010-03-15 06:00:16 +0000380
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000381 // If this is the only type in the small set, the constraint can never be
382 // satisfied.
383 if (TypeVec.size() == 1 && TypeVec[0] == Largest)
384 TP.error("Type inference contradiction found, '" +
385 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
386
387 TVI = std::find(TypeVec.begin(), TypeVec.end(), Largest);
388 if (TVI != TypeVec.end()) {
389 TypeVec.erase(TVI);
390 MadeChange = true;
391 }
392
393 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000394}
395
396/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner66fb9d22010-03-24 00:01:16 +0000397/// whose element is specified by VTOperand.
398bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattner2cacec52010-03-15 06:00:16 +0000399 TreePattern &TP) {
Chris Lattner66fb9d22010-03-24 00:01:16 +0000400 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattner2cacec52010-03-15 06:00:16 +0000401 bool MadeChange = false;
Chris Lattner66fb9d22010-03-24 00:01:16 +0000402 MadeChange |= EnforceVector(TP);
403 MadeChange |= VTOperand.EnforceScalar(TP);
404
405 // If we know the vector type, it forces the scalar to agree.
406 if (isConcrete()) {
407 EVT IVT = getConcrete();
408 IVT = IVT.getVectorElementType();
409 return MadeChange |
410 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
411 }
412
413 // If the scalar type is known, filter out vector types whose element types
414 // disagree.
415 if (!VTOperand.isConcrete())
416 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000417
Chris Lattner66fb9d22010-03-24 00:01:16 +0000418 MVT::SimpleValueType VT = VTOperand.getConcrete();
Chris Lattner2cacec52010-03-15 06:00:16 +0000419
Chris Lattner66fb9d22010-03-24 00:01:16 +0000420 TypeSet InputSet(*this);
421
422 // Filter out all the types which don't have the right element type.
423 for (unsigned i = 0; i != TypeVec.size(); ++i) {
424 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
425 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000426 TypeVec.erase(TypeVec.begin()+i--);
427 MadeChange = true;
428 }
Chris Lattner66fb9d22010-03-24 00:01:16 +0000429 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000430
431 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
432 TP.error("Type inference contradiction found, forcing '" +
433 InputSet.getName() + "' to have a vector element");
434 return MadeChange;
435}
436
437//===----------------------------------------------------------------------===//
438// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000439
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000440bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
441 return LHS->getID() < RHS->getID();
442}
Scott Michel327d0652008-03-05 17:49:05 +0000443
444/// Dependent variable map for CodeGenDAGPattern variant generation
445typedef std::map<std::string, int> DepVarMap;
446
447/// Const iterator shorthand for DepVarMap
448typedef DepVarMap::const_iterator DepVarMap_citer;
449
450namespace {
451void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
452 if (N->isLeaf()) {
453 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
454 DepMap[N->getName()]++;
455 }
456 } else {
457 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
458 FindDepVarsOf(N->getChild(i), DepMap);
459 }
460}
461
462//! Find dependent variables within child patterns
463/*!
464 */
465void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
466 DepVarMap depcounts;
467 FindDepVarsOf(N, depcounts);
468 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
469 if (i->second > 1) { // std::pair<std::string, int>
470 DepVars.insert(i->first);
471 }
472 }
473}
474
475//! Dump the dependent variable set:
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000476#ifndef NDEBUG
Scott Michel327d0652008-03-05 17:49:05 +0000477void DumpDepVars(MultipleUseVarSet &DepVars) {
478 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000479 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000480 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000481 DEBUG(errs() << "[ ");
Jim Grosbachbb168242010-10-08 18:13:57 +0000482 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
483 e = DepVars.end(); i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000484 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000485 }
Chris Lattner569f1212009-08-23 04:44:11 +0000486 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000487 }
488}
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000489#endif
490
Scott Michel327d0652008-03-05 17:49:05 +0000491}
492
Chris Lattner6cefb772008-01-05 22:25:12 +0000493//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000494// PatternToMatch implementation
495//
496
Chris Lattner48e86db2010-03-29 01:40:38 +0000497
498/// getPatternSize - Return the 'size' of this pattern. We want to match large
499/// patterns before small ones. This is used to determine the size of a
500/// pattern.
501static unsigned getPatternSize(const TreePatternNode *P,
502 const CodeGenDAGPatterns &CGP) {
503 unsigned Size = 3; // The node itself.
504 // If the root node is a ConstantSDNode, increases its size.
505 // e.g. (set R32:$dst, 0).
506 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
507 Size += 2;
508
509 // FIXME: This is a hack to statically increase the priority of patterns
510 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
511 // Later we can allow complexity / cost for each pattern to be (optionally)
512 // specified. To get best possible pattern match we'll need to dynamically
513 // calculate the complexity of all patterns a dag can potentially map to.
514 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
515 if (AM)
516 Size += AM->getNumOperands() * 3;
517
518 // If this node has some predicate function that must match, it adds to the
519 // complexity of this node.
520 if (!P->getPredicateFns().empty())
521 ++Size;
522
523 // Count children in the count if they are also nodes.
524 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
525 TreePatternNode *Child = P->getChild(i);
526 if (!Child->isLeaf() && Child->getNumTypes() &&
527 Child->getType(0) != MVT::Other)
528 Size += getPatternSize(Child, CGP);
529 else if (Child->isLeaf()) {
530 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
531 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
532 else if (Child->getComplexPatternInfo(CGP))
533 Size += getPatternSize(Child, CGP);
534 else if (!Child->getPredicateFns().empty())
535 ++Size;
536 }
537 }
538
539 return Size;
540}
541
542/// Compute the complexity metric for the input pattern. This roughly
543/// corresponds to the number of nodes that are covered.
544unsigned PatternToMatch::
545getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
546 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
547}
548
549
Dan Gohman22bb3112008-08-22 00:20:26 +0000550/// getPredicateCheck - Return a single string containing all of this
551/// pattern's predicates concatenated with "&&" operators.
552///
553std::string PatternToMatch::getPredicateCheck() const {
554 std::string PredicateCheck;
555 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
556 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
557 Record *Def = Pred->getDef();
558 if (!Def->isSubClassOf("Predicate")) {
559#ifndef NDEBUG
560 Def->dump();
561#endif
562 assert(0 && "Unknown predicate type!");
563 }
564 if (!PredicateCheck.empty())
565 PredicateCheck += " && ";
566 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
567 }
568 }
569
570 return PredicateCheck;
571}
572
573//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000574// SDTypeConstraint implementation
575//
576
577SDTypeConstraint::SDTypeConstraint(Record *R) {
578 OperandNo = R->getValueAsInt("OperandNum");
579
580 if (R->isSubClassOf("SDTCisVT")) {
581 ConstraintType = SDTCisVT;
582 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerc8122612010-03-28 06:04:39 +0000583 if (x.SDTCisVT_Info.VT == MVT::isVoid)
584 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
585
Chris Lattner6cefb772008-01-05 22:25:12 +0000586 } else if (R->isSubClassOf("SDTCisPtrTy")) {
587 ConstraintType = SDTCisPtrTy;
588 } else if (R->isSubClassOf("SDTCisInt")) {
589 ConstraintType = SDTCisInt;
590 } else if (R->isSubClassOf("SDTCisFP")) {
591 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000592 } else if (R->isSubClassOf("SDTCisVec")) {
593 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000594 } else if (R->isSubClassOf("SDTCisSameAs")) {
595 ConstraintType = SDTCisSameAs;
596 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
597 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
598 ConstraintType = SDTCisVTSmallerThanOp;
599 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
600 R->getValueAsInt("OtherOperandNum");
601 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
602 ConstraintType = SDTCisOpSmallerThanOp;
603 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
604 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000605 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
606 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000607 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000608 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000609 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000610 exit(1);
611 }
612}
613
614/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000615/// N, and the result number in ResNo.
616static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
617 const SDNodeInfo &NodeInfo,
618 unsigned &ResNo) {
619 unsigned NumResults = NodeInfo.getNumResults();
620 if (OpNo < NumResults) {
621 ResNo = OpNo;
622 return N;
623 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000624
Chris Lattner2e68a022010-03-19 21:56:21 +0000625 OpNo -= NumResults;
626
627 if (OpNo >= N->getNumChildren()) {
628 errs() << "Invalid operand number in type constraint "
629 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000630 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000631 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000632 exit(1);
633 }
634
Chris Lattner2e68a022010-03-19 21:56:21 +0000635 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000636}
637
638/// ApplyTypeConstraint - Given a node in a pattern, apply this type
639/// constraint to the nodes operands. This returns true if it makes a
640/// change, false otherwise. If a type contradiction is found, throw an
641/// exception.
642bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
643 const SDNodeInfo &NodeInfo,
644 TreePattern &TP) const {
Chris Lattner2e68a022010-03-19 21:56:21 +0000645 unsigned ResNo = 0; // The result number being referenced.
646 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000647
648 switch (ConstraintType) {
649 default: assert(0 && "Unknown constraint type!");
650 case SDTCisVT:
651 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000652 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000653 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000654 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000655 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000656 case SDTCisInt:
657 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000658 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000659 case SDTCisFP:
660 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000661 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000662 case SDTCisVec:
663 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000664 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000665 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000666 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000667 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000668 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000669 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
670 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000671 }
672 case SDTCisVTSmallerThanOp: {
673 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
674 // have an integer type that is smaller than the VT.
675 if (!NodeToApply->isLeaf() ||
676 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
677 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
678 ->isSubClassOf("ValueType"))
679 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000680 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000681 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Chris Lattnercc878302010-03-24 00:06:46 +0000682
683 EEVT::TypeSet TypeListTmp(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000684
Chris Lattner2e68a022010-03-19 21:56:21 +0000685 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000686 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000687 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
688 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000689
Chris Lattnercc878302010-03-24 00:06:46 +0000690 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000691 }
692 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000693 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000694 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000695 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
696 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000697 return NodeToApply->getExtType(ResNo).
698 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000699 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000700 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000701 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000702 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000703 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
704 VResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000705
Chris Lattner66fb9d22010-03-24 00:01:16 +0000706 // Filter vector types out of VecOperand that don't have the right element
707 // type.
708 return VecOperand->getExtType(VResNo).
709 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000710 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000711 }
712 return false;
713}
714
715//===----------------------------------------------------------------------===//
716// SDNodeInfo implementation
717//
718SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
719 EnumName = R->getValueAsString("Opcode");
720 SDClassName = R->getValueAsString("SDClass");
721 Record *TypeProfile = R->getValueAsDef("TypeProfile");
722 NumResults = TypeProfile->getValueAsInt("NumResults");
723 NumOperands = TypeProfile->getValueAsInt("NumOperands");
724
725 // Parse the properties.
726 Properties = 0;
727 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
728 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
729 if (PropList[i]->getName() == "SDNPCommutative") {
730 Properties |= 1 << SDNPCommutative;
731 } else if (PropList[i]->getName() == "SDNPAssociative") {
732 Properties |= 1 << SDNPAssociative;
733 } else if (PropList[i]->getName() == "SDNPHasChain") {
734 Properties |= 1 << SDNPHasChain;
735 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000736 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000737 } else if (PropList[i]->getName() == "SDNPInFlag") {
738 Properties |= 1 << SDNPInFlag;
739 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
740 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000741 } else if (PropList[i]->getName() == "SDNPMayStore") {
742 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000743 } else if (PropList[i]->getName() == "SDNPMayLoad") {
744 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000745 } else if (PropList[i]->getName() == "SDNPSideEffect") {
746 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000747 } else if (PropList[i]->getName() == "SDNPMemOperand") {
748 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000749 } else if (PropList[i]->getName() == "SDNPVariadic") {
750 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000751 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000752 errs() << "Unknown SD Node property '" << PropList[i]->getName()
753 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000754 exit(1);
755 }
756 }
757
758
759 // Parse the type constraints.
760 std::vector<Record*> ConstraintList =
761 TypeProfile->getValueAsListOfDefs("Constraints");
762 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
763}
764
Chris Lattner22579812010-02-28 00:22:30 +0000765/// getKnownType - If the type constraints on this node imply a fixed type
766/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000767/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +0000768MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +0000769 unsigned NumResults = getNumResults();
770 assert(NumResults <= 1 &&
771 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +0000772 assert(ResNo == 0 && "Only handles single result nodes so far");
Chris Lattner22579812010-02-28 00:22:30 +0000773
774 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
775 // Make sure that this applies to the correct node result.
776 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
777 continue;
778
779 switch (TypeConstraints[i].ConstraintType) {
780 default: break;
781 case SDTypeConstraint::SDTCisVT:
782 return TypeConstraints[i].x.SDTCisVT_Info.VT;
783 case SDTypeConstraint::SDTCisPtrTy:
784 return MVT::iPTR;
785 }
786 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000787 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000788}
789
Chris Lattner6cefb772008-01-05 22:25:12 +0000790//===----------------------------------------------------------------------===//
791// TreePatternNode implementation
792//
793
794TreePatternNode::~TreePatternNode() {
795#if 0 // FIXME: implement refcounted tree nodes!
796 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
797 delete getChild(i);
798#endif
799}
800
Chris Lattnerd7349192010-03-19 21:37:09 +0000801static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
802 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +0000803 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +0000804 return 0; // All return nothing.
805
Chris Lattner93dc92e2010-03-22 20:56:36 +0000806 if (Operator->isSubClassOf("Intrinsic"))
807 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Chris Lattner6cefb772008-01-05 22:25:12 +0000808
Chris Lattnerd7349192010-03-19 21:37:09 +0000809 if (Operator->isSubClassOf("SDNode"))
810 return CDP.getSDNodeInfo(Operator).getNumResults();
811
812 if (Operator->isSubClassOf("PatFrag")) {
813 // If we've already parsed this pattern fragment, get it. Otherwise, handle
814 // the forward reference case where one pattern fragment references another
815 // before it is processed.
816 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
817 return PFRec->getOnlyTree()->getNumTypes();
818
819 // Get the result tree.
820 DagInit *Tree = Operator->getValueAsDag("Fragment");
821 Record *Op = 0;
822 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
823 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
824 assert(Op && "Invalid Fragment");
825 return GetNumNodeResults(Op, CDP);
826 }
827
828 if (Operator->isSubClassOf("Instruction")) {
829 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +0000830
831 // FIXME: Should allow access to all the results here.
Chris Lattnerc240bb02010-11-01 04:03:32 +0000832 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Chris Lattnerd7349192010-03-19 21:37:09 +0000833
Chris Lattner9414ae52010-03-27 20:09:24 +0000834 // Add on one implicit def if it has a resolvable type.
835 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
836 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +0000837 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +0000838 }
839
840 if (Operator->isSubClassOf("SDNodeXForm"))
841 return 1; // FIXME: Generalize SDNodeXForm
842
843 Operator->dump();
844 errs() << "Unhandled node in GetNumNodeResults\n";
845 exit(1);
846}
847
848void TreePatternNode::print(raw_ostream &OS) const {
849 if (isLeaf())
850 OS << *getLeafValue();
851 else
852 OS << '(' << getOperator()->getName();
853
854 for (unsigned i = 0, e = Types.size(); i != e; ++i)
855 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000856
857 if (!isLeaf()) {
858 if (getNumChildren() != 0) {
859 OS << " ";
860 getChild(0)->print(OS);
861 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
862 OS << ", ";
863 getChild(i)->print(OS);
864 }
865 }
866 OS << ")";
867 }
868
Dan Gohman0540e172008-10-15 06:17:21 +0000869 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
870 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000871 if (TransformFn)
872 OS << "<<X:" << TransformFn->getName() << ">>";
873 if (!getName().empty())
874 OS << ":$" << getName();
875
876}
877void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000878 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000879}
880
Scott Michel327d0652008-03-05 17:49:05 +0000881/// isIsomorphicTo - Return true if this node is recursively
882/// isomorphic to the specified node. For this comparison, the node's
883/// entire state is considered. The assigned name is ignored, since
884/// nodes with differing names are considered isomorphic. However, if
885/// the assigned name is present in the dependent variable set, then
886/// the assigned name is considered significant and the node is
887/// isomorphic if the names match.
888bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
889 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000890 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +0000891 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000892 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000893 getTransformFn() != N->getTransformFn())
894 return false;
895
896 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000897 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
898 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000899 return ((DI->getDef() == NDI->getDef())
900 && (DepVars.find(getName()) == DepVars.end()
901 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000902 }
903 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000904 return getLeafValue() == N->getLeafValue();
905 }
906
907 if (N->getOperator() != getOperator() ||
908 N->getNumChildren() != getNumChildren()) return false;
909 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000910 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000911 return false;
912 return true;
913}
914
915/// clone - Make a copy of this tree and all of its children.
916///
917TreePatternNode *TreePatternNode::clone() const {
918 TreePatternNode *New;
919 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +0000920 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000921 } else {
922 std::vector<TreePatternNode*> CChildren;
923 CChildren.reserve(Children.size());
924 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
925 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +0000926 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000927 }
928 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +0000929 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +0000930 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000931 New->setTransformFn(getTransformFn());
932 return New;
933}
934
Chris Lattner47661322010-02-14 22:22:58 +0000935/// RemoveAllTypes - Recursively strip all the types of this tree.
936void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +0000937 for (unsigned i = 0, e = Types.size(); i != e; ++i)
938 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +0000939 if (isLeaf()) return;
940 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
941 getChild(i)->RemoveAllTypes();
942}
943
944
Chris Lattner6cefb772008-01-05 22:25:12 +0000945/// SubstituteFormalArguments - Replace the formal arguments in this tree
946/// with actual values specified by ArgMap.
947void TreePatternNode::
948SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
949 if (isLeaf()) return;
950
951 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
952 TreePatternNode *Child = getChild(i);
953 if (Child->isLeaf()) {
954 Init *Val = Child->getLeafValue();
955 if (dynamic_cast<DefInit*>(Val) &&
956 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
957 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000958 TreePatternNode *NewChild = ArgMap[Child->getName()];
959 assert(NewChild && "Couldn't find formal argument!");
960 assert((Child->getPredicateFns().empty() ||
961 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
962 "Non-empty child predicate clobbered!");
963 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000964 }
965 } else {
966 getChild(i)->SubstituteFormalArguments(ArgMap);
967 }
968 }
969}
970
971
972/// InlinePatternFragments - If this pattern refers to any pattern
973/// fragments, inline them into place, giving us a pattern without any
974/// PatFrag references.
975TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
976 if (isLeaf()) return this; // nothing to do.
977 Record *Op = getOperator();
978
979 if (!Op->isSubClassOf("PatFrag")) {
980 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000981 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
982 TreePatternNode *Child = getChild(i);
983 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
984
985 assert((Child->getPredicateFns().empty() ||
986 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
987 "Non-empty child predicate clobbered!");
988
989 setChild(i, NewChild);
990 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000991 return this;
992 }
993
994 // Otherwise, we found a reference to a fragment. First, look up its
995 // TreePattern record.
996 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
997
998 // Verify that we are passing the right number of operands.
999 if (Frag->getNumArgs() != Children.size())
1000 TP.error("'" + Op->getName() + "' fragment requires " +
1001 utostr(Frag->getNumArgs()) + " operands!");
1002
1003 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1004
Dan Gohman0540e172008-10-15 06:17:21 +00001005 std::string Code = Op->getValueAsCode("Predicate");
1006 if (!Code.empty())
1007 FragTree->addPredicateFn("Predicate_"+Op->getName());
1008
Chris Lattner6cefb772008-01-05 22:25:12 +00001009 // Resolve formal arguments to their actual value.
1010 if (Frag->getNumArgs()) {
1011 // Compute the map of formal to actual arguments.
1012 std::map<std::string, TreePatternNode*> ArgMap;
1013 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1014 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1015
1016 FragTree->SubstituteFormalArguments(ArgMap);
1017 }
1018
1019 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001020 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1021 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +00001022
1023 // Transfer in the old predicates.
1024 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1025 FragTree->addPredicateFn(getPredicateFns()[i]);
1026
Chris Lattner6cefb772008-01-05 22:25:12 +00001027 // Get a new copy of this fragment to stitch into here.
1028 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +00001029
1030 // The fragment we inlined could have recursive inlining that is needed. See
1031 // if there are any pattern fragments in it and inline them as needed.
1032 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001033}
1034
1035/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +00001036/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +00001037/// references from the register file information, for example.
1038///
Chris Lattnerd7349192010-03-19 21:37:09 +00001039static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1040 bool NotRegisters, TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001041 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00001042 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001043 assert(ResNo == 0 && "Regclass ref only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001044 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001045 return EEVT::TypeSet(); // Unknown.
1046 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1047 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001048 }
1049
1050 if (R->isSubClassOf("PatFrag")) {
1051 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001052 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001053 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001054 }
1055
1056 if (R->isSubClassOf("Register")) {
1057 assert(ResNo == 0 && "Registers only produce one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001058 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001059 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001060 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001061 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001062 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00001063
1064 if (R->isSubClassOf("SubRegIndex")) {
1065 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1066 return EEVT::TypeSet();
1067 }
Chris Lattner640a3f52010-03-23 23:50:31 +00001068
1069 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1070 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001071 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001072 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001073 }
1074
1075 if (R->isSubClassOf("ComplexPattern")) {
1076 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001077 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001078 return EEVT::TypeSet(); // Unknown.
1079 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1080 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001081 }
1082 if (R->isSubClassOf("PointerLikeRegClass")) {
1083 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001084 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001085 }
1086
1087 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1088 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001089 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001090 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001091 }
1092
1093 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001094 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001095}
1096
Chris Lattnere67bde52008-01-06 05:36:50 +00001097
1098/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1099/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1100const CodeGenIntrinsic *TreePatternNode::
1101getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1102 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1103 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1104 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1105 return 0;
1106
1107 unsigned IID =
1108 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1109 return &CDP.getIntrinsicInfo(IID);
1110}
1111
Chris Lattner47661322010-02-14 22:22:58 +00001112/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1113/// return the ComplexPattern information, otherwise return null.
1114const ComplexPattern *
1115TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1116 if (!isLeaf()) return 0;
1117
1118 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1119 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1120 return &CGP.getComplexPattern(DI->getDef());
1121 return 0;
1122}
1123
1124/// NodeHasProperty - Return true if this node has the specified property.
1125bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001126 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001127 if (isLeaf()) {
1128 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1129 return CP->hasProperty(Property);
1130 return false;
1131 }
1132
1133 Record *Operator = getOperator();
1134 if (!Operator->isSubClassOf("SDNode")) return false;
1135
1136 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1137}
1138
1139
1140
1141
1142/// TreeHasProperty - Return true if any node in this tree has the specified
1143/// property.
1144bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001145 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001146 if (NodeHasProperty(Property, CGP))
1147 return true;
1148 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1149 if (getChild(i)->TreeHasProperty(Property, CGP))
1150 return true;
1151 return false;
1152}
1153
Evan Cheng6bd95672008-06-16 20:29:38 +00001154/// isCommutativeIntrinsic - Return true if the node corresponds to a
1155/// commutative intrinsic.
1156bool
1157TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1158 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1159 return Int->isCommutative;
1160 return false;
1161}
1162
Chris Lattnere67bde52008-01-06 05:36:50 +00001163
Bob Wilson6c01ca92009-01-05 17:23:09 +00001164/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001165/// this node and its children in the tree. This returns true if it makes a
1166/// change, false otherwise. If a type contradiction is found, throw an
1167/// exception.
1168bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001169 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001170 if (isLeaf()) {
1171 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1172 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001173 bool MadeChange = false;
1174 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1175 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1176 NotRegisters, TP), TP);
1177 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001178 }
1179
1180 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001181 assert(Types.size() == 1 && "Invalid IntInit");
Chris Lattner6cefb772008-01-05 22:25:12 +00001182
Chris Lattnerd7349192010-03-19 21:37:09 +00001183 // Int inits are always integers. :)
1184 bool MadeChange = Types[0].EnforceInteger(TP);
1185
1186 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001187 return MadeChange;
1188
Chris Lattnerd7349192010-03-19 21:37:09 +00001189 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001190 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1191 return MadeChange;
1192
1193 unsigned Size = EVT(VT).getSizeInBits();
1194 // Make sure that the value is representable for this type.
1195 if (Size >= 32) return MadeChange;
1196
1197 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1198 if (Val == II->getValue()) return MadeChange;
1199
1200 // If sign-extended doesn't fit, does it fit as unsigned?
1201 unsigned ValueMask;
1202 unsigned UnsignedVal;
1203 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1204 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001205
Chris Lattner2cacec52010-03-15 06:00:16 +00001206 if ((ValueMask & UnsignedVal) == UnsignedVal)
1207 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001208
Chris Lattner2cacec52010-03-15 06:00:16 +00001209 TP.error("Integer value '" + itostr(II->getValue())+
Chris Lattnerd7349192010-03-19 21:37:09 +00001210 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001211 return MadeChange;
1212 }
1213 return false;
1214 }
1215
1216 // special handling for set, which isn't really an SDNode.
1217 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001218 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1219 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001220 unsigned NC = getNumChildren();
Chris Lattnerd7349192010-03-19 21:37:09 +00001221
1222 TreePatternNode *SetVal = getChild(NC-1);
1223 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1224
Chris Lattner6cefb772008-01-05 22:25:12 +00001225 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001226 TreePatternNode *Child = getChild(i);
1227 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001228
1229 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001230 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1231 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001232 }
1233 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001234 }
1235
Chris Lattner310adf12010-03-27 02:53:27 +00001236 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001237 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1238
Chris Lattner6cefb772008-01-05 22:25:12 +00001239 bool MadeChange = false;
1240 for (unsigned i = 0; i < getNumChildren(); ++i)
1241 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001242 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001243 }
1244
1245 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001246 bool MadeChange = false;
1247 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1248 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner2cacec52010-03-15 06:00:16 +00001249
Chris Lattnerd7349192010-03-19 21:37:09 +00001250 assert(getChild(0)->getNumTypes() == 1 &&
1251 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1252
Chris Lattner2cacec52010-03-15 06:00:16 +00001253 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1254 // what type it gets, so if it didn't get a concrete type just give it the
1255 // first viable type from the reg class.
Chris Lattnerd7349192010-03-19 21:37:09 +00001256 if (!getChild(1)->hasTypeSet(0) &&
1257 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1258 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1259 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001260 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001261 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001262 }
1263
1264 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001265 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001266
Chris Lattner6cefb772008-01-05 22:25:12 +00001267 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001268 unsigned NumRetVTs = Int->IS.RetVTs.size();
1269 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Chris Lattnerd7349192010-03-19 21:37:09 +00001270
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001271 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001272 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001273
Chris Lattnerd7349192010-03-19 21:37:09 +00001274 if (getNumChildren() != NumParamVTs + 1)
Chris Lattnere67bde52008-01-06 05:36:50 +00001275 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001276 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001277 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001278
1279 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001280 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001281
Chris Lattnerd7349192010-03-19 21:37:09 +00001282 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1283 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1284
1285 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1286 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1287 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001288 }
1289 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001290 }
1291
1292 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001293 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1294
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001295 // Check that the number of operands is sane. Negative operands -> varargs.
1296 if (NI.getNumOperands() >= 0 &&
1297 getNumChildren() != (unsigned)NI.getNumOperands())
1298 TP.error(getOperator()->getName() + " node requires exactly " +
1299 itostr(NI.getNumOperands()) + " operands!");
1300
Chris Lattner6cefb772008-01-05 22:25:12 +00001301 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1302 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1303 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001304 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001305 }
1306
1307 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001308 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001309 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001310 CDP.getTargetInfo().getInstruction(getOperator());
Chris Lattner6c6ba362010-03-18 23:15:10 +00001311
Chris Lattner0be6fe72010-03-27 19:15:02 +00001312 bool MadeChange = false;
1313
1314 // Apply the result types to the node, these come from the things in the
1315 // (outs) list of the instruction.
1316 // FIXME: Cap at one result so far.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001317 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001318 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1319 Record *ResultNode = Inst.getResult(ResNo);
Chris Lattner6cefb772008-01-05 22:25:12 +00001320
Chris Lattnera938ac62009-07-29 20:43:05 +00001321 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001322 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001323 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001324 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001325 } else {
1326 assert(ResultNode->isSubClassOf("RegisterClass") &&
1327 "Operands should be register classes!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001328 const CodeGenRegisterClass &RC =
1329 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001330 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001331 }
Chris Lattner0be6fe72010-03-27 19:15:02 +00001332 }
1333
1334 // If the instruction has implicit defs, we apply the first one as a result.
1335 // FIXME: This sucks, it should apply all implicit defs.
1336 if (!InstInfo.ImplicitDefs.empty()) {
1337 unsigned ResNo = NumResultsToAdd;
1338
Chris Lattner9414ae52010-03-27 20:09:24 +00001339 // FIXME: Generalize to multiple possible types and multiple possible
1340 // ImplicitDefs.
1341 MVT::SimpleValueType VT =
1342 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1343
1344 if (VT != MVT::Other)
1345 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001346 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001347
1348 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1349 // be the same.
1350 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001351 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1352 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1353 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001354 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001355
1356 unsigned ChildNo = 0;
1357 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1358 Record *OperandNode = Inst.getOperand(i);
1359
1360 // If the instruction expects a predicate or optional def operand, we
1361 // codegen this by setting the operand to it's default value if it has a
1362 // non-empty DefaultOps field.
1363 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1364 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1365 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1366 continue;
1367
1368 // Verify that we didn't run out of provided operands.
1369 if (ChildNo >= getNumChildren())
1370 TP.error("Instruction '" + getOperator()->getName() +
1371 "' expects more operands than were provided.");
1372
Owen Anderson825b72b2009-08-11 20:47:22 +00001373 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001374 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001375 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Chris Lattnerd7349192010-03-19 21:37:09 +00001376
Chris Lattner6cefb772008-01-05 22:25:12 +00001377 if (OperandNode->isSubClassOf("RegisterClass")) {
1378 const CodeGenRegisterClass &RC =
1379 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001380 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001381 } else if (OperandNode->isSubClassOf("Operand")) {
1382 VT = getValueType(OperandNode->getValueAsDef("Type"));
Chris Lattner0be6fe72010-03-27 19:15:02 +00001383 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001384 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner0be6fe72010-03-27 19:15:02 +00001385 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001386 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001387 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001388 } else {
1389 assert(0 && "Unknown operand type!");
1390 abort();
1391 }
1392 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1393 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001394
Christopher Lamb02f69372008-03-10 04:16:09 +00001395 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001396 TP.error("Instruction '" + getOperator()->getName() +
1397 "' was provided too many operands!");
1398
1399 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001400 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001401
1402 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1403
1404 // Node transforms always take one operand.
1405 if (getNumChildren() != 1)
1406 TP.error("Node transform '" + getOperator()->getName() +
1407 "' requires one operand!");
1408
Chris Lattner2cacec52010-03-15 06:00:16 +00001409 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1410
1411
Chris Lattner6eb30122010-02-23 05:51:07 +00001412 // If either the output or input of the xform does not have exact
1413 // type info. We assume they must be the same. Otherwise, it is perfectly
1414 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001415#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001416 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001417 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1418 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001419 return MadeChange;
1420 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001421#endif
1422 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001423}
1424
1425/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1426/// RHS of a commutative operation, not the on LHS.
1427static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1428 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1429 return true;
1430 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1431 return true;
1432 return false;
1433}
1434
1435
1436/// canPatternMatch - If it is impossible for this pattern to match on this
1437/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001438/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001439/// that can never possibly work), and to prevent the pattern permuter from
1440/// generating stuff that is useless.
1441bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001442 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001443 if (isLeaf()) return true;
1444
1445 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1446 if (!getChild(i)->canPatternMatch(Reason, CDP))
1447 return false;
1448
1449 // If this is an intrinsic, handle cases that would make it not match. For
1450 // example, if an operand is required to be an immediate.
1451 if (getOperator()->isSubClassOf("Intrinsic")) {
1452 // TODO:
1453 return true;
1454 }
1455
1456 // If this node is a commutative operator, check that the LHS isn't an
1457 // immediate.
1458 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001459 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1460 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001461 // Scan all of the operands of the node and make sure that only the last one
1462 // is a constant node, unless the RHS also is.
1463 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001464 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1465 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001466 if (OnlyOnRHSOfCommutative(getChild(i))) {
1467 Reason="Immediate value must be on the RHS of commutative operators!";
1468 return false;
1469 }
1470 }
1471 }
1472
1473 return true;
1474}
1475
1476//===----------------------------------------------------------------------===//
1477// TreePattern implementation
1478//
1479
1480TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001481 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001482 isInputPattern = isInput;
1483 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattnerc2173052010-03-28 06:50:34 +00001484 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001485}
1486
1487TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001488 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001489 isInputPattern = isInput;
Chris Lattnerc2173052010-03-28 06:50:34 +00001490 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001491}
1492
1493TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001494 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001495 isInputPattern = isInput;
1496 Trees.push_back(Pat);
1497}
1498
Chris Lattner6cefb772008-01-05 22:25:12 +00001499void TreePattern::error(const std::string &Msg) const {
1500 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001501 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001502}
1503
Chris Lattner2cacec52010-03-15 06:00:16 +00001504void TreePattern::ComputeNamedNodes() {
1505 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1506 ComputeNamedNodes(Trees[i]);
1507}
1508
1509void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1510 if (!N->getName().empty())
1511 NamedNodes[N->getName()].push_back(N);
1512
1513 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1514 ComputeNamedNodes(N->getChild(i));
1515}
1516
Chris Lattnerd7349192010-03-19 21:37:09 +00001517
Chris Lattnerc2173052010-03-28 06:50:34 +00001518TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1519 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
1520 Record *R = DI->getDef();
1521
1522 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1523 // TreePatternNode if its own. For example:
1524 /// (foo GPR, imm) -> (foo GPR, (imm))
1525 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1526 return ParseTreePattern(new DagInit(DI, "",
1527 std::vector<std::pair<Init*, std::string> >()),
1528 OpName);
1529
1530 // Input argument?
1531 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001532 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001533 if (OpName.empty())
1534 error("'node' argument requires a name to match with operand list");
1535 Args.push_back(OpName);
1536 }
1537
1538 Res->setName(OpName);
1539 return Res;
1540 }
1541
1542 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
1543 if (!OpName.empty())
1544 error("Constant int argument should not have a name!");
1545 return new TreePatternNode(II, 1);
1546 }
1547
1548 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
1549 // Turn this into an IntInit.
1550 Init *II = BI->convertInitializerTo(new IntRecTy());
1551 if (II == 0 || !dynamic_cast<IntInit*>(II))
1552 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001553 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00001554 }
1555
1556 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
1557 if (!Dag) {
1558 TheInit->dump();
1559 error("Pattern has unexpected init kind!");
1560 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001561 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1562 if (!OpDef) error("Pattern has unexpected operator type!");
1563 Record *Operator = OpDef->getDef();
1564
1565 if (Operator->isSubClassOf("ValueType")) {
1566 // If the operator is a ValueType, then this must be "type cast" of a leaf
1567 // node.
1568 if (Dag->getNumArgs() != 1)
1569 error("Type cast only takes one operand!");
1570
Chris Lattnerc2173052010-03-28 06:50:34 +00001571 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001572
1573 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001574 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1575 New->UpdateNodeType(0, getValueType(Operator), *this);
Chris Lattnerc2173052010-03-28 06:50:34 +00001576
1577 if (!OpName.empty())
1578 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001579 return New;
1580 }
1581
1582 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001583 if (!Operator->isSubClassOf("PatFrag") &&
1584 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001585 !Operator->isSubClassOf("Instruction") &&
1586 !Operator->isSubClassOf("SDNodeXForm") &&
1587 !Operator->isSubClassOf("Intrinsic") &&
1588 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001589 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001590 error("Unrecognized node '" + Operator->getName() + "'!");
1591
1592 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001593 if (isInputPattern) {
1594 if (Operator->isSubClassOf("Instruction") ||
1595 Operator->isSubClassOf("SDNodeXForm"))
1596 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1597 } else {
1598 if (Operator->isSubClassOf("Intrinsic"))
1599 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1600
1601 if (Operator->isSubClassOf("SDNode") &&
1602 Operator->getName() != "imm" &&
1603 Operator->getName() != "fpimm" &&
1604 Operator->getName() != "tglobaltlsaddr" &&
1605 Operator->getName() != "tconstpool" &&
1606 Operator->getName() != "tjumptable" &&
1607 Operator->getName() != "tframeindex" &&
1608 Operator->getName() != "texternalsym" &&
1609 Operator->getName() != "tblockaddress" &&
1610 Operator->getName() != "tglobaladdr" &&
1611 Operator->getName() != "bb" &&
1612 Operator->getName() != "vt")
1613 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1614 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001615
1616 std::vector<TreePatternNode*> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00001617
1618 // Parse all the operands.
1619 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1620 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001621
1622 // If the operator is an intrinsic, then this is just syntactic sugar for for
1623 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1624 // convert the intrinsic name to a number.
1625 if (Operator->isSubClassOf("Intrinsic")) {
1626 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1627 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1628
1629 // If this intrinsic returns void, it must have side-effects and thus a
1630 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00001631 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001632 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001633 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00001634 // Has side-effects, requires chain.
1635 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001636 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00001637 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Chris Lattner6cefb772008-01-05 22:25:12 +00001638
Chris Lattnerd7349192010-03-19 21:37:09 +00001639 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001640 Children.insert(Children.begin(), IIDNode);
1641 }
1642
Chris Lattnerd7349192010-03-19 21:37:09 +00001643 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1644 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00001645 Result->setName(OpName);
1646
1647 if (!Dag->getName().empty()) {
1648 assert(Result->getName().empty());
1649 Result->setName(Dag->getName());
1650 }
Nate Begeman7cee8172009-03-19 05:21:56 +00001651 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001652}
1653
Chris Lattner7a0eb912010-03-28 08:38:32 +00001654/// SimplifyTree - See if we can simplify this tree to eliminate something that
1655/// will never match in favor of something obvious that will. This is here
1656/// strictly as a convenience to target authors because it allows them to write
1657/// more type generic things and have useless type casts fold away.
1658///
1659/// This returns true if any change is made.
1660static bool SimplifyTree(TreePatternNode *&N) {
1661 if (N->isLeaf())
1662 return false;
1663
1664 // If we have a bitconvert with a resolved type and if the source and
1665 // destination types are the same, then the bitconvert is useless, remove it.
1666 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattner7a0eb912010-03-28 08:38:32 +00001667 N->getExtType(0).isConcrete() &&
1668 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1669 N->getName().empty()) {
1670 N = N->getChild(0);
1671 SimplifyTree(N);
1672 return true;
1673 }
1674
1675 // Walk all children.
1676 bool MadeChange = false;
1677 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1678 TreePatternNode *Child = N->getChild(i);
1679 MadeChange |= SimplifyTree(Child);
1680 N->setChild(i, Child);
1681 }
1682 return MadeChange;
1683}
1684
1685
1686
Chris Lattner6cefb772008-01-05 22:25:12 +00001687/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001688/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001689/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001690bool TreePattern::
1691InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1692 if (NamedNodes.empty())
1693 ComputeNamedNodes();
1694
Chris Lattner6cefb772008-01-05 22:25:12 +00001695 bool MadeChange = true;
1696 while (MadeChange) {
1697 MadeChange = false;
Chris Lattner7a0eb912010-03-28 08:38:32 +00001698 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001699 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner7a0eb912010-03-28 08:38:32 +00001700 MadeChange |= SimplifyTree(Trees[i]);
1701 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001702
1703 // If there are constraints on our named nodes, apply them.
1704 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1705 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1706 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1707
1708 // If we have input named node types, propagate their types to the named
1709 // values here.
1710 if (InNamedTypes) {
1711 // FIXME: Should be error?
1712 assert(InNamedTypes->count(I->getKey()) &&
1713 "Named node in output pattern but not input pattern?");
1714
1715 const SmallVectorImpl<TreePatternNode*> &InNodes =
1716 InNamedTypes->find(I->getKey())->second;
1717
1718 // The input types should be fully resolved by now.
1719 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1720 // If this node is a register class, and it is the root of the pattern
1721 // then we're mapping something onto an input register. We allow
1722 // changing the type of the input register in this case. This allows
1723 // us to match things like:
1724 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1725 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1726 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1727 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1728 continue;
1729 }
1730
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001731 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001732 InNodes[0]->getNumTypes() == 1 &&
1733 "FIXME: cannot name multiple result nodes yet");
1734 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1735 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001736 }
1737 }
1738
1739 // If there are multiple nodes with the same name, they must all have the
1740 // same type.
1741 if (I->second.size() > 1) {
1742 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001743 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00001744 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00001745 "FIXME: cannot name multiple result nodes yet");
1746
1747 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1748 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00001749 }
1750 }
1751 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001752 }
1753
1754 bool HasUnresolvedTypes = false;
1755 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1756 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1757 return !HasUnresolvedTypes;
1758}
1759
Daniel Dunbar1a551802009-07-03 00:10:29 +00001760void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001761 OS << getRecord()->getName();
1762 if (!Args.empty()) {
1763 OS << "(" << Args[0];
1764 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1765 OS << ", " << Args[i];
1766 OS << ")";
1767 }
1768 OS << ": ";
1769
1770 if (Trees.size() > 1)
1771 OS << "[\n";
1772 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1773 OS << "\t";
1774 Trees[i]->print(OS);
1775 OS << "\n";
1776 }
1777
1778 if (Trees.size() > 1)
1779 OS << "]\n";
1780}
1781
Daniel Dunbar1a551802009-07-03 00:10:29 +00001782void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001783
1784//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001785// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001786//
1787
Chris Lattner67db8832010-12-13 00:23:57 +00001788CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
1789 Records(R), Target(R) {
1790
Dale Johannesen49de9822009-02-05 01:49:45 +00001791 Intrinsics = LoadIntrinsics(Records, false);
1792 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001793 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001794 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001795 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001796 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001797 ParseDefaultOperands();
1798 ParseInstructions();
1799 ParsePatterns();
1800
1801 // Generate variants. For example, commutative patterns can match
1802 // multiple ways. Add them to PatternsToMatch as well.
1803 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001804
1805 // Infer instruction flags. For example, we can detect loads,
1806 // stores, and side effects in many cases by examining an
1807 // instruction's pattern.
1808 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001809}
1810
Chris Lattnerfe718932008-01-06 01:10:31 +00001811CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001812 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001813 E = PatternFragments.end(); I != E; ++I)
1814 delete I->second;
1815}
1816
1817
Chris Lattnerfe718932008-01-06 01:10:31 +00001818Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001819 Record *N = Records.getDef(Name);
1820 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001821 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001822 exit(1);
1823 }
1824 return N;
1825}
1826
1827// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001828void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001829 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1830 while (!Nodes.empty()) {
1831 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1832 Nodes.pop_back();
1833 }
1834
Jim Grosbachda4231f2009-03-26 16:17:51 +00001835 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001836 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1837 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1838 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1839}
1840
1841/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1842/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001843void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001844 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1845 while (!Xforms.empty()) {
1846 Record *XFormNode = Xforms.back();
1847 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1848 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001849 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001850
1851 Xforms.pop_back();
1852 }
1853}
1854
Chris Lattnerfe718932008-01-06 01:10:31 +00001855void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001856 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1857 while (!AMs.empty()) {
1858 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1859 AMs.pop_back();
1860 }
1861}
1862
1863
1864/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1865/// file, building up the PatternFragments map. After we've collected them all,
1866/// inline fragments together as necessary, so that there are no references left
1867/// inside a pattern fragment to a pattern fragment.
1868///
Chris Lattnerfe718932008-01-06 01:10:31 +00001869void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001870 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1871
Chris Lattnerdc32f982008-01-05 22:43:57 +00001872 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001873 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1874 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1875 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1876 PatternFragments[Fragments[i]] = P;
1877
Chris Lattnerdc32f982008-01-05 22:43:57 +00001878 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001879 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001880 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001881
Chris Lattnerdc32f982008-01-05 22:43:57 +00001882 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001883 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1884
1885 // Parse the operands list.
1886 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1887 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1888 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001889 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001890 if (!OpsOp ||
1891 (OpsOp->getDef()->getName() != "ops" &&
1892 OpsOp->getDef()->getName() != "outs" &&
1893 OpsOp->getDef()->getName() != "ins"))
1894 P->error("Operands list should start with '(ops ... '!");
1895
1896 // Copy over the arguments.
1897 Args.clear();
1898 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1899 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1900 static_cast<DefInit*>(OpsList->getArg(j))->
1901 getDef()->getName() != "node")
1902 P->error("Operands list should all be 'node' values.");
1903 if (OpsList->getArgName(j).empty())
1904 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001905 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001906 P->error("'" + OpsList->getArgName(j) +
1907 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001908 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001909 Args.push_back(OpsList->getArgName(j));
1910 }
1911
Chris Lattnerdc32f982008-01-05 22:43:57 +00001912 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001913 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001914 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001915
Chris Lattnerdc32f982008-01-05 22:43:57 +00001916 // If there is a code init for this fragment, keep track of the fact that
1917 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001918 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001919 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001920 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001921
1922 // If there is a node transformation corresponding to this, keep track of
1923 // it.
1924 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1925 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1926 P->getOnlyTree()->setTransformFn(Transform);
1927 }
1928
Chris Lattner6cefb772008-01-05 22:25:12 +00001929 // Now that we've parsed all of the tree fragments, do a closure on them so
1930 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001931 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1932 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001933 ThePat->InlinePatternFragments();
1934
1935 // Infer as many types as possible. Don't worry about it if we don't infer
1936 // all of them, some may depend on the inputs of the pattern.
1937 try {
1938 ThePat->InferAllTypes();
1939 } catch (...) {
1940 // If this pattern fragment is not supported by this target (no types can
1941 // satisfy its constraints), just ignore it. If the bogus pattern is
1942 // actually used by instructions, the type consistency error will be
1943 // reported there.
1944 }
1945
1946 // If debugging, print out the pattern fragment result.
1947 DEBUG(ThePat->dump());
1948 }
1949}
1950
Chris Lattnerfe718932008-01-06 01:10:31 +00001951void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001952 std::vector<Record*> DefaultOps[2];
1953 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1954 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1955
1956 // Find some SDNode.
1957 assert(!SDNodes.empty() && "No SDNodes parsed?");
1958 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1959
1960 for (unsigned iter = 0; iter != 2; ++iter) {
1961 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1962 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1963
1964 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1965 // SomeSDnode so that we can parse this.
1966 std::vector<std::pair<Init*, std::string> > Ops;
1967 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1968 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1969 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001970 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001971
1972 // Create a TreePattern to parse this.
1973 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1974 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1975
1976 // Copy the operands over into a DAGDefaultOperand.
1977 DAGDefaultOperand DefaultOpInfo;
1978
1979 TreePatternNode *T = P.getTree(0);
1980 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1981 TreePatternNode *TPN = T->getChild(op);
1982 while (TPN->ApplyTypeConstraints(P, false))
1983 /* Resolve all types */;
1984
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001985 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001986 if (iter == 0)
1987 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001988 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00001989 else
1990 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001991 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001992 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001993 DefaultOpInfo.DefaultOps.push_back(TPN);
1994 }
1995
1996 // Insert it into the DefaultOperands map so we can find it later.
1997 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1998 }
1999 }
2000}
2001
2002/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2003/// instruction input. Return true if this is a real use.
2004static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002005 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002006 // No name -> not interesting.
2007 if (Pat->getName().empty()) {
2008 if (Pat->isLeaf()) {
2009 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2010 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
2011 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002012 }
2013 return false;
2014 }
2015
2016 Record *Rec;
2017 if (Pat->isLeaf()) {
2018 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2019 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2020 Rec = DI->getDef();
2021 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00002022 Rec = Pat->getOperator();
2023 }
2024
2025 // SRCVALUE nodes are ignored.
2026 if (Rec->getName() == "srcvalue")
2027 return false;
2028
2029 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2030 if (!Slot) {
2031 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00002032 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00002033 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00002034 Record *SlotRec;
2035 if (Slot->isLeaf()) {
2036 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
2037 } else {
2038 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2039 SlotRec = Slot->getOperator();
2040 }
2041
2042 // Ensure that the inputs agree if we've already seen this input.
2043 if (Rec != SlotRec)
2044 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00002045 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00002046 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00002047 return true;
2048}
2049
2050/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2051/// part of "I", the instruction), computing the set of inputs and outputs of
2052/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00002053void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00002054FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2055 std::map<std::string, TreePatternNode*> &InstInputs,
2056 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner6cefb772008-01-05 22:25:12 +00002057 std::vector<Record*> &InstImpResults) {
2058 if (Pat->isLeaf()) {
Chris Lattneracfb70f2010-04-20 06:30:25 +00002059 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002060 if (!isUse && Pat->getTransformFn())
2061 I->error("Cannot specify a transform function for a non-input value!");
2062 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002063 }
2064
2065 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002066 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2067 TreePatternNode *Dest = Pat->getChild(i);
2068 if (!Dest->isLeaf())
2069 I->error("implicitly defined value should be a register!");
2070
2071 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2072 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2073 I->error("implicitly defined value should be a register!");
2074 InstImpResults.push_back(Val->getDef());
2075 }
2076 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002077 }
2078
2079 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002080 // If this is not a set, verify that the children nodes are not void typed,
2081 // and recurse.
2082 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002083 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002084 I->error("Cannot have void nodes inside of patterns!");
2085 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002086 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002087 }
2088
2089 // If this is a non-leaf node with no children, treat it basically as if
2090 // it were a leaf. This handles nodes like (imm).
Chris Lattneracfb70f2010-04-20 06:30:25 +00002091 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002092
2093 if (!isUse && Pat->getTransformFn())
2094 I->error("Cannot specify a transform function for a non-input value!");
2095 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002096 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002097
2098 // Otherwise, this is a set, validate and collect instruction results.
2099 if (Pat->getNumChildren() == 0)
2100 I->error("set requires operands!");
2101
2102 if (Pat->getTransformFn())
2103 I->error("Cannot specify a transform function on a set node!");
2104
2105 // Check the set destinations.
2106 unsigned NumDests = Pat->getNumChildren()-1;
2107 for (unsigned i = 0; i != NumDests; ++i) {
2108 TreePatternNode *Dest = Pat->getChild(i);
2109 if (!Dest->isLeaf())
2110 I->error("set destination should be a register!");
2111
2112 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2113 if (!Val)
2114 I->error("set destination should be a register!");
2115
2116 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002117 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002118 if (Dest->getName().empty())
2119 I->error("set destination must have a name!");
2120 if (InstResults.count(Dest->getName()))
2121 I->error("cannot set '" + Dest->getName() +"' multiple times");
2122 InstResults[Dest->getName()] = Dest;
2123 } else if (Val->getDef()->isSubClassOf("Register")) {
2124 InstImpResults.push_back(Val->getDef());
2125 } else {
2126 I->error("set destination should be a register!");
2127 }
2128 }
2129
2130 // Verify and collect info from the computation.
2131 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattneracfb70f2010-04-20 06:30:25 +00002132 InstInputs, InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002133}
2134
Dan Gohmanee4fa192008-04-03 00:02:49 +00002135//===----------------------------------------------------------------------===//
2136// Instruction Analysis
2137//===----------------------------------------------------------------------===//
2138
2139class InstAnalyzer {
2140 const CodeGenDAGPatterns &CDP;
2141 bool &mayStore;
2142 bool &mayLoad;
2143 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002144 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002145public:
2146 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Chris Lattner1e506312010-03-19 05:34:15 +00002147 bool &maystore, bool &mayload, bool &hse, bool &isv)
2148 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
2149 IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002150 }
2151
2152 /// Analyze - Analyze the specified instruction, returning true if the
2153 /// instruction had a pattern.
2154 bool Analyze(Record *InstRecord) {
2155 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2156 if (Pattern == 0) {
2157 HasSideEffects = 1;
2158 return false; // No pattern.
2159 }
2160
2161 // FIXME: Assume only the first tree is the pattern. The others are clobber
2162 // nodes.
2163 AnalyzeNode(Pattern->getTree(0));
2164 return true;
2165 }
2166
2167private:
2168 void AnalyzeNode(const TreePatternNode *N) {
2169 if (N->isLeaf()) {
2170 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2171 Record *LeafRec = DI->getDef();
2172 // Handle ComplexPattern leaves.
2173 if (LeafRec->isSubClassOf("ComplexPattern")) {
2174 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2175 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2176 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2177 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2178 }
2179 }
2180 return;
2181 }
2182
2183 // Analyze children.
2184 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2185 AnalyzeNode(N->getChild(i));
2186
2187 // Ignore set nodes, which are not SDNodes.
2188 if (N->getOperator()->getName() == "set")
2189 return;
2190
2191 // Get information about the SDNode for the operator.
2192 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2193
2194 // Notice properties of the node.
2195 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2196 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2197 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002198 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002199
2200 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2201 // If this is an intrinsic, analyze it.
2202 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2203 mayLoad = true;// These may load memory.
2204
Dan Gohman7365c092010-08-05 23:36:21 +00002205 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002206 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2207
Dan Gohman7365c092010-08-05 23:36:21 +00002208 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002209 // WriteMem intrinsics can have other strange effects.
2210 HasSideEffects = true;
2211 }
2212 }
2213
2214};
2215
2216static void InferFromPattern(const CodeGenInstruction &Inst,
2217 bool &MayStore, bool &MayLoad,
Chris Lattner1e506312010-03-19 05:34:15 +00002218 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002219 const CodeGenDAGPatterns &CDP) {
Chris Lattner1e506312010-03-19 05:34:15 +00002220 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002221
2222 bool HadPattern =
Chris Lattner1e506312010-03-19 05:34:15 +00002223 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2224 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002225
2226 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2227 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2228 // If we decided that this is a store from the pattern, then the .td file
2229 // entry is redundant.
2230 if (MayStore)
2231 fprintf(stderr,
2232 "Warning: mayStore flag explicitly set on instruction '%s'"
2233 " but flag already inferred from pattern.\n",
2234 Inst.TheDef->getName().c_str());
2235 MayStore = true;
2236 }
2237
2238 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2239 // If we decided that this is a load from the pattern, then the .td file
2240 // entry is redundant.
2241 if (MayLoad)
2242 fprintf(stderr,
2243 "Warning: mayLoad flag explicitly set on instruction '%s'"
2244 " but flag already inferred from pattern.\n",
2245 Inst.TheDef->getName().c_str());
2246 MayLoad = true;
2247 }
2248
2249 if (Inst.neverHasSideEffects) {
2250 if (HadPattern)
2251 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2252 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2253 HasSideEffects = false;
2254 }
2255
2256 if (Inst.hasSideEffects) {
2257 if (HasSideEffects)
2258 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2259 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2260 HasSideEffects = true;
2261 }
Chris Lattner1e506312010-03-19 05:34:15 +00002262
Chris Lattnerc240bb02010-11-01 04:03:32 +00002263 if (Inst.Operands.isVariadic)
Chris Lattner1e506312010-03-19 05:34:15 +00002264 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002265}
2266
Chris Lattner6cefb772008-01-05 22:25:12 +00002267/// ParseInstructions - Parse all of the instructions, inlining and resolving
2268/// any fragments involved. This populates the Instructions list with fully
2269/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002270void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002271 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2272
2273 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2274 ListInit *LI = 0;
2275
2276 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2277 LI = Instrs[i]->getValueAsListInit("Pattern");
2278
2279 // If there is no pattern, only collect minimal information about the
2280 // instruction for its operand list. We have to assume that there is one
2281 // result, as we have no detailed info.
2282 if (!LI || LI->getSize() == 0) {
2283 std::vector<Record*> Results;
2284 std::vector<Record*> Operands;
2285
Chris Lattnerf30187a2010-03-19 00:07:20 +00002286 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002287
Chris Lattnerc240bb02010-11-01 04:03:32 +00002288 if (InstInfo.Operands.size() != 0) {
2289 if (InstInfo.Operands.NumDefs == 0) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002290 // These produce no results
Chris Lattnerc240bb02010-11-01 04:03:32 +00002291 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2292 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002293 } else {
2294 // Assume the first operand is the result.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002295 Results.push_back(InstInfo.Operands[0].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002296
2297 // The rest are inputs.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002298 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2299 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002300 }
2301 }
2302
2303 // Create and insert the instruction.
2304 std::vector<Record*> ImpResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00002305 Instructions.insert(std::make_pair(Instrs[i],
Chris Lattner62bcec82010-04-20 06:28:43 +00002306 DAGInstruction(0, Results, Operands, ImpResults)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002307 continue; // no pattern.
2308 }
2309
2310 // Parse the instruction.
2311 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2312 // Inline pattern fragments into it.
2313 I->InlinePatternFragments();
2314
2315 // Infer as many types as possible. If we cannot infer all of them, we can
2316 // never do anything with this instruction pattern: report it to the user.
2317 if (!I->InferAllTypes())
2318 I->error("Could not infer all types in pattern!");
2319
2320 // InstInputs - Keep track of all of the inputs of the instruction, along
2321 // with the record they are declared as.
2322 std::map<std::string, TreePatternNode*> InstInputs;
2323
2324 // InstResults - Keep track of all the virtual registers that are 'set'
2325 // in the instruction, including what reg class they are.
2326 std::map<std::string, TreePatternNode*> InstResults;
2327
Chris Lattner6cefb772008-01-05 22:25:12 +00002328 std::vector<Record*> InstImpResults;
2329
2330 // Verify that the top-level forms in the instruction are of void type, and
2331 // fill in the InstResults map.
2332 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2333 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002334 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002335 I->error("Top-level forms in instruction pattern should have"
2336 " void types");
2337
2338 // Find inputs and outputs, and verify the structure of the uses/defs.
2339 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002340 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002341 }
2342
2343 // Now that we have inputs and outputs of the pattern, inspect the operands
2344 // list for the instruction. This determines the order that operands are
2345 // added to the machine instruction the node corresponds to.
2346 unsigned NumResults = InstResults.size();
2347
2348 // Parse the operands list from the (ops) list, validating it.
2349 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002350 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002351
2352 // Check that all of the results occur first in the list.
2353 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002354 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002355 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00002356 if (i == CGI.Operands.size())
Chris Lattner6cefb772008-01-05 22:25:12 +00002357 I->error("'" + InstResults.begin()->first +
2358 "' set but does not appear in operand list!");
Chris Lattnerc240bb02010-11-01 04:03:32 +00002359 const std::string &OpName = CGI.Operands[i].Name;
Chris Lattner6cefb772008-01-05 22:25:12 +00002360
2361 // Check that it exists in InstResults.
2362 TreePatternNode *RNode = InstResults[OpName];
2363 if (RNode == 0)
2364 I->error("Operand $" + OpName + " does not exist in operand list!");
2365
2366 if (i == 0)
2367 Res0Node = RNode;
2368 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2369 if (R == 0)
2370 I->error("Operand $" + OpName + " should be a set destination: all "
2371 "outputs must occur before inputs in operand list!");
2372
Chris Lattnerc240bb02010-11-01 04:03:32 +00002373 if (CGI.Operands[i].Rec != R)
Chris Lattner6cefb772008-01-05 22:25:12 +00002374 I->error("Operand $" + OpName + " class mismatch!");
2375
2376 // Remember the return type.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002377 Results.push_back(CGI.Operands[i].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002378
2379 // Okay, this one checks out.
2380 InstResults.erase(OpName);
2381 }
2382
2383 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2384 // the copy while we're checking the inputs.
2385 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2386
2387 std::vector<TreePatternNode*> ResultNodeOperands;
2388 std::vector<Record*> Operands;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002389 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2390 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner6cefb772008-01-05 22:25:12 +00002391 const std::string &OpName = Op.Name;
2392 if (OpName.empty())
2393 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2394
2395 if (!InstInputsCheck.count(OpName)) {
2396 // If this is an predicate operand or optional def operand with an
2397 // DefaultOps set filled in, we can ignore this. When we codegen it,
2398 // we will do so as always executed.
2399 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2400 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2401 // Does it have a non-empty DefaultOps field? If so, ignore this
2402 // operand.
2403 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2404 continue;
2405 }
2406 I->error("Operand $" + OpName +
2407 " does not appear in the instruction pattern");
2408 }
2409 TreePatternNode *InVal = InstInputsCheck[OpName];
2410 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2411
2412 if (InVal->isLeaf() &&
2413 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2414 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2415 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2416 I->error("Operand $" + OpName + "'s register class disagrees"
2417 " between the operand and pattern");
2418 }
2419 Operands.push_back(Op.Rec);
2420
2421 // Construct the result for the dest-pattern operand list.
2422 TreePatternNode *OpNode = InVal->clone();
2423
2424 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002425 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002426
2427 // Promote the xform function to be an explicit node if set.
2428 if (Record *Xform = OpNode->getTransformFn()) {
2429 OpNode->setTransformFn(0);
2430 std::vector<TreePatternNode*> Children;
2431 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002432 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002433 }
2434
2435 ResultNodeOperands.push_back(OpNode);
2436 }
2437
2438 if (!InstInputsCheck.empty())
2439 I->error("Input operand $" + InstInputsCheck.begin()->first +
2440 " occurs in pattern but not in operands list!");
2441
2442 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002443 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2444 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002445 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002446 for (unsigned i = 0; i != NumResults; ++i)
2447 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002448
2449 // Create and insert the instruction.
Chris Lattneracfb70f2010-04-20 06:30:25 +00002450 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner62bcec82010-04-20 06:28:43 +00002451 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002452 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2453
2454 // Use a temporary tree pattern to infer all types and make sure that the
2455 // constructed result is correct. This depends on the instruction already
2456 // being inserted into the Instructions map.
2457 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002458 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002459
2460 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2461 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2462
2463 DEBUG(I->dump());
2464 }
2465
2466 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002467 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2468 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002469 E = Instructions.end(); II != E; ++II) {
2470 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002471 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002472 if (I == 0) continue; // No pattern.
2473
2474 // FIXME: Assume only the first tree is the pattern. The others are clobber
2475 // nodes.
2476 TreePatternNode *Pattern = I->getTree(0);
2477 TreePatternNode *SrcPattern;
2478 if (Pattern->getOperator()->getName() == "set") {
2479 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2480 } else{
2481 // Not a set (store or something?)
2482 SrcPattern = Pattern;
2483 }
2484
Chris Lattner6cefb772008-01-05 22:25:12 +00002485 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002486 AddPatternToMatch(I,
Jim Grosbach997759a2010-12-07 23:05:49 +00002487 PatternToMatch(Instr,
2488 Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002489 SrcPattern,
2490 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002491 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002492 Instr->getValueAsInt("AddedComplexity"),
2493 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002494 }
2495}
2496
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002497
2498typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2499
Chris Lattner967d54a2010-02-23 06:35:45 +00002500static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002501 std::map<std::string, NameRecord> &Names,
2502 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002503 if (!P->getName().empty()) {
2504 NameRecord &Rec = Names[P->getName()];
2505 // If this is the first instance of the name, remember the node.
2506 if (Rec.second++ == 0)
2507 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002508 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002509 PatternTop->error("repetition of value: $" + P->getName() +
2510 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002511 }
Chris Lattner967d54a2010-02-23 06:35:45 +00002512
2513 if (!P->isLeaf()) {
2514 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002515 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002516 }
2517}
2518
Chris Lattner25b6f912010-02-23 06:16:51 +00002519void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2520 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002521 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002522 std::string Reason;
2523 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002524 Pattern->error("Pattern can never match: " + Reason);
Chris Lattner25b6f912010-02-23 06:16:51 +00002525
Chris Lattner405f1252010-03-01 22:29:19 +00002526 // If the source pattern's root is a complex pattern, that complex pattern
2527 // must specify the nodes it can potentially match.
2528 if (const ComplexPattern *CP =
2529 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2530 if (CP->getRootNodes().empty())
2531 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2532 " could match");
2533
2534
Chris Lattner967d54a2010-02-23 06:35:45 +00002535 // Find all of the named values in the input and output, ensure they have the
2536 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002537 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002538 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2539 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002540
2541 // Scan all of the named values in the destination pattern, rejecting them if
2542 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002543 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002544 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002545 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002546 Pattern->error("Pattern has input without matching name in output: $" +
2547 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002548 }
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002549
2550 // Scan all of the named values in the source pattern, rejecting them if the
2551 // name isn't used in the dest, and isn't used to tie two values together.
2552 for (std::map<std::string, NameRecord>::iterator
2553 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2554 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2555 Pattern->error("Pattern has dead named input: $" + I->first);
2556
Chris Lattner25b6f912010-02-23 06:16:51 +00002557 PatternsToMatch.push_back(PTM);
2558}
2559
2560
Dan Gohmanee4fa192008-04-03 00:02:49 +00002561
2562void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002563 const std::vector<const CodeGenInstruction*> &Instructions =
2564 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002565 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2566 CodeGenInstruction &InstInfo =
2567 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002568 // Determine properties of the instruction from its pattern.
Chris Lattner1e506312010-03-19 05:34:15 +00002569 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2570 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2571 *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002572 InstInfo.mayStore = MayStore;
2573 InstInfo.mayLoad = MayLoad;
2574 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002575 InstInfo.Operands.isVariadic = IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002576 }
2577}
2578
Chris Lattner2cacec52010-03-15 06:00:16 +00002579/// Given a pattern result with an unresolved type, see if we can find one
2580/// instruction with an unresolved result type. Force this result type to an
2581/// arbitrary element if it's possible types to converge results.
2582static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2583 if (N->isLeaf())
2584 return false;
2585
2586 // Analyze children.
2587 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2588 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2589 return true;
2590
2591 if (!N->getOperator()->isSubClassOf("Instruction"))
2592 return false;
2593
2594 // If this type is already concrete or completely unknown we can't do
2595 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00002596 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2597 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2598 continue;
Chris Lattner2cacec52010-03-15 06:00:16 +00002599
Chris Lattnerd7349192010-03-19 21:37:09 +00002600 // Otherwise, force its type to the first possibility (an arbitrary choice).
2601 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2602 return true;
2603 }
2604
2605 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00002606}
2607
Chris Lattnerfe718932008-01-06 01:10:31 +00002608void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002609 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2610
2611 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002612 Record *CurPattern = Patterns[i];
2613 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Chris Lattner310adf12010-03-27 02:53:27 +00002614 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002615
2616 // Inline pattern fragments into it.
2617 Pattern->InlinePatternFragments();
2618
Chris Lattnerd7349192010-03-19 21:37:09 +00002619 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00002620 if (LI->getSize() == 0) continue; // no pattern.
2621
2622 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00002623 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002624
2625 // Inline pattern fragments into it.
2626 Result->InlinePatternFragments();
2627
2628 if (Result->getNumTrees() != 1)
2629 Result->error("Cannot handle instructions producing instructions "
2630 "with temporaries yet!");
2631
2632 bool IterateInference;
2633 bool InferredAllPatternTypes, InferredAllResultTypes;
2634 do {
2635 // Infer as many types as possible. If we cannot infer all of them, we
2636 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002637 InferredAllPatternTypes =
2638 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002639
2640 // Infer as many types as possible. If we cannot infer all of them, we
2641 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002642 InferredAllResultTypes =
2643 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002644
Chris Lattner6c6ba362010-03-18 23:15:10 +00002645 IterateInference = false;
2646
Chris Lattner6cefb772008-01-05 22:25:12 +00002647 // Apply the type of the result to the source pattern. This helps us
2648 // resolve cases where the input type is known to be a pointer type (which
2649 // is considered resolved), but the result knows it needs to be 32- or
2650 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00002651 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2652 Pattern->getTree(0)->getNumTypes());
2653 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00002654 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002655 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002656 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00002657 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00002658 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002659
2660 // If our iteration has converged and the input pattern's types are fully
2661 // resolved but the result pattern is not fully resolved, we may have a
2662 // situation where we have two instructions in the result pattern and
2663 // the instructions require a common register class, but don't care about
2664 // what actual MVT is used. This is actually a bug in our modelling:
2665 // output patterns should have register classes, not MVTs.
2666 //
2667 // In any case, to handle this, we just go through and disambiguate some
2668 // arbitrary types to the result pattern's nodes.
2669 if (!IterateInference && InferredAllPatternTypes &&
2670 !InferredAllResultTypes)
2671 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2672 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002673 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002674
Chris Lattner6cefb772008-01-05 22:25:12 +00002675 // Verify that we inferred enough types that we can do something with the
2676 // pattern and result. If these fire the user has to add type casts.
2677 if (!InferredAllPatternTypes)
2678 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002679 if (!InferredAllResultTypes) {
2680 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002681 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002682 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002683
2684 // Validate that the input pattern is correct.
2685 std::map<std::string, TreePatternNode*> InstInputs;
2686 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00002687 std::vector<Record*> InstImpResults;
2688 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2689 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2690 InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002691 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002692
2693 // Promote the xform function to be an explicit node if set.
2694 TreePatternNode *DstPattern = Result->getOnlyTree();
2695 std::vector<TreePatternNode*> ResultNodeOperands;
2696 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2697 TreePatternNode *OpNode = DstPattern->getChild(ii);
2698 if (Record *Xform = OpNode->getTransformFn()) {
2699 OpNode->setTransformFn(0);
2700 std::vector<TreePatternNode*> Children;
2701 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002702 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002703 }
2704 ResultNodeOperands.push_back(OpNode);
2705 }
2706 DstPattern = Result->getOnlyTree();
2707 if (!DstPattern->isLeaf())
2708 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00002709 ResultNodeOperands,
2710 DstPattern->getNumTypes());
2711
2712 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2713 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2714
Chris Lattner6cefb772008-01-05 22:25:12 +00002715 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2716 Temp.InferAllTypes();
2717
Chris Lattner6cefb772008-01-05 22:25:12 +00002718
Chris Lattner25b6f912010-02-23 06:16:51 +00002719 AddPatternToMatch(Pattern,
Jim Grosbach997759a2010-12-07 23:05:49 +00002720 PatternToMatch(CurPattern,
2721 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerd7349192010-03-19 21:37:09 +00002722 Pattern->getTree(0),
2723 Temp.getOnlyTree(), InstImpResults,
2724 CurPattern->getValueAsInt("AddedComplexity"),
2725 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002726 }
2727}
2728
2729/// CombineChildVariants - Given a bunch of permutations of each child of the
2730/// 'operator' node, put them together in all possible ways.
2731static void CombineChildVariants(TreePatternNode *Orig,
2732 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2733 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002734 CodeGenDAGPatterns &CDP,
2735 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002736 // Make sure that each operand has at least one variant to choose from.
2737 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2738 if (ChildVariants[i].empty())
2739 return;
2740
2741 // The end result is an all-pairs construction of the resultant pattern.
2742 std::vector<unsigned> Idxs;
2743 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002744 bool NotDone;
2745 do {
2746#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002747 DEBUG(if (!Idxs.empty()) {
2748 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2749 for (unsigned i = 0; i < Idxs.size(); ++i) {
2750 errs() << Idxs[i] << " ";
2751 }
2752 errs() << "]\n";
2753 });
Scott Michel327d0652008-03-05 17:49:05 +00002754#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002755 // Create the variant and add it to the output list.
2756 std::vector<TreePatternNode*> NewChildren;
2757 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2758 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00002759 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2760 Orig->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002761
2762 // Copy over properties.
2763 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002764 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002765 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00002766 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2767 R->setType(i, Orig->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002768
Scott Michel327d0652008-03-05 17:49:05 +00002769 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002770 std::string ErrString;
2771 if (!R->canPatternMatch(ErrString, CDP)) {
2772 delete R;
2773 } else {
2774 bool AlreadyExists = false;
2775
2776 // Scan to see if this pattern has already been emitted. We can get
2777 // duplication due to things like commuting:
2778 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2779 // which are the same pattern. Ignore the dups.
2780 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002781 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002782 AlreadyExists = true;
2783 break;
2784 }
2785
2786 if (AlreadyExists)
2787 delete R;
2788 else
2789 OutVariants.push_back(R);
2790 }
2791
Scott Michel327d0652008-03-05 17:49:05 +00002792 // Increment indices to the next permutation by incrementing the
2793 // indicies from last index backward, e.g., generate the sequence
2794 // [0, 0], [0, 1], [1, 0], [1, 1].
2795 int IdxsIdx;
2796 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2797 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2798 Idxs[IdxsIdx] = 0;
2799 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002800 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002801 }
Scott Michel327d0652008-03-05 17:49:05 +00002802 NotDone = (IdxsIdx >= 0);
2803 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002804}
2805
2806/// CombineChildVariants - A helper function for binary operators.
2807///
2808static void CombineChildVariants(TreePatternNode *Orig,
2809 const std::vector<TreePatternNode*> &LHS,
2810 const std::vector<TreePatternNode*> &RHS,
2811 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002812 CodeGenDAGPatterns &CDP,
2813 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002814 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2815 ChildVariants.push_back(LHS);
2816 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002817 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002818}
2819
2820
2821static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2822 std::vector<TreePatternNode *> &Children) {
2823 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2824 Record *Operator = N->getOperator();
2825
2826 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002827 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002828 N->getTransformFn()) {
2829 Children.push_back(N);
2830 return;
2831 }
2832
2833 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2834 Children.push_back(N->getChild(0));
2835 else
2836 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2837
2838 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2839 Children.push_back(N->getChild(1));
2840 else
2841 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2842}
2843
2844/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2845/// the (potentially recursive) pattern by using algebraic laws.
2846///
2847static void GenerateVariantsOf(TreePatternNode *N,
2848 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002849 CodeGenDAGPatterns &CDP,
2850 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002851 // We cannot permute leaves.
2852 if (N->isLeaf()) {
2853 OutVariants.push_back(N);
2854 return;
2855 }
2856
2857 // Look up interesting info about the node.
2858 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2859
Jim Grosbachda4231f2009-03-26 16:17:51 +00002860 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002861 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002862 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002863 std::vector<TreePatternNode*> MaximalChildren;
2864 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2865
2866 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2867 // permutations.
2868 if (MaximalChildren.size() == 3) {
2869 // Find the variants of all of our maximal children.
2870 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002871 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2872 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2873 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002874
2875 // There are only two ways we can permute the tree:
2876 // (A op B) op C and A op (B op C)
2877 // Within these forms, we can also permute A/B/C.
2878
2879 // Generate legal pair permutations of A/B/C.
2880 std::vector<TreePatternNode*> ABVariants;
2881 std::vector<TreePatternNode*> BAVariants;
2882 std::vector<TreePatternNode*> ACVariants;
2883 std::vector<TreePatternNode*> CAVariants;
2884 std::vector<TreePatternNode*> BCVariants;
2885 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002886 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2887 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2888 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2889 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2890 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2891 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002892
2893 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002894 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2895 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2896 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2897 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2898 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2899 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002900
2901 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002902 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2903 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2904 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2905 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2906 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2907 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002908 return;
2909 }
2910 }
2911
2912 // Compute permutations of all children.
2913 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2914 ChildVariants.resize(N->getNumChildren());
2915 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002916 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002917
2918 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002919 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002920
2921 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002922 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2923 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2924 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2925 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002926 // Don't count children which are actually register references.
2927 unsigned NC = 0;
2928 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2929 TreePatternNode *Child = N->getChild(i);
2930 if (Child->isLeaf())
2931 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2932 Record *RR = DI->getDef();
2933 if (RR->isSubClassOf("Register"))
2934 continue;
2935 }
2936 NC++;
2937 }
2938 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002939 if (isCommIntrinsic) {
2940 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2941 // operands are the commutative operands, and there might be more operands
2942 // after those.
2943 assert(NC >= 3 &&
2944 "Commutative intrinsic should have at least 3 childrean!");
2945 std::vector<std::vector<TreePatternNode*> > Variants;
2946 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2947 Variants.push_back(ChildVariants[2]);
2948 Variants.push_back(ChildVariants[1]);
2949 for (unsigned i = 3; i != NC; ++i)
2950 Variants.push_back(ChildVariants[i]);
2951 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2952 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002953 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002954 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002955 }
2956}
2957
2958
2959// GenerateVariants - Generate variants. For example, commutative patterns can
2960// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002961void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002962 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002963
2964 // Loop over all of the patterns we've collected, checking to see if we can
2965 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002966 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002967 // the .td file having to contain tons of variants of instructions.
2968 //
2969 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2970 // intentionally do not reconsider these. Any variants of added patterns have
2971 // already been added.
2972 //
2973 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002974 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002975 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002976 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002977 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002978 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002979 DEBUG(errs() << "\n");
Jim Grosbachbb168242010-10-08 18:13:57 +00002980 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
2981 DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002982
2983 assert(!Variants.empty() && "Must create at least original variant!");
2984 Variants.erase(Variants.begin()); // Remove the original pattern.
2985
2986 if (Variants.empty()) // No variants for this pattern.
2987 continue;
2988
Chris Lattner569f1212009-08-23 04:44:11 +00002989 DEBUG(errs() << "FOUND VARIANTS OF: ";
2990 PatternsToMatch[i].getSrcPattern()->dump();
2991 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002992
2993 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2994 TreePatternNode *Variant = Variants[v];
2995
Chris Lattner569f1212009-08-23 04:44:11 +00002996 DEBUG(errs() << " VAR#" << v << ": ";
2997 Variant->dump();
2998 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002999
3000 // Scan to see if an instruction or explicit pattern already matches this.
3001 bool AlreadyExists = false;
3002 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00003003 // Skip if the top level predicates do not match.
3004 if (PatternsToMatch[i].getPredicates() !=
3005 PatternsToMatch[p].getPredicates())
3006 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00003007 // Check to see if this variant already exists.
Jim Grosbachbb168242010-10-08 18:13:57 +00003008 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3009 DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00003010 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003011 AlreadyExists = true;
3012 break;
3013 }
3014 }
3015 // If we already have it, ignore the variant.
3016 if (AlreadyExists) continue;
3017
3018 // Otherwise, add it to the list of patterns we have.
3019 PatternsToMatch.
Jim Grosbach997759a2010-12-07 23:05:49 +00003020 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3021 PatternsToMatch[i].getPredicates(),
Chris Lattner6cefb772008-01-05 22:25:12 +00003022 Variant, PatternsToMatch[i].getDstPattern(),
3023 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00003024 PatternsToMatch[i].getAddedComplexity(),
3025 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003026 }
3027
Chris Lattner569f1212009-08-23 04:44:11 +00003028 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003029 }
3030}
3031