blob: 2ade4e32d35c6b3218f53e30de767dc52a86b3a2 [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner6cefb772008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfe718932008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner93c7e412008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
Chris Lattner2cacec52010-03-15 06:00:16 +000018#include "llvm/ADT/STLExtras.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include "llvm/Support/Debug.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000020#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000021#include <algorithm>
Chris Lattner6cefb772008-01-05 22:25:12 +000022using namespace llvm;
23
24//===----------------------------------------------------------------------===//
Chris Lattner2cacec52010-03-15 06:00:16 +000025// EEVT::TypeSet Implementation
26//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +000027
Owen Anderson825b72b2009-08-11 20:47:22 +000028static inline bool isInteger(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000029 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000030}
Owen Anderson825b72b2009-08-11 20:47:22 +000031static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000032 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000033}
Owen Anderson825b72b2009-08-11 20:47:22 +000034static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000035 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000036}
Chris Lattner774ce292010-03-19 17:41:26 +000037static inline bool isScalar(MVT::SimpleValueType VT) {
38 return !EVT(VT).isVector();
39}
Duncan Sands83ec4b62008-06-06 12:08:01 +000040
Chris Lattner2cacec52010-03-15 06:00:16 +000041EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
42 if (VT == MVT::iAny)
43 EnforceInteger(TP);
44 else if (VT == MVT::fAny)
45 EnforceFloatingPoint(TP);
46 else if (VT == MVT::vAny)
47 EnforceVector(TP);
48 else {
49 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
50 VT == MVT::iPTRAny) && "Not a concrete type!");
51 TypeVec.push_back(VT);
52 }
Chris Lattner6cefb772008-01-05 22:25:12 +000053}
54
Chris Lattner2cacec52010-03-15 06:00:16 +000055
56EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
57 assert(!VTList.empty() && "empty list?");
58 TypeVec.append(VTList.begin(), VTList.end());
59
60 if (!VTList.empty())
61 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62 VTList[0] != MVT::fAny);
63
64 // Remove duplicates.
65 array_pod_sort(TypeVec.begin(), TypeVec.end());
66 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Chris Lattner6cefb772008-01-05 22:25:12 +000067}
68
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000069/// FillWithPossibleTypes - Set to all legal types and return true, only valid
70/// on completely unknown type sets.
Chris Lattner774ce292010-03-19 17:41:26 +000071bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
72 bool (*Pred)(MVT::SimpleValueType),
73 const char *PredicateName) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000074 assert(isCompletelyUnknown());
Chris Lattner774ce292010-03-19 17:41:26 +000075 const std::vector<MVT::SimpleValueType> &LegalTypes =
76 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
77
78 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
79 if (Pred == 0 || Pred(LegalTypes[i]))
80 TypeVec.push_back(LegalTypes[i]);
81
82 // If we have nothing that matches the predicate, bail out.
83 if (TypeVec.empty())
84 TP.error("Type inference contradiction found, no " +
85 std::string(PredicateName) + " types found");
86 // No need to sort with one element.
87 if (TypeVec.size() == 1) return true;
88
89 // Remove duplicates.
90 array_pod_sort(TypeVec.begin(), TypeVec.end());
91 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
92
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000093 return true;
94}
Chris Lattner2cacec52010-03-15 06:00:16 +000095
96/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
97/// integer value type.
98bool EEVT::TypeSet::hasIntegerTypes() const {
99 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
100 if (isInteger(TypeVec[i]))
101 return true;
102 return false;
103}
104
105/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
106/// a floating point value type.
107bool EEVT::TypeSet::hasFloatingPointTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isFloatingPoint(TypeVec[i]))
110 return true;
111 return false;
112}
113
114/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
115/// value type.
116bool EEVT::TypeSet::hasVectorTypes() const {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isVector(TypeVec[i]))
119 return true;
120 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +0000121}
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000122
Chris Lattner2cacec52010-03-15 06:00:16 +0000123
124std::string EEVT::TypeSet::getName() const {
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000125 if (TypeVec.empty()) return "<empty>";
Chris Lattner2cacec52010-03-15 06:00:16 +0000126
127 std::string Result;
128
129 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
130 std::string VTName = llvm::getEnumName(TypeVec[i]);
131 // Strip off MVT:: prefix if present.
132 if (VTName.substr(0,5) == "MVT::")
133 VTName = VTName.substr(5);
134 if (i) Result += ':';
135 Result += VTName;
136 }
137
138 if (TypeVec.size() == 1)
139 return Result;
140 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000141}
Chris Lattner2cacec52010-03-15 06:00:16 +0000142
143/// MergeInTypeInfo - This merges in type information from the specified
144/// argument. If 'this' changes, it returns true. If the two types are
145/// contradictory (e.g. merge f32 into i32) then this throws an exception.
146bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
147 if (InVT.isCompletelyUnknown() || *this == InVT)
148 return false;
149
150 if (isCompletelyUnknown()) {
151 *this = InVT;
152 return true;
153 }
154
155 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
156
157 // Handle the abstract cases, seeing if we can resolve them better.
158 switch (TypeVec[0]) {
159 default: break;
160 case MVT::iPTR:
161 case MVT::iPTRAny:
162 if (InVT.hasIntegerTypes()) {
163 EEVT::TypeSet InCopy(InVT);
164 InCopy.EnforceInteger(TP);
165 InCopy.EnforceScalar(TP);
166
167 if (InCopy.isConcrete()) {
168 // If the RHS has one integer type, upgrade iPTR to i32.
169 TypeVec[0] = InVT.TypeVec[0];
170 return true;
171 }
172
173 // If the input has multiple scalar integers, this doesn't add any info.
174 if (!InCopy.isCompletelyUnknown())
175 return false;
176 }
177 break;
178 }
179
180 // If the input constraint is iAny/iPTR and this is an integer type list,
181 // remove non-integer types from the list.
182 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
183 hasIntegerTypes()) {
184 bool MadeChange = EnforceInteger(TP);
185
186 // If we're merging in iPTR/iPTRAny and the node currently has a list of
187 // multiple different integer types, replace them with a single iPTR.
188 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
189 TypeVec.size() != 1) {
190 TypeVec.resize(1);
191 TypeVec[0] = InVT.TypeVec[0];
192 MadeChange = true;
193 }
194
195 return MadeChange;
196 }
197
198 // If this is a type list and the RHS is a typelist as well, eliminate entries
199 // from this list that aren't in the other one.
200 bool MadeChange = false;
201 TypeSet InputSet(*this);
202
203 for (unsigned i = 0; i != TypeVec.size(); ++i) {
204 bool InInVT = false;
205 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
206 if (TypeVec[i] == InVT.TypeVec[j]) {
207 InInVT = true;
208 break;
209 }
210
211 if (InInVT) continue;
212 TypeVec.erase(TypeVec.begin()+i--);
213 MadeChange = true;
214 }
215
216 // If we removed all of our types, we have a type contradiction.
217 if (!TypeVec.empty())
218 return MadeChange;
219
220 // FIXME: Really want an SMLoc here!
221 TP.error("Type inference contradiction found, merging '" +
222 InVT.getName() + "' into '" + InputSet.getName() + "'");
223 return true; // unreachable
224}
225
226/// EnforceInteger - Remove all non-integer types from this set.
227bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000228 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000229 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000230 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattner2cacec52010-03-15 06:00:16 +0000231 if (!hasFloatingPointTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000232 return false;
233
234 TypeSet InputSet(*this);
Chris Lattner2cacec52010-03-15 06:00:16 +0000235
236 // Filter out all the fp types.
237 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000238 if (!isInteger(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000239 TypeVec.erase(TypeVec.begin()+i--);
240
241 if (TypeVec.empty())
242 TP.error("Type inference contradiction found, '" +
243 InputSet.getName() + "' needs to be integer");
Chris Lattner774ce292010-03-19 17:41:26 +0000244 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000245}
246
247/// EnforceFloatingPoint - Remove all integer types from this set.
248bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000249 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000250 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000251 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
252
Chris Lattner2cacec52010-03-15 06:00:16 +0000253 if (!hasIntegerTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000254 return false;
255
256 TypeSet InputSet(*this);
Chris Lattner2cacec52010-03-15 06:00:16 +0000257
258 // Filter out all the fp types.
259 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000260 if (!isFloatingPoint(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000261 TypeVec.erase(TypeVec.begin()+i--);
262
263 if (TypeVec.empty())
264 TP.error("Type inference contradiction found, '" +
265 InputSet.getName() + "' needs to be floating point");
Chris Lattner774ce292010-03-19 17:41:26 +0000266 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000267}
268
269/// EnforceScalar - Remove all vector types from this.
270bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000271 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000272 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000273 return FillWithPossibleTypes(TP, isScalar, "scalar");
274
Chris Lattner2cacec52010-03-15 06:00:16 +0000275 if (!hasVectorTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000276 return false;
277
278 TypeSet InputSet(*this);
Chris Lattner2cacec52010-03-15 06:00:16 +0000279
280 // Filter out all the vector types.
281 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000282 if (!isScalar(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000283 TypeVec.erase(TypeVec.begin()+i--);
284
285 if (TypeVec.empty())
286 TP.error("Type inference contradiction found, '" +
287 InputSet.getName() + "' needs to be scalar");
Chris Lattner774ce292010-03-19 17:41:26 +0000288 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000289}
290
291/// EnforceVector - Remove all vector types from this.
292bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Chris Lattner774ce292010-03-19 17:41:26 +0000293 // If we know nothing, then get the full set.
294 if (TypeVec.empty())
295 return FillWithPossibleTypes(TP, isVector, "vector");
296
Chris Lattner2cacec52010-03-15 06:00:16 +0000297 TypeSet InputSet(*this);
298 bool MadeChange = false;
299
Chris Lattner2cacec52010-03-15 06:00:16 +0000300 // Filter out all the scalar types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000302 if (!isVector(TypeVec[i])) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000303 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner774ce292010-03-19 17:41:26 +0000304 MadeChange = true;
305 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000306
307 if (TypeVec.empty())
308 TP.error("Type inference contradiction found, '" +
309 InputSet.getName() + "' needs to be a vector");
310 return MadeChange;
311}
312
313
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000314
Chris Lattner2cacec52010-03-15 06:00:16 +0000315/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
316/// this an other based on this information.
317bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
318 // Both operands must be integer or FP, but we don't care which.
319 bool MadeChange = false;
320
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000321 if (isCompletelyUnknown())
322 MadeChange = FillWithPossibleTypes(TP);
323
324 if (Other.isCompletelyUnknown())
325 MadeChange = Other.FillWithPossibleTypes(TP);
326
327 // If one side is known to be integer or known to be FP but the other side has
328 // no information, get at least the type integrality info in there.
329 if (!hasFloatingPointTypes())
330 MadeChange |= Other.EnforceInteger(TP);
331 else if (!hasIntegerTypes())
332 MadeChange |= Other.EnforceFloatingPoint(TP);
333 if (!Other.hasFloatingPointTypes())
334 MadeChange |= EnforceInteger(TP);
335 else if (!Other.hasIntegerTypes())
336 MadeChange |= EnforceFloatingPoint(TP);
337
338 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339 "Should have a type list now");
340
341 // If one contains vectors but the other doesn't pull vectors out.
342 if (!hasVectorTypes())
343 MadeChange |= Other.EnforceScalar(TP);
344 if (!hasVectorTypes())
345 MadeChange |= EnforceScalar(TP);
346
Chris Lattner2cacec52010-03-15 06:00:16 +0000347 // This code does not currently handle nodes which have multiple types,
348 // where some types are integer, and some are fp. Assert that this is not
349 // the case.
350 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
351 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
352 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000353
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000354 // Okay, find the smallest type from the current set and remove it from the
355 // largest set.
356 MVT::SimpleValueType Smallest = TypeVec[0];
357 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
358 if (TypeVec[i] < Smallest)
359 Smallest = TypeVec[i];
Chris Lattner2cacec52010-03-15 06:00:16 +0000360
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000361 // If this is the only type in the large set, the constraint can never be
362 // satisfied.
363 if (Other.TypeVec.size() == 1 && Other.TypeVec[0] == Smallest)
364 TP.error("Type inference contradiction found, '" +
365 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000366
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000367 SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
368 std::find(Other.TypeVec.begin(), Other.TypeVec.end(), Smallest);
369 if (TVI != Other.TypeVec.end()) {
370 Other.TypeVec.erase(TVI);
371 MadeChange = true;
372 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000373
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000374 // Okay, find the largest type in the Other set and remove it from the
375 // current set.
376 MVT::SimpleValueType Largest = Other.TypeVec[0];
377 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
378 if (Other.TypeVec[i] > Largest)
379 Largest = Other.TypeVec[i];
Chris Lattner2cacec52010-03-15 06:00:16 +0000380
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000381 // If this is the only type in the small set, the constraint can never be
382 // satisfied.
383 if (TypeVec.size() == 1 && TypeVec[0] == Largest)
384 TP.error("Type inference contradiction found, '" +
385 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
386
387 TVI = std::find(TypeVec.begin(), TypeVec.end(), Largest);
388 if (TVI != TypeVec.end()) {
389 TypeVec.erase(TVI);
390 MadeChange = true;
391 }
392
393 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000394}
395
396/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
397/// whose element is VT.
398bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
399 TreePattern &TP) {
400 TypeSet InputSet(*this);
401 bool MadeChange = false;
402
403 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000404 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000405 MadeChange = FillWithPossibleTypes(TP, isVector, "vector");
Chris Lattner2cacec52010-03-15 06:00:16 +0000406
407 // Filter out all the non-vector types and types which don't have the right
408 // element type.
409 for (unsigned i = 0; i != TypeVec.size(); ++i)
410 if (!isVector(TypeVec[i]) ||
411 EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
412 TypeVec.erase(TypeVec.begin()+i--);
413 MadeChange = true;
414 }
415
416 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
417 TP.error("Type inference contradiction found, forcing '" +
418 InputSet.getName() + "' to have a vector element");
419 return MadeChange;
420}
421
422//===----------------------------------------------------------------------===//
423// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000424
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000425bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
426 return LHS->getID() < RHS->getID();
427}
Scott Michel327d0652008-03-05 17:49:05 +0000428
429/// Dependent variable map for CodeGenDAGPattern variant generation
430typedef std::map<std::string, int> DepVarMap;
431
432/// Const iterator shorthand for DepVarMap
433typedef DepVarMap::const_iterator DepVarMap_citer;
434
435namespace {
436void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
437 if (N->isLeaf()) {
438 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
439 DepMap[N->getName()]++;
440 }
441 } else {
442 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
443 FindDepVarsOf(N->getChild(i), DepMap);
444 }
445}
446
447//! Find dependent variables within child patterns
448/*!
449 */
450void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
451 DepVarMap depcounts;
452 FindDepVarsOf(N, depcounts);
453 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
454 if (i->second > 1) { // std::pair<std::string, int>
455 DepVars.insert(i->first);
456 }
457 }
458}
459
460//! Dump the dependent variable set:
461void DumpDepVars(MultipleUseVarSet &DepVars) {
462 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000463 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000464 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000465 DEBUG(errs() << "[ ");
Scott Michel327d0652008-03-05 17:49:05 +0000466 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
467 i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000468 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000469 }
Chris Lattner569f1212009-08-23 04:44:11 +0000470 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000471 }
472}
473}
474
Chris Lattner6cefb772008-01-05 22:25:12 +0000475//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000476// PatternToMatch implementation
477//
478
479/// getPredicateCheck - Return a single string containing all of this
480/// pattern's predicates concatenated with "&&" operators.
481///
482std::string PatternToMatch::getPredicateCheck() const {
483 std::string PredicateCheck;
484 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
485 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
486 Record *Def = Pred->getDef();
487 if (!Def->isSubClassOf("Predicate")) {
488#ifndef NDEBUG
489 Def->dump();
490#endif
491 assert(0 && "Unknown predicate type!");
492 }
493 if (!PredicateCheck.empty())
494 PredicateCheck += " && ";
495 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
496 }
497 }
498
499 return PredicateCheck;
500}
501
502//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000503// SDTypeConstraint implementation
504//
505
506SDTypeConstraint::SDTypeConstraint(Record *R) {
507 OperandNo = R->getValueAsInt("OperandNum");
508
509 if (R->isSubClassOf("SDTCisVT")) {
510 ConstraintType = SDTCisVT;
511 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
512 } else if (R->isSubClassOf("SDTCisPtrTy")) {
513 ConstraintType = SDTCisPtrTy;
514 } else if (R->isSubClassOf("SDTCisInt")) {
515 ConstraintType = SDTCisInt;
516 } else if (R->isSubClassOf("SDTCisFP")) {
517 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000518 } else if (R->isSubClassOf("SDTCisVec")) {
519 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000520 } else if (R->isSubClassOf("SDTCisSameAs")) {
521 ConstraintType = SDTCisSameAs;
522 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
523 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
524 ConstraintType = SDTCisVTSmallerThanOp;
525 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
526 R->getValueAsInt("OtherOperandNum");
527 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
528 ConstraintType = SDTCisOpSmallerThanOp;
529 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
530 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000531 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
532 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000533 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000534 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000535 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000536 exit(1);
537 }
538}
539
540/// getOperandNum - Return the node corresponding to operand #OpNo in tree
541/// N, which has NumResults results.
542TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
543 TreePatternNode *N,
544 unsigned NumResults) const {
545 assert(NumResults <= 1 &&
546 "We only work with nodes with zero or one result so far!");
547
548 if (OpNo >= (NumResults + N->getNumChildren())) {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000549 errs() << "Invalid operand number " << OpNo << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000550 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000551 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000552 exit(1);
553 }
554
555 if (OpNo < NumResults)
556 return N; // FIXME: need value #
557 else
558 return N->getChild(OpNo-NumResults);
559}
560
561/// ApplyTypeConstraint - Given a node in a pattern, apply this type
562/// constraint to the nodes operands. This returns true if it makes a
563/// change, false otherwise. If a type contradiction is found, throw an
564/// exception.
565bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
566 const SDNodeInfo &NodeInfo,
567 TreePattern &TP) const {
568 unsigned NumResults = NodeInfo.getNumResults();
569 assert(NumResults <= 1 &&
570 "We only work with nodes with zero or one result so far!");
571
572 // Check that the number of operands is sane. Negative operands -> varargs.
573 if (NodeInfo.getNumOperands() >= 0) {
574 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
575 TP.error(N->getOperator()->getName() + " node requires exactly " +
576 itostr(NodeInfo.getNumOperands()) + " operands!");
577 }
578
Chris Lattner6cefb772008-01-05 22:25:12 +0000579 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
580
581 switch (ConstraintType) {
582 default: assert(0 && "Unknown constraint type!");
583 case SDTCisVT:
584 // Operand must be a particular type.
585 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000586 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000587 // Operand must be same as target pointer type.
Owen Anderson825b72b2009-08-11 20:47:22 +0000588 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000589 case SDTCisInt:
590 // Require it to be one of the legal integer VTs.
591 return NodeToApply->getExtType().EnforceInteger(TP);
592 case SDTCisFP:
593 // Require it to be one of the legal fp VTs.
594 return NodeToApply->getExtType().EnforceFloatingPoint(TP);
595 case SDTCisVec:
596 // Require it to be one of the legal vector VTs.
597 return NodeToApply->getExtType().EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000598 case SDTCisSameAs: {
599 TreePatternNode *OtherNode =
600 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Chris Lattner2cacec52010-03-15 06:00:16 +0000601 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
602 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000603 }
604 case SDTCisVTSmallerThanOp: {
605 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
606 // have an integer type that is smaller than the VT.
607 if (!NodeToApply->isLeaf() ||
608 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
609 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
610 ->isSubClassOf("ValueType"))
611 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000612 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000613 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Duncan Sands83ec4b62008-06-06 12:08:01 +0000614 if (!isInteger(VT))
Chris Lattner6cefb772008-01-05 22:25:12 +0000615 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
616
617 TreePatternNode *OtherNode =
618 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
619
620 // It must be integer.
Chris Lattner2cacec52010-03-15 06:00:16 +0000621 bool MadeChange = OtherNode->getExtType().EnforceInteger(TP);
622
623 // This doesn't try to enforce any information on the OtherNode, it just
624 // validates it when information is determined.
625 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
Owen Anderson825b72b2009-08-11 20:47:22 +0000626 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
Bill Wendling7529ece2009-12-25 13:35:40 +0000627 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +0000628 }
629 case SDTCisOpSmallerThanOp: {
630 TreePatternNode *BigOperand =
631 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
Chris Lattner2cacec52010-03-15 06:00:16 +0000632 return NodeToApply->getExtType().
633 EnforceSmallerThan(BigOperand->getExtType(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000634 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000635 case SDTCisEltOfVec: {
Chris Lattner2cacec52010-03-15 06:00:16 +0000636 TreePatternNode *VecOperand =
637 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NumResults);
638 if (VecOperand->hasTypeSet()) {
639 if (!isVector(VecOperand->getType()))
Nate Begemanb5af3342008-02-09 01:37:05 +0000640 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000641 EVT IVT = VecOperand->getType();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000642 IVT = IVT.getVectorElementType();
Owen Anderson825b72b2009-08-11 20:47:22 +0000643 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000644 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000645
646 if (NodeToApply->hasTypeSet() && VecOperand->getExtType().hasVectorTypes()){
647 // Filter vector types out of VecOperand that don't have the right element
648 // type.
649 return VecOperand->getExtType().
650 EnforceVectorEltTypeIs(NodeToApply->getType(), TP);
651 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000652 return false;
653 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000654 }
655 return false;
656}
657
658//===----------------------------------------------------------------------===//
659// SDNodeInfo implementation
660//
661SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
662 EnumName = R->getValueAsString("Opcode");
663 SDClassName = R->getValueAsString("SDClass");
664 Record *TypeProfile = R->getValueAsDef("TypeProfile");
665 NumResults = TypeProfile->getValueAsInt("NumResults");
666 NumOperands = TypeProfile->getValueAsInt("NumOperands");
667
668 // Parse the properties.
669 Properties = 0;
670 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
671 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
672 if (PropList[i]->getName() == "SDNPCommutative") {
673 Properties |= 1 << SDNPCommutative;
674 } else if (PropList[i]->getName() == "SDNPAssociative") {
675 Properties |= 1 << SDNPAssociative;
676 } else if (PropList[i]->getName() == "SDNPHasChain") {
677 Properties |= 1 << SDNPHasChain;
678 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000679 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000680 } else if (PropList[i]->getName() == "SDNPInFlag") {
681 Properties |= 1 << SDNPInFlag;
682 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
683 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000684 } else if (PropList[i]->getName() == "SDNPMayStore") {
685 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000686 } else if (PropList[i]->getName() == "SDNPMayLoad") {
687 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000688 } else if (PropList[i]->getName() == "SDNPSideEffect") {
689 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000690 } else if (PropList[i]->getName() == "SDNPMemOperand") {
691 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000692 } else if (PropList[i]->getName() == "SDNPVariadic") {
693 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000694 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000695 errs() << "Unknown SD Node property '" << PropList[i]->getName()
696 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000697 exit(1);
698 }
699 }
700
701
702 // Parse the type constraints.
703 std::vector<Record*> ConstraintList =
704 TypeProfile->getValueAsListOfDefs("Constraints");
705 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
706}
707
Chris Lattner22579812010-02-28 00:22:30 +0000708/// getKnownType - If the type constraints on this node imply a fixed type
709/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000710/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
711MVT::SimpleValueType SDNodeInfo::getKnownType() const {
Chris Lattner22579812010-02-28 00:22:30 +0000712 unsigned NumResults = getNumResults();
713 assert(NumResults <= 1 &&
714 "We only work with nodes with zero or one result so far!");
715
716 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
717 // Make sure that this applies to the correct node result.
718 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
719 continue;
720
721 switch (TypeConstraints[i].ConstraintType) {
722 default: break;
723 case SDTypeConstraint::SDTCisVT:
724 return TypeConstraints[i].x.SDTCisVT_Info.VT;
725 case SDTypeConstraint::SDTCisPtrTy:
726 return MVT::iPTR;
727 }
728 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000729 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000730}
731
Chris Lattner6cefb772008-01-05 22:25:12 +0000732//===----------------------------------------------------------------------===//
733// TreePatternNode implementation
734//
735
736TreePatternNode::~TreePatternNode() {
737#if 0 // FIXME: implement refcounted tree nodes!
738 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
739 delete getChild(i);
740#endif
741}
742
Chris Lattnerba1cff42010-02-23 07:50:58 +0000743
Chris Lattner6cefb772008-01-05 22:25:12 +0000744
Daniel Dunbar1a551802009-07-03 00:10:29 +0000745void TreePatternNode::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000746 if (isLeaf()) {
747 OS << *getLeafValue();
748 } else {
Chris Lattnerba1cff42010-02-23 07:50:58 +0000749 OS << '(' << getOperator()->getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000750 }
751
Chris Lattner2cacec52010-03-15 06:00:16 +0000752 if (!isTypeCompletelyUnknown())
753 OS << ':' << getExtType().getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000754
755 if (!isLeaf()) {
756 if (getNumChildren() != 0) {
757 OS << " ";
758 getChild(0)->print(OS);
759 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
760 OS << ", ";
761 getChild(i)->print(OS);
762 }
763 }
764 OS << ")";
765 }
766
Dan Gohman0540e172008-10-15 06:17:21 +0000767 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
768 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000769 if (TransformFn)
770 OS << "<<X:" << TransformFn->getName() << ">>";
771 if (!getName().empty())
772 OS << ":$" << getName();
773
774}
775void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000776 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000777}
778
Scott Michel327d0652008-03-05 17:49:05 +0000779/// isIsomorphicTo - Return true if this node is recursively
780/// isomorphic to the specified node. For this comparison, the node's
781/// entire state is considered. The assigned name is ignored, since
782/// nodes with differing names are considered isomorphic. However, if
783/// the assigned name is present in the dependent variable set, then
784/// the assigned name is considered significant and the node is
785/// isomorphic if the names match.
786bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
787 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000788 if (N == this) return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000789 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000790 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000791 getTransformFn() != N->getTransformFn())
792 return false;
793
794 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000795 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
796 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000797 return ((DI->getDef() == NDI->getDef())
798 && (DepVars.find(getName()) == DepVars.end()
799 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000800 }
801 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000802 return getLeafValue() == N->getLeafValue();
803 }
804
805 if (N->getOperator() != getOperator() ||
806 N->getNumChildren() != getNumChildren()) return false;
807 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000808 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000809 return false;
810 return true;
811}
812
813/// clone - Make a copy of this tree and all of its children.
814///
815TreePatternNode *TreePatternNode::clone() const {
816 TreePatternNode *New;
817 if (isLeaf()) {
818 New = new TreePatternNode(getLeafValue());
819 } else {
820 std::vector<TreePatternNode*> CChildren;
821 CChildren.reserve(Children.size());
822 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
823 CChildren.push_back(getChild(i)->clone());
824 New = new TreePatternNode(getOperator(), CChildren);
825 }
826 New->setName(getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000827 New->setType(getExtType());
Dan Gohman0540e172008-10-15 06:17:21 +0000828 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000829 New->setTransformFn(getTransformFn());
830 return New;
831}
832
Chris Lattner47661322010-02-14 22:22:58 +0000833/// RemoveAllTypes - Recursively strip all the types of this tree.
834void TreePatternNode::RemoveAllTypes() {
Chris Lattner2cacec52010-03-15 06:00:16 +0000835 setType(EEVT::TypeSet()); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +0000836 if (isLeaf()) return;
837 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
838 getChild(i)->RemoveAllTypes();
839}
840
841
Chris Lattner6cefb772008-01-05 22:25:12 +0000842/// SubstituteFormalArguments - Replace the formal arguments in this tree
843/// with actual values specified by ArgMap.
844void TreePatternNode::
845SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
846 if (isLeaf()) return;
847
848 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
849 TreePatternNode *Child = getChild(i);
850 if (Child->isLeaf()) {
851 Init *Val = Child->getLeafValue();
852 if (dynamic_cast<DefInit*>(Val) &&
853 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
854 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000855 TreePatternNode *NewChild = ArgMap[Child->getName()];
856 assert(NewChild && "Couldn't find formal argument!");
857 assert((Child->getPredicateFns().empty() ||
858 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
859 "Non-empty child predicate clobbered!");
860 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000861 }
862 } else {
863 getChild(i)->SubstituteFormalArguments(ArgMap);
864 }
865 }
866}
867
868
869/// InlinePatternFragments - If this pattern refers to any pattern
870/// fragments, inline them into place, giving us a pattern without any
871/// PatFrag references.
872TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
873 if (isLeaf()) return this; // nothing to do.
874 Record *Op = getOperator();
875
876 if (!Op->isSubClassOf("PatFrag")) {
877 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000878 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
879 TreePatternNode *Child = getChild(i);
880 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
881
882 assert((Child->getPredicateFns().empty() ||
883 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
884 "Non-empty child predicate clobbered!");
885
886 setChild(i, NewChild);
887 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000888 return this;
889 }
890
891 // Otherwise, we found a reference to a fragment. First, look up its
892 // TreePattern record.
893 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
894
895 // Verify that we are passing the right number of operands.
896 if (Frag->getNumArgs() != Children.size())
897 TP.error("'" + Op->getName() + "' fragment requires " +
898 utostr(Frag->getNumArgs()) + " operands!");
899
900 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
901
Dan Gohman0540e172008-10-15 06:17:21 +0000902 std::string Code = Op->getValueAsCode("Predicate");
903 if (!Code.empty())
904 FragTree->addPredicateFn("Predicate_"+Op->getName());
905
Chris Lattner6cefb772008-01-05 22:25:12 +0000906 // Resolve formal arguments to their actual value.
907 if (Frag->getNumArgs()) {
908 // Compute the map of formal to actual arguments.
909 std::map<std::string, TreePatternNode*> ArgMap;
910 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
911 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
912
913 FragTree->SubstituteFormalArguments(ArgMap);
914 }
915
916 FragTree->setName(getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000917 FragTree->UpdateNodeType(getExtType(), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000918
919 // Transfer in the old predicates.
920 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
921 FragTree->addPredicateFn(getPredicateFns()[i]);
922
Chris Lattner6cefb772008-01-05 22:25:12 +0000923 // Get a new copy of this fragment to stitch into here.
924 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000925
926 // The fragment we inlined could have recursive inlining that is needed. See
927 // if there are any pattern fragments in it and inline them as needed.
928 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000929}
930
931/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000932/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +0000933/// references from the register file information, for example.
934///
Chris Lattner2cacec52010-03-15 06:00:16 +0000935static EEVT::TypeSet getImplicitType(Record *R, bool NotRegisters,
936 TreePattern &TP) {
937 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +0000938 if (R->isSubClassOf("RegisterClass")) {
939 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000940 return EEVT::TypeSet(); // Unknown.
941 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
942 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000943 } else if (R->isSubClassOf("PatFrag")) {
944 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +0000945 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000946 } else if (R->isSubClassOf("Register")) {
947 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000948 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000949 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +0000950 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6cefb772008-01-05 22:25:12 +0000951 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
952 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +0000953 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000954 } else if (R->isSubClassOf("ComplexPattern")) {
955 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000956 return EEVT::TypeSet(); // Unknown.
957 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
958 TP);
Chris Lattnera938ac62009-07-29 20:43:05 +0000959 } else if (R->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000960 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000961 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
962 R->getName() == "zero_reg") {
963 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +0000964 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000965 }
966
967 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000968 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000969}
970
Chris Lattnere67bde52008-01-06 05:36:50 +0000971
972/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
973/// CodeGenIntrinsic information for it, otherwise return a null pointer.
974const CodeGenIntrinsic *TreePatternNode::
975getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
976 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
977 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
978 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
979 return 0;
980
981 unsigned IID =
982 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
983 return &CDP.getIntrinsicInfo(IID);
984}
985
Chris Lattner47661322010-02-14 22:22:58 +0000986/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
987/// return the ComplexPattern information, otherwise return null.
988const ComplexPattern *
989TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
990 if (!isLeaf()) return 0;
991
992 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
993 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
994 return &CGP.getComplexPattern(DI->getDef());
995 return 0;
996}
997
998/// NodeHasProperty - Return true if this node has the specified property.
999bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001000 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001001 if (isLeaf()) {
1002 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1003 return CP->hasProperty(Property);
1004 return false;
1005 }
1006
1007 Record *Operator = getOperator();
1008 if (!Operator->isSubClassOf("SDNode")) return false;
1009
1010 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1011}
1012
1013
1014
1015
1016/// TreeHasProperty - Return true if any node in this tree has the specified
1017/// property.
1018bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001019 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001020 if (NodeHasProperty(Property, CGP))
1021 return true;
1022 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1023 if (getChild(i)->TreeHasProperty(Property, CGP))
1024 return true;
1025 return false;
1026}
1027
Evan Cheng6bd95672008-06-16 20:29:38 +00001028/// isCommutativeIntrinsic - Return true if the node corresponds to a
1029/// commutative intrinsic.
1030bool
1031TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1032 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1033 return Int->isCommutative;
1034 return false;
1035}
1036
Chris Lattnere67bde52008-01-06 05:36:50 +00001037
Bob Wilson6c01ca92009-01-05 17:23:09 +00001038/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001039/// this node and its children in the tree. This returns true if it makes a
1040/// change, false otherwise. If a type contradiction is found, throw an
1041/// exception.
1042bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001043 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001044 if (isLeaf()) {
1045 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1046 // If it's a regclass or something else known, include the type.
1047 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner523f6a52010-02-14 21:10:15 +00001048 }
1049
1050 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001051 // Int inits are always integers. :)
Chris Lattner2cacec52010-03-15 06:00:16 +00001052 bool MadeChange = Type.EnforceInteger(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001053
Chris Lattner2cacec52010-03-15 06:00:16 +00001054 if (!hasTypeSet())
1055 return MadeChange;
1056
1057 MVT::SimpleValueType VT = getType();
1058 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1059 return MadeChange;
1060
1061 unsigned Size = EVT(VT).getSizeInBits();
1062 // Make sure that the value is representable for this type.
1063 if (Size >= 32) return MadeChange;
1064
1065 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1066 if (Val == II->getValue()) return MadeChange;
1067
1068 // If sign-extended doesn't fit, does it fit as unsigned?
1069 unsigned ValueMask;
1070 unsigned UnsignedVal;
1071 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1072 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001073
Chris Lattner2cacec52010-03-15 06:00:16 +00001074 if ((ValueMask & UnsignedVal) == UnsignedVal)
1075 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001076
Chris Lattner2cacec52010-03-15 06:00:16 +00001077 TP.error("Integer value '" + itostr(II->getValue())+
1078 "' is out of range for type '" + getEnumName(getType()) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001079 return MadeChange;
1080 }
1081 return false;
1082 }
1083
1084 // special handling for set, which isn't really an SDNode.
1085 if (getOperator()->getName() == "set") {
1086 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
1087 unsigned NC = getNumChildren();
1088 bool MadeChange = false;
1089 for (unsigned i = 0; i < NC-1; ++i) {
1090 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1091 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
1092
1093 // Types of operands must match.
Chris Lattner2cacec52010-03-15 06:00:16 +00001094 MadeChange |=getChild(i)->UpdateNodeType(getChild(NC-1)->getExtType(),TP);
1095 MadeChange |=getChild(NC-1)->UpdateNodeType(getChild(i)->getExtType(),TP);
1096 MadeChange |=UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001097 }
1098 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001099 }
1100
1101 if (getOperator()->getName() == "implicit" ||
1102 getOperator()->getName() == "parallel") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001103 bool MadeChange = false;
1104 for (unsigned i = 0; i < getNumChildren(); ++i)
1105 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Owen Anderson825b72b2009-08-11 20:47:22 +00001106 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001107 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001108 }
1109
1110 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001111 bool MadeChange = false;
1112 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1113 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner2cacec52010-03-15 06:00:16 +00001114
1115 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1116 // what type it gets, so if it didn't get a concrete type just give it the
1117 // first viable type from the reg class.
1118 if (!getChild(1)->hasTypeSet() &&
1119 !getChild(1)->getExtType().isCompletelyUnknown()) {
1120 MVT::SimpleValueType RCVT = getChild(1)->getExtType().getTypeList()[0];
1121 MadeChange |= getChild(1)->UpdateNodeType(RCVT, TP);
1122 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001123 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001124 }
1125
1126 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001127 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001128
Chris Lattner6cefb772008-01-05 22:25:12 +00001129 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001130 unsigned NumRetVTs = Int->IS.RetVTs.size();
1131 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001132
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001133 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1134 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1135
1136 if (getNumChildren() != NumParamVTs + NumRetVTs)
Chris Lattnere67bde52008-01-06 05:36:50 +00001137 TP.error("Intrinsic '" + Int->Name + "' expects " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001138 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1139 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001140
1141 // Apply type info to the intrinsic ID.
Owen Anderson825b72b2009-08-11 20:47:22 +00001142 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001143
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001144 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001145 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
Chris Lattner6cefb772008-01-05 22:25:12 +00001146 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1147 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1148 }
1149 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001150 }
1151
1152 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001153 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1154
1155 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1156 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1157 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1158 // Branch, etc. do not produce results and top-level forms in instr pattern
1159 // must have void types.
1160 if (NI.getNumResults() == 0)
Owen Anderson825b72b2009-08-11 20:47:22 +00001161 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001162
Chris Lattner6cefb772008-01-05 22:25:12 +00001163 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001164 }
1165
1166 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001167 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Daniel Dunbar65f35d52010-03-19 03:18:20 +00001168 assert(Inst.getNumResults() <= 1 &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001169 "Only supports zero or one result instrs!");
1170
1171 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001172 CDP.getTargetInfo().getInstruction(getOperator());
Chris Lattner6c6ba362010-03-18 23:15:10 +00001173
1174 EEVT::TypeSet ResultType;
1175
Chris Lattner6cefb772008-01-05 22:25:12 +00001176 // Apply the result type to the node
Chris Lattner6c6ba362010-03-18 23:15:10 +00001177 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
Chris Lattner6cefb772008-01-05 22:25:12 +00001178 Record *ResultNode = Inst.getResult(0);
1179
Chris Lattnera938ac62009-07-29 20:43:05 +00001180 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00001181 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001182 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001183 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001184 } else {
1185 assert(ResultNode->isSubClassOf("RegisterClass") &&
1186 "Operands should be register classes!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001187 const CodeGenRegisterClass &RC =
1188 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001189 ResultType = RC.getValueTypes();
Chris Lattner6cefb772008-01-05 22:25:12 +00001190 }
Chris Lattner6c6ba362010-03-18 23:15:10 +00001191 } else if (!InstInfo.ImplicitDefs.empty()) {
1192 // If the instruction has implicit defs, the first one defines the result
1193 // type.
Chris Lattner6c6ba362010-03-18 23:15:10 +00001194 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
Chris Lattner92879532010-03-18 23:57:40 +00001195 assert(FirstImplicitDef->isSubClassOf("Register"));
Chris Lattner6c6ba362010-03-18 23:15:10 +00001196 const std::vector<MVT::SimpleValueType> &RegVTs =
1197 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
Chris Lattner92879532010-03-18 23:57:40 +00001198 if (RegVTs.size() == 1)
Chris Lattner6c6ba362010-03-18 23:15:10 +00001199 ResultType = EEVT::TypeSet(RegVTs);
Chris Lattner92879532010-03-18 23:57:40 +00001200 else
1201 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001202 } else {
1203 // Otherwise, the instruction produces no value result.
1204 // FIXME: Model "no result" different than "one result that is void"
1205 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001206 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001207
Chris Lattner6c6ba362010-03-18 23:15:10 +00001208 bool MadeChange = UpdateNodeType(ResultType, TP);
1209
Chris Lattner2cacec52010-03-15 06:00:16 +00001210 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1211 // be the same.
1212 if (getOperator()->getName() == "INSERT_SUBREG") {
1213 MadeChange |= UpdateNodeType(getChild(0)->getExtType(), TP);
1214 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1215 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001216
1217 unsigned ChildNo = 0;
1218 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1219 Record *OperandNode = Inst.getOperand(i);
1220
1221 // If the instruction expects a predicate or optional def operand, we
1222 // codegen this by setting the operand to it's default value if it has a
1223 // non-empty DefaultOps field.
1224 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1225 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1226 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1227 continue;
1228
1229 // Verify that we didn't run out of provided operands.
1230 if (ChildNo >= getNumChildren())
1231 TP.error("Instruction '" + getOperator()->getName() +
1232 "' expects more operands than were provided.");
1233
Owen Anderson825b72b2009-08-11 20:47:22 +00001234 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001235 TreePatternNode *Child = getChild(ChildNo++);
1236 if (OperandNode->isSubClassOf("RegisterClass")) {
1237 const CodeGenRegisterClass &RC =
1238 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner2cacec52010-03-15 06:00:16 +00001239 MadeChange |= Child->UpdateNodeType(RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001240 } else if (OperandNode->isSubClassOf("Operand")) {
1241 VT = getValueType(OperandNode->getValueAsDef("Type"));
1242 MadeChange |= Child->UpdateNodeType(VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001243 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001244 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001245 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001246 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001247 } else {
1248 assert(0 && "Unknown operand type!");
1249 abort();
1250 }
1251 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1252 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001253
Christopher Lamb02f69372008-03-10 04:16:09 +00001254 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001255 TP.error("Instruction '" + getOperator()->getName() +
1256 "' was provided too many operands!");
1257
1258 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001259 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001260
1261 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1262
1263 // Node transforms always take one operand.
1264 if (getNumChildren() != 1)
1265 TP.error("Node transform '" + getOperator()->getName() +
1266 "' requires one operand!");
1267
Chris Lattner2cacec52010-03-15 06:00:16 +00001268 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1269
1270
Chris Lattner6eb30122010-02-23 05:51:07 +00001271 // If either the output or input of the xform does not have exact
1272 // type info. We assume they must be the same. Otherwise, it is perfectly
1273 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001274#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001275 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001276 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1277 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001278 return MadeChange;
1279 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001280#endif
1281 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001282}
1283
1284/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1285/// RHS of a commutative operation, not the on LHS.
1286static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1287 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1288 return true;
1289 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1290 return true;
1291 return false;
1292}
1293
1294
1295/// canPatternMatch - If it is impossible for this pattern to match on this
1296/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001297/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001298/// that can never possibly work), and to prevent the pattern permuter from
1299/// generating stuff that is useless.
1300bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001301 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001302 if (isLeaf()) return true;
1303
1304 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1305 if (!getChild(i)->canPatternMatch(Reason, CDP))
1306 return false;
1307
1308 // If this is an intrinsic, handle cases that would make it not match. For
1309 // example, if an operand is required to be an immediate.
1310 if (getOperator()->isSubClassOf("Intrinsic")) {
1311 // TODO:
1312 return true;
1313 }
1314
1315 // If this node is a commutative operator, check that the LHS isn't an
1316 // immediate.
1317 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001318 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1319 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001320 // Scan all of the operands of the node and make sure that only the last one
1321 // is a constant node, unless the RHS also is.
1322 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001323 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1324 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001325 if (OnlyOnRHSOfCommutative(getChild(i))) {
1326 Reason="Immediate value must be on the RHS of commutative operators!";
1327 return false;
1328 }
1329 }
1330 }
1331
1332 return true;
1333}
1334
1335//===----------------------------------------------------------------------===//
1336// TreePattern implementation
1337//
1338
1339TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001340 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001341 isInputPattern = isInput;
1342 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1343 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001344}
1345
1346TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001347 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001348 isInputPattern = isInput;
1349 Trees.push_back(ParseTreePattern(Pat));
1350}
1351
1352TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001353 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001354 isInputPattern = isInput;
1355 Trees.push_back(Pat);
1356}
1357
Chris Lattner6cefb772008-01-05 22:25:12 +00001358void TreePattern::error(const std::string &Msg) const {
1359 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001360 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001361}
1362
Chris Lattner2cacec52010-03-15 06:00:16 +00001363void TreePattern::ComputeNamedNodes() {
1364 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1365 ComputeNamedNodes(Trees[i]);
1366}
1367
1368void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1369 if (!N->getName().empty())
1370 NamedNodes[N->getName()].push_back(N);
1371
1372 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1373 ComputeNamedNodes(N->getChild(i));
1374}
1375
Chris Lattner6cefb772008-01-05 22:25:12 +00001376TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1377 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1378 if (!OpDef) error("Pattern has unexpected operator type!");
1379 Record *Operator = OpDef->getDef();
1380
1381 if (Operator->isSubClassOf("ValueType")) {
1382 // If the operator is a ValueType, then this must be "type cast" of a leaf
1383 // node.
1384 if (Dag->getNumArgs() != 1)
1385 error("Type cast only takes one operand!");
1386
1387 Init *Arg = Dag->getArg(0);
1388 TreePatternNode *New;
1389 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1390 Record *R = DI->getDef();
1391 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001392 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001393 std::vector<std::pair<Init*, std::string> >()));
1394 return ParseTreePattern(Dag);
1395 }
Chris Lattner43e47542010-03-08 18:36:19 +00001396
1397 // Input argument?
1398 if (R->getName() == "node") {
1399 if (Dag->getArgName(0).empty())
1400 error("'node' argument requires a name to match with operand list");
1401 Args.push_back(Dag->getArgName(0));
1402 }
1403
Chris Lattner6cefb772008-01-05 22:25:12 +00001404 New = new TreePatternNode(DI);
1405 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1406 New = ParseTreePattern(DI);
1407 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1408 New = new TreePatternNode(II);
1409 if (!Dag->getArgName(0).empty())
1410 error("Constant int argument should not have a name!");
1411 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1412 // Turn this into an IntInit.
1413 Init *II = BI->convertInitializerTo(new IntRecTy());
1414 if (II == 0 || !dynamic_cast<IntInit*>(II))
1415 error("Bits value must be constants!");
1416
1417 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1418 if (!Dag->getArgName(0).empty())
1419 error("Constant int argument should not have a name!");
1420 } else {
1421 Arg->dump();
1422 error("Unknown leaf value for tree pattern!");
1423 return 0;
1424 }
1425
1426 // Apply the type cast.
1427 New->UpdateNodeType(getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001428 if (New->getNumChildren() == 0)
1429 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001430 return New;
1431 }
1432
1433 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001434 if (!Operator->isSubClassOf("PatFrag") &&
1435 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001436 !Operator->isSubClassOf("Instruction") &&
1437 !Operator->isSubClassOf("SDNodeXForm") &&
1438 !Operator->isSubClassOf("Intrinsic") &&
1439 Operator->getName() != "set" &&
1440 Operator->getName() != "implicit" &&
1441 Operator->getName() != "parallel")
1442 error("Unrecognized node '" + Operator->getName() + "'!");
1443
1444 // Check to see if this is something that is illegal in an input pattern.
1445 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1446 Operator->isSubClassOf("SDNodeXForm")))
1447 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1448
1449 std::vector<TreePatternNode*> Children;
1450
1451 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1452 Init *Arg = Dag->getArg(i);
1453 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1454 Children.push_back(ParseTreePattern(DI));
1455 if (Children.back()->getName().empty())
1456 Children.back()->setName(Dag->getArgName(i));
1457 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1458 Record *R = DefI->getDef();
1459 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1460 // TreePatternNode if its own.
1461 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001462 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001463 std::vector<std::pair<Init*, std::string> >()));
1464 --i; // Revisit this node...
1465 } else {
1466 TreePatternNode *Node = new TreePatternNode(DefI);
1467 Node->setName(Dag->getArgName(i));
1468 Children.push_back(Node);
1469
1470 // Input argument?
1471 if (R->getName() == "node") {
1472 if (Dag->getArgName(i).empty())
1473 error("'node' argument requires a name to match with operand list");
1474 Args.push_back(Dag->getArgName(i));
1475 }
1476 }
1477 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1478 TreePatternNode *Node = new TreePatternNode(II);
1479 if (!Dag->getArgName(i).empty())
1480 error("Constant int argument should not have a name!");
1481 Children.push_back(Node);
1482 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1483 // Turn this into an IntInit.
1484 Init *II = BI->convertInitializerTo(new IntRecTy());
1485 if (II == 0 || !dynamic_cast<IntInit*>(II))
1486 error("Bits value must be constants!");
1487
1488 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1489 if (!Dag->getArgName(i).empty())
1490 error("Constant int argument should not have a name!");
1491 Children.push_back(Node);
1492 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001493 errs() << '"';
Chris Lattner6cefb772008-01-05 22:25:12 +00001494 Arg->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001495 errs() << "\": ";
Chris Lattner6cefb772008-01-05 22:25:12 +00001496 error("Unknown leaf value for tree pattern!");
1497 }
1498 }
1499
1500 // If the operator is an intrinsic, then this is just syntactic sugar for for
1501 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1502 // convert the intrinsic name to a number.
1503 if (Operator->isSubClassOf("Intrinsic")) {
1504 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1505 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1506
1507 // If this intrinsic returns void, it must have side-effects and thus a
1508 // chain.
Owen Anderson825b72b2009-08-11 20:47:22 +00001509 if (Int.IS.RetVTs[0] == MVT::isVoid) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001510 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1511 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1512 // Has side-effects, requires chain.
1513 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1514 } else {
1515 // Otherwise, no chain.
1516 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1517 }
1518
1519 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1520 Children.insert(Children.begin(), IIDNode);
1521 }
1522
Nate Begeman7cee8172009-03-19 05:21:56 +00001523 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1524 Result->setName(Dag->getName());
1525 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001526}
1527
1528/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001529/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001530/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001531bool TreePattern::
1532InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1533 if (NamedNodes.empty())
1534 ComputeNamedNodes();
1535
Chris Lattner6cefb772008-01-05 22:25:12 +00001536 bool MadeChange = true;
1537 while (MadeChange) {
1538 MadeChange = false;
1539 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1540 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner2cacec52010-03-15 06:00:16 +00001541
1542 // If there are constraints on our named nodes, apply them.
1543 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1544 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1545 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1546
1547 // If we have input named node types, propagate their types to the named
1548 // values here.
1549 if (InNamedTypes) {
1550 // FIXME: Should be error?
1551 assert(InNamedTypes->count(I->getKey()) &&
1552 "Named node in output pattern but not input pattern?");
1553
1554 const SmallVectorImpl<TreePatternNode*> &InNodes =
1555 InNamedTypes->find(I->getKey())->second;
1556
1557 // The input types should be fully resolved by now.
1558 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1559 // If this node is a register class, and it is the root of the pattern
1560 // then we're mapping something onto an input register. We allow
1561 // changing the type of the input register in this case. This allows
1562 // us to match things like:
1563 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1564 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1565 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1566 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1567 continue;
1568 }
1569
1570 MadeChange |=Nodes[i]->UpdateNodeType(InNodes[0]->getExtType(),*this);
1571 }
1572 }
1573
1574 // If there are multiple nodes with the same name, they must all have the
1575 // same type.
1576 if (I->second.size() > 1) {
1577 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1578 MadeChange |=Nodes[i]->UpdateNodeType(Nodes[i+1]->getExtType(),*this);
1579 MadeChange |=Nodes[i+1]->UpdateNodeType(Nodes[i]->getExtType(),*this);
1580 }
1581 }
1582 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001583 }
1584
1585 bool HasUnresolvedTypes = false;
1586 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1587 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1588 return !HasUnresolvedTypes;
1589}
1590
Daniel Dunbar1a551802009-07-03 00:10:29 +00001591void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001592 OS << getRecord()->getName();
1593 if (!Args.empty()) {
1594 OS << "(" << Args[0];
1595 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1596 OS << ", " << Args[i];
1597 OS << ")";
1598 }
1599 OS << ": ";
1600
1601 if (Trees.size() > 1)
1602 OS << "[\n";
1603 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1604 OS << "\t";
1605 Trees[i]->print(OS);
1606 OS << "\n";
1607 }
1608
1609 if (Trees.size() > 1)
1610 OS << "]\n";
1611}
1612
Daniel Dunbar1a551802009-07-03 00:10:29 +00001613void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001614
1615//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001616// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001617//
1618
Chris Lattnerfe718932008-01-06 01:10:31 +00001619CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001620 Intrinsics = LoadIntrinsics(Records, false);
1621 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001622 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001623 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001624 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001625 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001626 ParseDefaultOperands();
1627 ParseInstructions();
1628 ParsePatterns();
1629
1630 // Generate variants. For example, commutative patterns can match
1631 // multiple ways. Add them to PatternsToMatch as well.
1632 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001633
1634 // Infer instruction flags. For example, we can detect loads,
1635 // stores, and side effects in many cases by examining an
1636 // instruction's pattern.
1637 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001638}
1639
Chris Lattnerfe718932008-01-06 01:10:31 +00001640CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001641 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001642 E = PatternFragments.end(); I != E; ++I)
1643 delete I->second;
1644}
1645
1646
Chris Lattnerfe718932008-01-06 01:10:31 +00001647Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001648 Record *N = Records.getDef(Name);
1649 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001650 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001651 exit(1);
1652 }
1653 return N;
1654}
1655
1656// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001657void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001658 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1659 while (!Nodes.empty()) {
1660 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1661 Nodes.pop_back();
1662 }
1663
Jim Grosbachda4231f2009-03-26 16:17:51 +00001664 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001665 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1666 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1667 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1668}
1669
1670/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1671/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001672void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001673 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1674 while (!Xforms.empty()) {
1675 Record *XFormNode = Xforms.back();
1676 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1677 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001678 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001679
1680 Xforms.pop_back();
1681 }
1682}
1683
Chris Lattnerfe718932008-01-06 01:10:31 +00001684void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001685 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1686 while (!AMs.empty()) {
1687 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1688 AMs.pop_back();
1689 }
1690}
1691
1692
1693/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1694/// file, building up the PatternFragments map. After we've collected them all,
1695/// inline fragments together as necessary, so that there are no references left
1696/// inside a pattern fragment to a pattern fragment.
1697///
Chris Lattnerfe718932008-01-06 01:10:31 +00001698void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001699 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1700
Chris Lattnerdc32f982008-01-05 22:43:57 +00001701 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001702 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1703 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1704 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1705 PatternFragments[Fragments[i]] = P;
1706
Chris Lattnerdc32f982008-01-05 22:43:57 +00001707 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001708 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001709 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001710
Chris Lattnerdc32f982008-01-05 22:43:57 +00001711 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001712 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1713
1714 // Parse the operands list.
1715 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1716 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1717 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001718 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001719 if (!OpsOp ||
1720 (OpsOp->getDef()->getName() != "ops" &&
1721 OpsOp->getDef()->getName() != "outs" &&
1722 OpsOp->getDef()->getName() != "ins"))
1723 P->error("Operands list should start with '(ops ... '!");
1724
1725 // Copy over the arguments.
1726 Args.clear();
1727 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1728 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1729 static_cast<DefInit*>(OpsList->getArg(j))->
1730 getDef()->getName() != "node")
1731 P->error("Operands list should all be 'node' values.");
1732 if (OpsList->getArgName(j).empty())
1733 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001734 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001735 P->error("'" + OpsList->getArgName(j) +
1736 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001737 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001738 Args.push_back(OpsList->getArgName(j));
1739 }
1740
Chris Lattnerdc32f982008-01-05 22:43:57 +00001741 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001742 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001743 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001744
Chris Lattnerdc32f982008-01-05 22:43:57 +00001745 // If there is a code init for this fragment, keep track of the fact that
1746 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001747 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001748 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001749 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001750
1751 // If there is a node transformation corresponding to this, keep track of
1752 // it.
1753 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1754 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1755 P->getOnlyTree()->setTransformFn(Transform);
1756 }
1757
Chris Lattner6cefb772008-01-05 22:25:12 +00001758 // Now that we've parsed all of the tree fragments, do a closure on them so
1759 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001760 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1761 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001762 ThePat->InlinePatternFragments();
1763
1764 // Infer as many types as possible. Don't worry about it if we don't infer
1765 // all of them, some may depend on the inputs of the pattern.
1766 try {
1767 ThePat->InferAllTypes();
1768 } catch (...) {
1769 // If this pattern fragment is not supported by this target (no types can
1770 // satisfy its constraints), just ignore it. If the bogus pattern is
1771 // actually used by instructions, the type consistency error will be
1772 // reported there.
1773 }
1774
1775 // If debugging, print out the pattern fragment result.
1776 DEBUG(ThePat->dump());
1777 }
1778}
1779
Chris Lattnerfe718932008-01-06 01:10:31 +00001780void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001781 std::vector<Record*> DefaultOps[2];
1782 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1783 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1784
1785 // Find some SDNode.
1786 assert(!SDNodes.empty() && "No SDNodes parsed?");
1787 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1788
1789 for (unsigned iter = 0; iter != 2; ++iter) {
1790 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1791 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1792
1793 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1794 // SomeSDnode so that we can parse this.
1795 std::vector<std::pair<Init*, std::string> > Ops;
1796 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1797 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1798 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001799 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001800
1801 // Create a TreePattern to parse this.
1802 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1803 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1804
1805 // Copy the operands over into a DAGDefaultOperand.
1806 DAGDefaultOperand DefaultOpInfo;
1807
1808 TreePatternNode *T = P.getTree(0);
1809 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1810 TreePatternNode *TPN = T->getChild(op);
1811 while (TPN->ApplyTypeConstraints(P, false))
1812 /* Resolve all types */;
1813
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001814 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001815 if (iter == 0)
1816 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001817 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00001818 else
1819 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001820 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001821 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001822 DefaultOpInfo.DefaultOps.push_back(TPN);
1823 }
1824
1825 // Insert it into the DefaultOperands map so we can find it later.
1826 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1827 }
1828 }
1829}
1830
1831/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1832/// instruction input. Return true if this is a real use.
1833static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1834 std::map<std::string, TreePatternNode*> &InstInputs,
1835 std::vector<Record*> &InstImpInputs) {
1836 // No name -> not interesting.
1837 if (Pat->getName().empty()) {
1838 if (Pat->isLeaf()) {
1839 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1840 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1841 I->error("Input " + DI->getDef()->getName() + " must be named!");
1842 else if (DI && DI->getDef()->isSubClassOf("Register"))
1843 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001844 }
1845 return false;
1846 }
1847
1848 Record *Rec;
1849 if (Pat->isLeaf()) {
1850 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1851 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1852 Rec = DI->getDef();
1853 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001854 Rec = Pat->getOperator();
1855 }
1856
1857 // SRCVALUE nodes are ignored.
1858 if (Rec->getName() == "srcvalue")
1859 return false;
1860
1861 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1862 if (!Slot) {
1863 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00001864 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00001865 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00001866 Record *SlotRec;
1867 if (Slot->isLeaf()) {
1868 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1869 } else {
1870 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1871 SlotRec = Slot->getOperator();
1872 }
1873
1874 // Ensure that the inputs agree if we've already seen this input.
1875 if (Rec != SlotRec)
1876 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner2cacec52010-03-15 06:00:16 +00001877 if (Slot->getExtType() != Pat->getExtType())
Chris Lattner53d09bd2010-02-23 05:59:10 +00001878 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00001879 return true;
1880}
1881
1882/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1883/// part of "I", the instruction), computing the set of inputs and outputs of
1884/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001885void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001886FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1887 std::map<std::string, TreePatternNode*> &InstInputs,
1888 std::map<std::string, TreePatternNode*>&InstResults,
1889 std::vector<Record*> &InstImpInputs,
1890 std::vector<Record*> &InstImpResults) {
1891 if (Pat->isLeaf()) {
1892 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1893 if (!isUse && Pat->getTransformFn())
1894 I->error("Cannot specify a transform function for a non-input value!");
1895 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001896 }
1897
1898 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001899 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1900 TreePatternNode *Dest = Pat->getChild(i);
1901 if (!Dest->isLeaf())
1902 I->error("implicitly defined value should be a register!");
1903
1904 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1905 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1906 I->error("implicitly defined value should be a register!");
1907 InstImpResults.push_back(Val->getDef());
1908 }
1909 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001910 }
1911
1912 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001913 // If this is not a set, verify that the children nodes are not void typed,
1914 // and recurse.
1915 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001916 if (Pat->getChild(i)->getType() == MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00001917 I->error("Cannot have void nodes inside of patterns!");
1918 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1919 InstImpInputs, InstImpResults);
1920 }
1921
1922 // If this is a non-leaf node with no children, treat it basically as if
1923 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00001924 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00001925
1926 if (!isUse && Pat->getTransformFn())
1927 I->error("Cannot specify a transform function for a non-input value!");
1928 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001929 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001930
1931 // Otherwise, this is a set, validate and collect instruction results.
1932 if (Pat->getNumChildren() == 0)
1933 I->error("set requires operands!");
1934
1935 if (Pat->getTransformFn())
1936 I->error("Cannot specify a transform function on a set node!");
1937
1938 // Check the set destinations.
1939 unsigned NumDests = Pat->getNumChildren()-1;
1940 for (unsigned i = 0; i != NumDests; ++i) {
1941 TreePatternNode *Dest = Pat->getChild(i);
1942 if (!Dest->isLeaf())
1943 I->error("set destination should be a register!");
1944
1945 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1946 if (!Val)
1947 I->error("set destination should be a register!");
1948
1949 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00001950 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001951 if (Dest->getName().empty())
1952 I->error("set destination must have a name!");
1953 if (InstResults.count(Dest->getName()))
1954 I->error("cannot set '" + Dest->getName() +"' multiple times");
1955 InstResults[Dest->getName()] = Dest;
1956 } else if (Val->getDef()->isSubClassOf("Register")) {
1957 InstImpResults.push_back(Val->getDef());
1958 } else {
1959 I->error("set destination should be a register!");
1960 }
1961 }
1962
1963 // Verify and collect info from the computation.
1964 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1965 InstInputs, InstResults,
1966 InstImpInputs, InstImpResults);
1967}
1968
Dan Gohmanee4fa192008-04-03 00:02:49 +00001969//===----------------------------------------------------------------------===//
1970// Instruction Analysis
1971//===----------------------------------------------------------------------===//
1972
1973class InstAnalyzer {
1974 const CodeGenDAGPatterns &CDP;
1975 bool &mayStore;
1976 bool &mayLoad;
1977 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00001978 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00001979public:
1980 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Chris Lattner1e506312010-03-19 05:34:15 +00001981 bool &maystore, bool &mayload, bool &hse, bool &isv)
1982 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
1983 IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00001984 }
1985
1986 /// Analyze - Analyze the specified instruction, returning true if the
1987 /// instruction had a pattern.
1988 bool Analyze(Record *InstRecord) {
1989 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1990 if (Pattern == 0) {
1991 HasSideEffects = 1;
1992 return false; // No pattern.
1993 }
1994
1995 // FIXME: Assume only the first tree is the pattern. The others are clobber
1996 // nodes.
1997 AnalyzeNode(Pattern->getTree(0));
1998 return true;
1999 }
2000
2001private:
2002 void AnalyzeNode(const TreePatternNode *N) {
2003 if (N->isLeaf()) {
2004 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2005 Record *LeafRec = DI->getDef();
2006 // Handle ComplexPattern leaves.
2007 if (LeafRec->isSubClassOf("ComplexPattern")) {
2008 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2009 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2010 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2011 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2012 }
2013 }
2014 return;
2015 }
2016
2017 // Analyze children.
2018 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2019 AnalyzeNode(N->getChild(i));
2020
2021 // Ignore set nodes, which are not SDNodes.
2022 if (N->getOperator()->getName() == "set")
2023 return;
2024
2025 // Get information about the SDNode for the operator.
2026 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2027
2028 // Notice properties of the node.
2029 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2030 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2031 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002032 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002033
2034 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2035 // If this is an intrinsic, analyze it.
2036 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2037 mayLoad = true;// These may load memory.
2038
2039 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2040 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2041
2042 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2043 // WriteMem intrinsics can have other strange effects.
2044 HasSideEffects = true;
2045 }
2046 }
2047
2048};
2049
2050static void InferFromPattern(const CodeGenInstruction &Inst,
2051 bool &MayStore, bool &MayLoad,
Chris Lattner1e506312010-03-19 05:34:15 +00002052 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002053 const CodeGenDAGPatterns &CDP) {
Chris Lattner1e506312010-03-19 05:34:15 +00002054 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002055
2056 bool HadPattern =
Chris Lattner1e506312010-03-19 05:34:15 +00002057 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2058 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002059
2060 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2061 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2062 // If we decided that this is a store from the pattern, then the .td file
2063 // entry is redundant.
2064 if (MayStore)
2065 fprintf(stderr,
2066 "Warning: mayStore flag explicitly set on instruction '%s'"
2067 " but flag already inferred from pattern.\n",
2068 Inst.TheDef->getName().c_str());
2069 MayStore = true;
2070 }
2071
2072 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2073 // If we decided that this is a load from the pattern, then the .td file
2074 // entry is redundant.
2075 if (MayLoad)
2076 fprintf(stderr,
2077 "Warning: mayLoad flag explicitly set on instruction '%s'"
2078 " but flag already inferred from pattern.\n",
2079 Inst.TheDef->getName().c_str());
2080 MayLoad = true;
2081 }
2082
2083 if (Inst.neverHasSideEffects) {
2084 if (HadPattern)
2085 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2086 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2087 HasSideEffects = false;
2088 }
2089
2090 if (Inst.hasSideEffects) {
2091 if (HasSideEffects)
2092 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2093 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2094 HasSideEffects = true;
2095 }
Chris Lattner1e506312010-03-19 05:34:15 +00002096
2097 if (Inst.isVariadic)
2098 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002099}
2100
Chris Lattner6cefb772008-01-05 22:25:12 +00002101/// ParseInstructions - Parse all of the instructions, inlining and resolving
2102/// any fragments involved. This populates the Instructions list with fully
2103/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002104void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002105 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2106
2107 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2108 ListInit *LI = 0;
2109
2110 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2111 LI = Instrs[i]->getValueAsListInit("Pattern");
2112
2113 // If there is no pattern, only collect minimal information about the
2114 // instruction for its operand list. We have to assume that there is one
2115 // result, as we have no detailed info.
2116 if (!LI || LI->getSize() == 0) {
2117 std::vector<Record*> Results;
2118 std::vector<Record*> Operands;
2119
Chris Lattnerf30187a2010-03-19 00:07:20 +00002120 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002121
2122 if (InstInfo.OperandList.size() != 0) {
2123 if (InstInfo.NumDefs == 0) {
2124 // These produce no results
2125 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2126 Operands.push_back(InstInfo.OperandList[j].Rec);
2127 } else {
2128 // Assume the first operand is the result.
2129 Results.push_back(InstInfo.OperandList[0].Rec);
2130
2131 // The rest are inputs.
2132 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2133 Operands.push_back(InstInfo.OperandList[j].Rec);
2134 }
2135 }
2136
2137 // Create and insert the instruction.
2138 std::vector<Record*> ImpResults;
2139 std::vector<Record*> ImpOperands;
2140 Instructions.insert(std::make_pair(Instrs[i],
2141 DAGInstruction(0, Results, Operands, ImpResults,
2142 ImpOperands)));
2143 continue; // no pattern.
2144 }
2145
2146 // Parse the instruction.
2147 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2148 // Inline pattern fragments into it.
2149 I->InlinePatternFragments();
2150
2151 // Infer as many types as possible. If we cannot infer all of them, we can
2152 // never do anything with this instruction pattern: report it to the user.
2153 if (!I->InferAllTypes())
2154 I->error("Could not infer all types in pattern!");
2155
2156 // InstInputs - Keep track of all of the inputs of the instruction, along
2157 // with the record they are declared as.
2158 std::map<std::string, TreePatternNode*> InstInputs;
2159
2160 // InstResults - Keep track of all the virtual registers that are 'set'
2161 // in the instruction, including what reg class they are.
2162 std::map<std::string, TreePatternNode*> InstResults;
2163
2164 std::vector<Record*> InstImpInputs;
2165 std::vector<Record*> InstImpResults;
2166
2167 // Verify that the top-level forms in the instruction are of void type, and
2168 // fill in the InstResults map.
2169 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2170 TreePatternNode *Pat = I->getTree(j);
Chris Lattner2cacec52010-03-15 06:00:16 +00002171 if (!Pat->hasTypeSet() || Pat->getType() != MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00002172 I->error("Top-level forms in instruction pattern should have"
2173 " void types");
2174
2175 // Find inputs and outputs, and verify the structure of the uses/defs.
2176 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2177 InstImpInputs, InstImpResults);
2178 }
2179
2180 // Now that we have inputs and outputs of the pattern, inspect the operands
2181 // list for the instruction. This determines the order that operands are
2182 // added to the machine instruction the node corresponds to.
2183 unsigned NumResults = InstResults.size();
2184
2185 // Parse the operands list from the (ops) list, validating it.
2186 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002187 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002188
2189 // Check that all of the results occur first in the list.
2190 std::vector<Record*> Results;
2191 TreePatternNode *Res0Node = NULL;
2192 for (unsigned i = 0; i != NumResults; ++i) {
2193 if (i == CGI.OperandList.size())
2194 I->error("'" + InstResults.begin()->first +
2195 "' set but does not appear in operand list!");
2196 const std::string &OpName = CGI.OperandList[i].Name;
2197
2198 // Check that it exists in InstResults.
2199 TreePatternNode *RNode = InstResults[OpName];
2200 if (RNode == 0)
2201 I->error("Operand $" + OpName + " does not exist in operand list!");
2202
2203 if (i == 0)
2204 Res0Node = RNode;
2205 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2206 if (R == 0)
2207 I->error("Operand $" + OpName + " should be a set destination: all "
2208 "outputs must occur before inputs in operand list!");
2209
2210 if (CGI.OperandList[i].Rec != R)
2211 I->error("Operand $" + OpName + " class mismatch!");
2212
2213 // Remember the return type.
2214 Results.push_back(CGI.OperandList[i].Rec);
2215
2216 // Okay, this one checks out.
2217 InstResults.erase(OpName);
2218 }
2219
2220 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2221 // the copy while we're checking the inputs.
2222 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2223
2224 std::vector<TreePatternNode*> ResultNodeOperands;
2225 std::vector<Record*> Operands;
2226 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2227 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2228 const std::string &OpName = Op.Name;
2229 if (OpName.empty())
2230 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2231
2232 if (!InstInputsCheck.count(OpName)) {
2233 // If this is an predicate operand or optional def operand with an
2234 // DefaultOps set filled in, we can ignore this. When we codegen it,
2235 // we will do so as always executed.
2236 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2237 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2238 // Does it have a non-empty DefaultOps field? If so, ignore this
2239 // operand.
2240 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2241 continue;
2242 }
2243 I->error("Operand $" + OpName +
2244 " does not appear in the instruction pattern");
2245 }
2246 TreePatternNode *InVal = InstInputsCheck[OpName];
2247 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2248
2249 if (InVal->isLeaf() &&
2250 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2251 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2252 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2253 I->error("Operand $" + OpName + "'s register class disagrees"
2254 " between the operand and pattern");
2255 }
2256 Operands.push_back(Op.Rec);
2257
2258 // Construct the result for the dest-pattern operand list.
2259 TreePatternNode *OpNode = InVal->clone();
2260
2261 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002262 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002263
2264 // Promote the xform function to be an explicit node if set.
2265 if (Record *Xform = OpNode->getTransformFn()) {
2266 OpNode->setTransformFn(0);
2267 std::vector<TreePatternNode*> Children;
2268 Children.push_back(OpNode);
2269 OpNode = new TreePatternNode(Xform, Children);
2270 }
2271
2272 ResultNodeOperands.push_back(OpNode);
2273 }
2274
2275 if (!InstInputsCheck.empty())
2276 I->error("Input operand $" + InstInputsCheck.begin()->first +
2277 " occurs in pattern but not in operands list!");
2278
2279 TreePatternNode *ResultPattern =
2280 new TreePatternNode(I->getRecord(), ResultNodeOperands);
2281 // Copy fully inferred output node type to instruction result pattern.
2282 if (NumResults > 0)
Chris Lattner2cacec52010-03-15 06:00:16 +00002283 ResultPattern->setType(Res0Node->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002284
2285 // Create and insert the instruction.
2286 // FIXME: InstImpResults and InstImpInputs should not be part of
2287 // DAGInstruction.
2288 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2289 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2290
2291 // Use a temporary tree pattern to infer all types and make sure that the
2292 // constructed result is correct. This depends on the instruction already
2293 // being inserted into the Instructions map.
2294 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002295 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002296
2297 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2298 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2299
2300 DEBUG(I->dump());
2301 }
2302
2303 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002304 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2305 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002306 E = Instructions.end(); II != E; ++II) {
2307 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002308 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002309 if (I == 0) continue; // No pattern.
2310
2311 // FIXME: Assume only the first tree is the pattern. The others are clobber
2312 // nodes.
2313 TreePatternNode *Pattern = I->getTree(0);
2314 TreePatternNode *SrcPattern;
2315 if (Pattern->getOperator()->getName() == "set") {
2316 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2317 } else{
2318 // Not a set (store or something?)
2319 SrcPattern = Pattern;
2320 }
2321
Chris Lattner6cefb772008-01-05 22:25:12 +00002322 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002323 AddPatternToMatch(I,
2324 PatternToMatch(Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002325 SrcPattern,
2326 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002327 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002328 Instr->getValueAsInt("AddedComplexity"),
2329 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002330 }
2331}
2332
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002333
2334typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2335
Chris Lattner967d54a2010-02-23 06:35:45 +00002336static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002337 std::map<std::string, NameRecord> &Names,
2338 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002339 if (!P->getName().empty()) {
2340 NameRecord &Rec = Names[P->getName()];
2341 // If this is the first instance of the name, remember the node.
2342 if (Rec.second++ == 0)
2343 Rec.first = P;
Chris Lattner2cacec52010-03-15 06:00:16 +00002344 else if (Rec.first->getType() != P->getType())
Chris Lattnera27234e2010-02-23 07:22:28 +00002345 PatternTop->error("repetition of value: $" + P->getName() +
2346 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002347 }
Chris Lattner967d54a2010-02-23 06:35:45 +00002348
2349 if (!P->isLeaf()) {
2350 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002351 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002352 }
2353}
2354
Chris Lattner25b6f912010-02-23 06:16:51 +00002355void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2356 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002357 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002358 std::string Reason;
2359 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002360 Pattern->error("Pattern can never match: " + Reason);
Chris Lattner25b6f912010-02-23 06:16:51 +00002361
Chris Lattner405f1252010-03-01 22:29:19 +00002362 // If the source pattern's root is a complex pattern, that complex pattern
2363 // must specify the nodes it can potentially match.
2364 if (const ComplexPattern *CP =
2365 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2366 if (CP->getRootNodes().empty())
2367 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2368 " could match");
2369
2370
Chris Lattner967d54a2010-02-23 06:35:45 +00002371 // Find all of the named values in the input and output, ensure they have the
2372 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002373 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002374 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2375 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002376
2377 // Scan all of the named values in the destination pattern, rejecting them if
2378 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002379 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002380 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002381 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002382 Pattern->error("Pattern has input without matching name in output: $" +
2383 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002384 }
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002385
2386 // Scan all of the named values in the source pattern, rejecting them if the
2387 // name isn't used in the dest, and isn't used to tie two values together.
2388 for (std::map<std::string, NameRecord>::iterator
2389 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2390 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2391 Pattern->error("Pattern has dead named input: $" + I->first);
2392
Chris Lattner25b6f912010-02-23 06:16:51 +00002393 PatternsToMatch.push_back(PTM);
2394}
2395
2396
Dan Gohmanee4fa192008-04-03 00:02:49 +00002397
2398void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002399 const std::vector<const CodeGenInstruction*> &Instructions =
2400 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002401 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2402 CodeGenInstruction &InstInfo =
2403 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002404 // Determine properties of the instruction from its pattern.
Chris Lattner1e506312010-03-19 05:34:15 +00002405 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2406 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2407 *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002408 InstInfo.mayStore = MayStore;
2409 InstInfo.mayLoad = MayLoad;
2410 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002411 InstInfo.isVariadic = IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002412 }
2413}
2414
Chris Lattner2cacec52010-03-15 06:00:16 +00002415/// Given a pattern result with an unresolved type, see if we can find one
2416/// instruction with an unresolved result type. Force this result type to an
2417/// arbitrary element if it's possible types to converge results.
2418static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2419 if (N->isLeaf())
2420 return false;
2421
2422 // Analyze children.
2423 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2424 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2425 return true;
2426
2427 if (!N->getOperator()->isSubClassOf("Instruction"))
2428 return false;
2429
2430 // If this type is already concrete or completely unknown we can't do
2431 // anything.
2432 if (N->getExtType().isCompletelyUnknown() || N->getExtType().isConcrete())
2433 return false;
2434
2435 // Otherwise, force its type to the first possibility (an arbitrary choice).
2436 return N->getExtType().MergeInTypeInfo(N->getExtType().getTypeList()[0], TP);
2437}
2438
Chris Lattnerfe718932008-01-06 01:10:31 +00002439void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002440 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2441
2442 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2443 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2444 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2445 Record *Operator = OpDef->getDef();
2446 TreePattern *Pattern;
2447 if (Operator->getName() != "parallel")
2448 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2449 else {
2450 std::vector<Init*> Values;
David Greenee1b46912009-06-08 20:23:18 +00002451 RecTy *ListTy = 0;
2452 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002453 Values.push_back(Tree->getArg(j));
David Greenee1b46912009-06-08 20:23:18 +00002454 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2455 if (TArg == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002456 errs() << "In dag: " << Tree->getAsString();
2457 errs() << " -- Untyped argument in pattern\n";
David Greenee1b46912009-06-08 20:23:18 +00002458 assert(0 && "Untyped argument in pattern");
2459 }
2460 if (ListTy != 0) {
2461 ListTy = resolveTypes(ListTy, TArg->getType());
2462 if (ListTy == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002463 errs() << "In dag: " << Tree->getAsString();
2464 errs() << " -- Incompatible types in pattern arguments\n";
David Greenee1b46912009-06-08 20:23:18 +00002465 assert(0 && "Incompatible types in pattern arguments");
2466 }
2467 }
2468 else {
Bill Wendlingee1f6b02009-06-09 18:49:42 +00002469 ListTy = TArg->getType();
David Greenee1b46912009-06-08 20:23:18 +00002470 }
2471 }
2472 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
Chris Lattner6cefb772008-01-05 22:25:12 +00002473 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2474 }
2475
2476 // Inline pattern fragments into it.
2477 Pattern->InlinePatternFragments();
2478
2479 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2480 if (LI->getSize() == 0) continue; // no pattern.
2481
2482 // Parse the instruction.
2483 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2484
2485 // Inline pattern fragments into it.
2486 Result->InlinePatternFragments();
2487
2488 if (Result->getNumTrees() != 1)
2489 Result->error("Cannot handle instructions producing instructions "
2490 "with temporaries yet!");
2491
2492 bool IterateInference;
2493 bool InferredAllPatternTypes, InferredAllResultTypes;
2494 do {
2495 // Infer as many types as possible. If we cannot infer all of them, we
2496 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002497 InferredAllPatternTypes =
2498 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002499
2500 // Infer as many types as possible. If we cannot infer all of them, we
2501 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002502 InferredAllResultTypes =
2503 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002504
Chris Lattner6c6ba362010-03-18 23:15:10 +00002505 IterateInference = false;
2506
Chris Lattner6cefb772008-01-05 22:25:12 +00002507 // Apply the type of the result to the source pattern. This helps us
2508 // resolve cases where the input type is known to be a pointer type (which
2509 // is considered resolved), but the result knows it needs to be 32- or
2510 // 64-bits. Infer the other way for good measure.
Chris Lattner6c6ba362010-03-18 23:15:10 +00002511 if (!Result->getTree(0)->getExtType().isVoid() &&
2512 !Pattern->getTree(0)->getExtType().isVoid()) {
2513 IterateInference = Pattern->getTree(0)->
2514 UpdateNodeType(Result->getTree(0)->getExtType(), *Result);
2515 IterateInference |= Result->getTree(0)->
2516 UpdateNodeType(Pattern->getTree(0)->getExtType(), *Result);
2517 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002518
2519 // If our iteration has converged and the input pattern's types are fully
2520 // resolved but the result pattern is not fully resolved, we may have a
2521 // situation where we have two instructions in the result pattern and
2522 // the instructions require a common register class, but don't care about
2523 // what actual MVT is used. This is actually a bug in our modelling:
2524 // output patterns should have register classes, not MVTs.
2525 //
2526 // In any case, to handle this, we just go through and disambiguate some
2527 // arbitrary types to the result pattern's nodes.
2528 if (!IterateInference && InferredAllPatternTypes &&
2529 !InferredAllResultTypes)
2530 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2531 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002532 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002533
Chris Lattner6cefb772008-01-05 22:25:12 +00002534 // Verify that we inferred enough types that we can do something with the
2535 // pattern and result. If these fire the user has to add type casts.
2536 if (!InferredAllPatternTypes)
2537 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002538 if (!InferredAllResultTypes) {
2539 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002540 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002541 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002542
2543 // Validate that the input pattern is correct.
2544 std::map<std::string, TreePatternNode*> InstInputs;
2545 std::map<std::string, TreePatternNode*> InstResults;
2546 std::vector<Record*> InstImpInputs;
2547 std::vector<Record*> InstImpResults;
2548 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2549 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2550 InstInputs, InstResults,
2551 InstImpInputs, InstImpResults);
2552
2553 // Promote the xform function to be an explicit node if set.
2554 TreePatternNode *DstPattern = Result->getOnlyTree();
2555 std::vector<TreePatternNode*> ResultNodeOperands;
2556 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2557 TreePatternNode *OpNode = DstPattern->getChild(ii);
2558 if (Record *Xform = OpNode->getTransformFn()) {
2559 OpNode->setTransformFn(0);
2560 std::vector<TreePatternNode*> Children;
2561 Children.push_back(OpNode);
2562 OpNode = new TreePatternNode(Xform, Children);
2563 }
2564 ResultNodeOperands.push_back(OpNode);
2565 }
2566 DstPattern = Result->getOnlyTree();
2567 if (!DstPattern->isLeaf())
2568 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2569 ResultNodeOperands);
Chris Lattner2cacec52010-03-15 06:00:16 +00002570 DstPattern->setType(Result->getOnlyTree()->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002571 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2572 Temp.InferAllTypes();
2573
Chris Lattner6cefb772008-01-05 22:25:12 +00002574
Chris Lattner25b6f912010-02-23 06:16:51 +00002575 AddPatternToMatch(Pattern,
2576 PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2577 Pattern->getTree(0),
2578 Temp.getOnlyTree(), InstImpResults,
Chris Lattner117ccb72010-03-01 22:09:11 +00002579 Patterns[i]->getValueAsInt("AddedComplexity"),
2580 Patterns[i]->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002581 }
2582}
2583
2584/// CombineChildVariants - Given a bunch of permutations of each child of the
2585/// 'operator' node, put them together in all possible ways.
2586static void CombineChildVariants(TreePatternNode *Orig,
2587 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2588 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002589 CodeGenDAGPatterns &CDP,
2590 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002591 // Make sure that each operand has at least one variant to choose from.
2592 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2593 if (ChildVariants[i].empty())
2594 return;
2595
2596 // The end result is an all-pairs construction of the resultant pattern.
2597 std::vector<unsigned> Idxs;
2598 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002599 bool NotDone;
2600 do {
2601#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002602 DEBUG(if (!Idxs.empty()) {
2603 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2604 for (unsigned i = 0; i < Idxs.size(); ++i) {
2605 errs() << Idxs[i] << " ";
2606 }
2607 errs() << "]\n";
2608 });
Scott Michel327d0652008-03-05 17:49:05 +00002609#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002610 // Create the variant and add it to the output list.
2611 std::vector<TreePatternNode*> NewChildren;
2612 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2613 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2614 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2615
2616 // Copy over properties.
2617 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002618 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002619 R->setTransformFn(Orig->getTransformFn());
Chris Lattner2cacec52010-03-15 06:00:16 +00002620 R->setType(Orig->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002621
Scott Michel327d0652008-03-05 17:49:05 +00002622 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002623 std::string ErrString;
2624 if (!R->canPatternMatch(ErrString, CDP)) {
2625 delete R;
2626 } else {
2627 bool AlreadyExists = false;
2628
2629 // Scan to see if this pattern has already been emitted. We can get
2630 // duplication due to things like commuting:
2631 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2632 // which are the same pattern. Ignore the dups.
2633 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002634 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002635 AlreadyExists = true;
2636 break;
2637 }
2638
2639 if (AlreadyExists)
2640 delete R;
2641 else
2642 OutVariants.push_back(R);
2643 }
2644
Scott Michel327d0652008-03-05 17:49:05 +00002645 // Increment indices to the next permutation by incrementing the
2646 // indicies from last index backward, e.g., generate the sequence
2647 // [0, 0], [0, 1], [1, 0], [1, 1].
2648 int IdxsIdx;
2649 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2650 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2651 Idxs[IdxsIdx] = 0;
2652 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002653 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002654 }
Scott Michel327d0652008-03-05 17:49:05 +00002655 NotDone = (IdxsIdx >= 0);
2656 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002657}
2658
2659/// CombineChildVariants - A helper function for binary operators.
2660///
2661static void CombineChildVariants(TreePatternNode *Orig,
2662 const std::vector<TreePatternNode*> &LHS,
2663 const std::vector<TreePatternNode*> &RHS,
2664 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002665 CodeGenDAGPatterns &CDP,
2666 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002667 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2668 ChildVariants.push_back(LHS);
2669 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002670 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002671}
2672
2673
2674static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2675 std::vector<TreePatternNode *> &Children) {
2676 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2677 Record *Operator = N->getOperator();
2678
2679 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002680 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002681 N->getTransformFn()) {
2682 Children.push_back(N);
2683 return;
2684 }
2685
2686 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2687 Children.push_back(N->getChild(0));
2688 else
2689 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2690
2691 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2692 Children.push_back(N->getChild(1));
2693 else
2694 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2695}
2696
2697/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2698/// the (potentially recursive) pattern by using algebraic laws.
2699///
2700static void GenerateVariantsOf(TreePatternNode *N,
2701 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002702 CodeGenDAGPatterns &CDP,
2703 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002704 // We cannot permute leaves.
2705 if (N->isLeaf()) {
2706 OutVariants.push_back(N);
2707 return;
2708 }
2709
2710 // Look up interesting info about the node.
2711 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2712
Jim Grosbachda4231f2009-03-26 16:17:51 +00002713 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002714 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002715 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002716 std::vector<TreePatternNode*> MaximalChildren;
2717 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2718
2719 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2720 // permutations.
2721 if (MaximalChildren.size() == 3) {
2722 // Find the variants of all of our maximal children.
2723 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002724 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2725 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2726 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002727
2728 // There are only two ways we can permute the tree:
2729 // (A op B) op C and A op (B op C)
2730 // Within these forms, we can also permute A/B/C.
2731
2732 // Generate legal pair permutations of A/B/C.
2733 std::vector<TreePatternNode*> ABVariants;
2734 std::vector<TreePatternNode*> BAVariants;
2735 std::vector<TreePatternNode*> ACVariants;
2736 std::vector<TreePatternNode*> CAVariants;
2737 std::vector<TreePatternNode*> BCVariants;
2738 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002739 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2740 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2741 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2742 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2743 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2744 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002745
2746 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002747 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2748 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2749 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2750 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2751 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2752 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002753
2754 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002755 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2756 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2757 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2758 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2759 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2760 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002761 return;
2762 }
2763 }
2764
2765 // Compute permutations of all children.
2766 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2767 ChildVariants.resize(N->getNumChildren());
2768 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002769 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002770
2771 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002772 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002773
2774 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002775 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2776 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2777 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2778 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002779 // Don't count children which are actually register references.
2780 unsigned NC = 0;
2781 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2782 TreePatternNode *Child = N->getChild(i);
2783 if (Child->isLeaf())
2784 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2785 Record *RR = DI->getDef();
2786 if (RR->isSubClassOf("Register"))
2787 continue;
2788 }
2789 NC++;
2790 }
2791 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002792 if (isCommIntrinsic) {
2793 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2794 // operands are the commutative operands, and there might be more operands
2795 // after those.
2796 assert(NC >= 3 &&
2797 "Commutative intrinsic should have at least 3 childrean!");
2798 std::vector<std::vector<TreePatternNode*> > Variants;
2799 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2800 Variants.push_back(ChildVariants[2]);
2801 Variants.push_back(ChildVariants[1]);
2802 for (unsigned i = 3; i != NC; ++i)
2803 Variants.push_back(ChildVariants[i]);
2804 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2805 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002806 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002807 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002808 }
2809}
2810
2811
2812// GenerateVariants - Generate variants. For example, commutative patterns can
2813// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002814void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002815 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002816
2817 // Loop over all of the patterns we've collected, checking to see if we can
2818 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002819 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002820 // the .td file having to contain tons of variants of instructions.
2821 //
2822 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2823 // intentionally do not reconsider these. Any variants of added patterns have
2824 // already been added.
2825 //
2826 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002827 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002828 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002829 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002830 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002831 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002832 DEBUG(errs() << "\n");
Scott Michel327d0652008-03-05 17:49:05 +00002833 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002834
2835 assert(!Variants.empty() && "Must create at least original variant!");
2836 Variants.erase(Variants.begin()); // Remove the original pattern.
2837
2838 if (Variants.empty()) // No variants for this pattern.
2839 continue;
2840
Chris Lattner569f1212009-08-23 04:44:11 +00002841 DEBUG(errs() << "FOUND VARIANTS OF: ";
2842 PatternsToMatch[i].getSrcPattern()->dump();
2843 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002844
2845 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2846 TreePatternNode *Variant = Variants[v];
2847
Chris Lattner569f1212009-08-23 04:44:11 +00002848 DEBUG(errs() << " VAR#" << v << ": ";
2849 Variant->dump();
2850 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002851
2852 // Scan to see if an instruction or explicit pattern already matches this.
2853 bool AlreadyExists = false;
2854 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00002855 // Skip if the top level predicates do not match.
2856 if (PatternsToMatch[i].getPredicates() !=
2857 PatternsToMatch[p].getPredicates())
2858 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00002859 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002860 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00002861 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002862 AlreadyExists = true;
2863 break;
2864 }
2865 }
2866 // If we already have it, ignore the variant.
2867 if (AlreadyExists) continue;
2868
2869 // Otherwise, add it to the list of patterns we have.
2870 PatternsToMatch.
2871 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2872 Variant, PatternsToMatch[i].getDstPattern(),
2873 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002874 PatternsToMatch[i].getAddedComplexity(),
2875 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002876 }
2877
Chris Lattner569f1212009-08-23 04:44:11 +00002878 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002879 }
2880}
2881