blob: e09a10103dee40008c3b4332400e43aa18230010 [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}
31
Owen Anderson825b72b2009-08-11 20:47:22 +000032static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000033 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000034}
35
Owen Anderson825b72b2009-08-11 20:47:22 +000036static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000037 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000038}
39
Chris Lattner2cacec52010-03-15 06:00:16 +000040EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
41 if (VT == MVT::iAny)
42 EnforceInteger(TP);
43 else if (VT == MVT::fAny)
44 EnforceFloatingPoint(TP);
45 else if (VT == MVT::vAny)
46 EnforceVector(TP);
47 else {
48 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
49 VT == MVT::iPTRAny) && "Not a concrete type!");
50 TypeVec.push_back(VT);
51 }
Chris Lattner6cefb772008-01-05 22:25:12 +000052}
53
Chris Lattner2cacec52010-03-15 06:00:16 +000054
55EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
56 assert(!VTList.empty() && "empty list?");
57 TypeVec.append(VTList.begin(), VTList.end());
58
59 if (!VTList.empty())
60 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
61 VTList[0] != MVT::fAny);
62
63 // Remove duplicates.
64 array_pod_sort(TypeVec.begin(), TypeVec.end());
65 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Chris Lattner6cefb772008-01-05 22:25:12 +000066}
67
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000068/// FillWithPossibleTypes - Set to all legal types and return true, only valid
69/// on completely unknown type sets.
70bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP) {
71 assert(isCompletelyUnknown());
72 *this = TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
73 return true;
74}
Chris Lattner2cacec52010-03-15 06:00:16 +000075
76/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
77/// integer value type.
78bool EEVT::TypeSet::hasIntegerTypes() const {
79 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
80 if (isInteger(TypeVec[i]))
81 return true;
82 return false;
83}
84
85/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
86/// a floating point value type.
87bool EEVT::TypeSet::hasFloatingPointTypes() const {
88 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
89 if (isFloatingPoint(TypeVec[i]))
90 return true;
91 return false;
92}
93
94/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
95/// value type.
96bool EEVT::TypeSet::hasVectorTypes() const {
97 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
98 if (isVector(TypeVec[i]))
99 return true;
100 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +0000101}
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000102
Chris Lattner2cacec52010-03-15 06:00:16 +0000103
104std::string EEVT::TypeSet::getName() const {
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000105 if (TypeVec.empty()) return "<empty>";
Chris Lattner2cacec52010-03-15 06:00:16 +0000106
107 std::string Result;
108
109 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
110 std::string VTName = llvm::getEnumName(TypeVec[i]);
111 // Strip off MVT:: prefix if present.
112 if (VTName.substr(0,5) == "MVT::")
113 VTName = VTName.substr(5);
114 if (i) Result += ':';
115 Result += VTName;
116 }
117
118 if (TypeVec.size() == 1)
119 return Result;
120 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000121}
Chris Lattner2cacec52010-03-15 06:00:16 +0000122
123/// MergeInTypeInfo - This merges in type information from the specified
124/// argument. If 'this' changes, it returns true. If the two types are
125/// contradictory (e.g. merge f32 into i32) then this throws an exception.
126bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
127 if (InVT.isCompletelyUnknown() || *this == InVT)
128 return false;
129
130 if (isCompletelyUnknown()) {
131 *this = InVT;
132 return true;
133 }
134
135 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
136
137 // Handle the abstract cases, seeing if we can resolve them better.
138 switch (TypeVec[0]) {
139 default: break;
140 case MVT::iPTR:
141 case MVT::iPTRAny:
142 if (InVT.hasIntegerTypes()) {
143 EEVT::TypeSet InCopy(InVT);
144 InCopy.EnforceInteger(TP);
145 InCopy.EnforceScalar(TP);
146
147 if (InCopy.isConcrete()) {
148 // If the RHS has one integer type, upgrade iPTR to i32.
149 TypeVec[0] = InVT.TypeVec[0];
150 return true;
151 }
152
153 // If the input has multiple scalar integers, this doesn't add any info.
154 if (!InCopy.isCompletelyUnknown())
155 return false;
156 }
157 break;
158 }
159
160 // If the input constraint is iAny/iPTR and this is an integer type list,
161 // remove non-integer types from the list.
162 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
163 hasIntegerTypes()) {
164 bool MadeChange = EnforceInteger(TP);
165
166 // If we're merging in iPTR/iPTRAny and the node currently has a list of
167 // multiple different integer types, replace them with a single iPTR.
168 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
169 TypeVec.size() != 1) {
170 TypeVec.resize(1);
171 TypeVec[0] = InVT.TypeVec[0];
172 MadeChange = true;
173 }
174
175 return MadeChange;
176 }
177
178 // If this is a type list and the RHS is a typelist as well, eliminate entries
179 // from this list that aren't in the other one.
180 bool MadeChange = false;
181 TypeSet InputSet(*this);
182
183 for (unsigned i = 0; i != TypeVec.size(); ++i) {
184 bool InInVT = false;
185 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
186 if (TypeVec[i] == InVT.TypeVec[j]) {
187 InInVT = true;
188 break;
189 }
190
191 if (InInVT) continue;
192 TypeVec.erase(TypeVec.begin()+i--);
193 MadeChange = true;
194 }
195
196 // If we removed all of our types, we have a type contradiction.
197 if (!TypeVec.empty())
198 return MadeChange;
199
200 // FIXME: Really want an SMLoc here!
201 TP.error("Type inference contradiction found, merging '" +
202 InVT.getName() + "' into '" + InputSet.getName() + "'");
203 return true; // unreachable
204}
205
206/// EnforceInteger - Remove all non-integer types from this set.
207bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
208 TypeSet InputSet(*this);
209 bool MadeChange = false;
210
211 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000212 if (TypeVec.empty())
213 MadeChange = FillWithPossibleTypes(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000214
215 if (!hasFloatingPointTypes())
216 return MadeChange;
217
218 // Filter out all the fp types.
219 for (unsigned i = 0; i != TypeVec.size(); ++i)
220 if (isFloatingPoint(TypeVec[i]))
221 TypeVec.erase(TypeVec.begin()+i--);
222
223 if (TypeVec.empty())
224 TP.error("Type inference contradiction found, '" +
225 InputSet.getName() + "' needs to be integer");
226 return MadeChange;
227}
228
229/// EnforceFloatingPoint - Remove all integer types from this set.
230bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
231 TypeSet InputSet(*this);
232 bool MadeChange = false;
233
234 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000235 if (TypeVec.empty())
236 MadeChange = FillWithPossibleTypes(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000237
238 if (!hasIntegerTypes())
239 return MadeChange;
240
241 // Filter out all the fp types.
242 for (unsigned i = 0; i != TypeVec.size(); ++i)
243 if (isInteger(TypeVec[i]))
244 TypeVec.erase(TypeVec.begin()+i--);
245
246 if (TypeVec.empty())
247 TP.error("Type inference contradiction found, '" +
248 InputSet.getName() + "' needs to be floating point");
249 return MadeChange;
250}
251
252/// EnforceScalar - Remove all vector types from this.
253bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
254 TypeSet InputSet(*this);
255 bool MadeChange = false;
256
257 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000258 if (TypeVec.empty())
259 MadeChange = FillWithPossibleTypes(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000260
261 if (!hasVectorTypes())
262 return MadeChange;
263
264 // Filter out all the vector types.
265 for (unsigned i = 0; i != TypeVec.size(); ++i)
266 if (isVector(TypeVec[i]))
267 TypeVec.erase(TypeVec.begin()+i--);
268
269 if (TypeVec.empty())
270 TP.error("Type inference contradiction found, '" +
271 InputSet.getName() + "' needs to be scalar");
272 return MadeChange;
273}
274
275/// EnforceVector - Remove all vector types from this.
276bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
277 TypeSet InputSet(*this);
278 bool MadeChange = false;
279
280 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000281 if (TypeVec.empty())
282 MadeChange = FillWithPossibleTypes(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000283
284 // Filter out all the scalar types.
285 for (unsigned i = 0; i != TypeVec.size(); ++i)
286 if (!isVector(TypeVec[i]))
287 TypeVec.erase(TypeVec.begin()+i--);
288
289 if (TypeVec.empty())
290 TP.error("Type inference contradiction found, '" +
291 InputSet.getName() + "' needs to be a vector");
292 return MadeChange;
293}
294
295
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000296
Chris Lattner2cacec52010-03-15 06:00:16 +0000297/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
298/// this an other based on this information.
299bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
300 // Both operands must be integer or FP, but we don't care which.
301 bool MadeChange = false;
302
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000303 if (isCompletelyUnknown())
304 MadeChange = FillWithPossibleTypes(TP);
305
306 if (Other.isCompletelyUnknown())
307 MadeChange = Other.FillWithPossibleTypes(TP);
308
309 // If one side is known to be integer or known to be FP but the other side has
310 // no information, get at least the type integrality info in there.
311 if (!hasFloatingPointTypes())
312 MadeChange |= Other.EnforceInteger(TP);
313 else if (!hasIntegerTypes())
314 MadeChange |= Other.EnforceFloatingPoint(TP);
315 if (!Other.hasFloatingPointTypes())
316 MadeChange |= EnforceInteger(TP);
317 else if (!Other.hasIntegerTypes())
318 MadeChange |= EnforceFloatingPoint(TP);
319
320 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
321 "Should have a type list now");
322
323 // If one contains vectors but the other doesn't pull vectors out.
324 if (!hasVectorTypes())
325 MadeChange |= Other.EnforceScalar(TP);
326 if (!hasVectorTypes())
327 MadeChange |= EnforceScalar(TP);
328
Chris Lattner2cacec52010-03-15 06:00:16 +0000329 // This code does not currently handle nodes which have multiple types,
330 // where some types are integer, and some are fp. Assert that this is not
331 // the case.
332 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
333 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
334 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000335
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000336 // Okay, find the smallest type from the current set and remove it from the
337 // largest set.
338 MVT::SimpleValueType Smallest = TypeVec[0];
339 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
340 if (TypeVec[i] < Smallest)
341 Smallest = TypeVec[i];
Chris Lattner2cacec52010-03-15 06:00:16 +0000342
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000343 // If this is the only type in the large set, the constraint can never be
344 // satisfied.
345 if (Other.TypeVec.size() == 1 && Other.TypeVec[0] == Smallest)
346 TP.error("Type inference contradiction found, '" +
347 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000348
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000349 SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
350 std::find(Other.TypeVec.begin(), Other.TypeVec.end(), Smallest);
351 if (TVI != Other.TypeVec.end()) {
352 Other.TypeVec.erase(TVI);
353 MadeChange = true;
354 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000355
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000356 // Okay, find the largest type in the Other set and remove it from the
357 // current set.
358 MVT::SimpleValueType Largest = Other.TypeVec[0];
359 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
360 if (Other.TypeVec[i] > Largest)
361 Largest = Other.TypeVec[i];
Chris Lattner2cacec52010-03-15 06:00:16 +0000362
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000363 // If this is the only type in the small set, the constraint can never be
364 // satisfied.
365 if (TypeVec.size() == 1 && TypeVec[0] == Largest)
366 TP.error("Type inference contradiction found, '" +
367 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
368
369 TVI = std::find(TypeVec.begin(), TypeVec.end(), Largest);
370 if (TVI != TypeVec.end()) {
371 TypeVec.erase(TVI);
372 MadeChange = true;
373 }
374
375 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000376}
377
378/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
379/// whose element is VT.
380bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
381 TreePattern &TP) {
382 TypeSet InputSet(*this);
383 bool MadeChange = false;
384
385 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000386 if (TypeVec.empty())
387 MadeChange = FillWithPossibleTypes(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000388
389 // Filter out all the non-vector types and types which don't have the right
390 // element type.
391 for (unsigned i = 0; i != TypeVec.size(); ++i)
392 if (!isVector(TypeVec[i]) ||
393 EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
394 TypeVec.erase(TypeVec.begin()+i--);
395 MadeChange = true;
396 }
397
398 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
399 TP.error("Type inference contradiction found, forcing '" +
400 InputSet.getName() + "' to have a vector element");
401 return MadeChange;
402}
403
404//===----------------------------------------------------------------------===//
405// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000406
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000407bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
408 return LHS->getID() < RHS->getID();
409}
Scott Michel327d0652008-03-05 17:49:05 +0000410
411/// Dependent variable map for CodeGenDAGPattern variant generation
412typedef std::map<std::string, int> DepVarMap;
413
414/// Const iterator shorthand for DepVarMap
415typedef DepVarMap::const_iterator DepVarMap_citer;
416
417namespace {
418void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
419 if (N->isLeaf()) {
420 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
421 DepMap[N->getName()]++;
422 }
423 } else {
424 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
425 FindDepVarsOf(N->getChild(i), DepMap);
426 }
427}
428
429//! Find dependent variables within child patterns
430/*!
431 */
432void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
433 DepVarMap depcounts;
434 FindDepVarsOf(N, depcounts);
435 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
436 if (i->second > 1) { // std::pair<std::string, int>
437 DepVars.insert(i->first);
438 }
439 }
440}
441
442//! Dump the dependent variable set:
443void DumpDepVars(MultipleUseVarSet &DepVars) {
444 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000445 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000446 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000447 DEBUG(errs() << "[ ");
Scott Michel327d0652008-03-05 17:49:05 +0000448 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
449 i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000450 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000451 }
Chris Lattner569f1212009-08-23 04:44:11 +0000452 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000453 }
454}
455}
456
Chris Lattner6cefb772008-01-05 22:25:12 +0000457//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000458// PatternToMatch implementation
459//
460
461/// getPredicateCheck - Return a single string containing all of this
462/// pattern's predicates concatenated with "&&" operators.
463///
464std::string PatternToMatch::getPredicateCheck() const {
465 std::string PredicateCheck;
466 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
467 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
468 Record *Def = Pred->getDef();
469 if (!Def->isSubClassOf("Predicate")) {
470#ifndef NDEBUG
471 Def->dump();
472#endif
473 assert(0 && "Unknown predicate type!");
474 }
475 if (!PredicateCheck.empty())
476 PredicateCheck += " && ";
477 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
478 }
479 }
480
481 return PredicateCheck;
482}
483
484//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000485// SDTypeConstraint implementation
486//
487
488SDTypeConstraint::SDTypeConstraint(Record *R) {
489 OperandNo = R->getValueAsInt("OperandNum");
490
491 if (R->isSubClassOf("SDTCisVT")) {
492 ConstraintType = SDTCisVT;
493 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
494 } else if (R->isSubClassOf("SDTCisPtrTy")) {
495 ConstraintType = SDTCisPtrTy;
496 } else if (R->isSubClassOf("SDTCisInt")) {
497 ConstraintType = SDTCisInt;
498 } else if (R->isSubClassOf("SDTCisFP")) {
499 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000500 } else if (R->isSubClassOf("SDTCisVec")) {
501 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000502 } else if (R->isSubClassOf("SDTCisSameAs")) {
503 ConstraintType = SDTCisSameAs;
504 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
505 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
506 ConstraintType = SDTCisVTSmallerThanOp;
507 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
508 R->getValueAsInt("OtherOperandNum");
509 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
510 ConstraintType = SDTCisOpSmallerThanOp;
511 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
512 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000513 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
514 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000515 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000516 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000517 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000518 exit(1);
519 }
520}
521
522/// getOperandNum - Return the node corresponding to operand #OpNo in tree
523/// N, which has NumResults results.
524TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
525 TreePatternNode *N,
526 unsigned NumResults) const {
527 assert(NumResults <= 1 &&
528 "We only work with nodes with zero or one result so far!");
529
530 if (OpNo >= (NumResults + N->getNumChildren())) {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000531 errs() << "Invalid operand number " << OpNo << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000532 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000533 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000534 exit(1);
535 }
536
537 if (OpNo < NumResults)
538 return N; // FIXME: need value #
539 else
540 return N->getChild(OpNo-NumResults);
541}
542
543/// ApplyTypeConstraint - Given a node in a pattern, apply this type
544/// constraint to the nodes operands. This returns true if it makes a
545/// change, false otherwise. If a type contradiction is found, throw an
546/// exception.
547bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
548 const SDNodeInfo &NodeInfo,
549 TreePattern &TP) const {
550 unsigned NumResults = NodeInfo.getNumResults();
551 assert(NumResults <= 1 &&
552 "We only work with nodes with zero or one result so far!");
553
554 // Check that the number of operands is sane. Negative operands -> varargs.
555 if (NodeInfo.getNumOperands() >= 0) {
556 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
557 TP.error(N->getOperator()->getName() + " node requires exactly " +
558 itostr(NodeInfo.getNumOperands()) + " operands!");
559 }
560
Chris Lattner6cefb772008-01-05 22:25:12 +0000561 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
562
563 switch (ConstraintType) {
564 default: assert(0 && "Unknown constraint type!");
565 case SDTCisVT:
566 // Operand must be a particular type.
567 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000568 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000569 // Operand must be same as target pointer type.
Owen Anderson825b72b2009-08-11 20:47:22 +0000570 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000571 case SDTCisInt:
572 // Require it to be one of the legal integer VTs.
573 return NodeToApply->getExtType().EnforceInteger(TP);
574 case SDTCisFP:
575 // Require it to be one of the legal fp VTs.
576 return NodeToApply->getExtType().EnforceFloatingPoint(TP);
577 case SDTCisVec:
578 // Require it to be one of the legal vector VTs.
579 return NodeToApply->getExtType().EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000580 case SDTCisSameAs: {
581 TreePatternNode *OtherNode =
582 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Chris Lattner2cacec52010-03-15 06:00:16 +0000583 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
584 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000585 }
586 case SDTCisVTSmallerThanOp: {
587 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
588 // have an integer type that is smaller than the VT.
589 if (!NodeToApply->isLeaf() ||
590 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
591 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
592 ->isSubClassOf("ValueType"))
593 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000594 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000595 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Duncan Sands83ec4b62008-06-06 12:08:01 +0000596 if (!isInteger(VT))
Chris Lattner6cefb772008-01-05 22:25:12 +0000597 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
598
599 TreePatternNode *OtherNode =
600 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
601
602 // It must be integer.
Chris Lattner2cacec52010-03-15 06:00:16 +0000603 bool MadeChange = OtherNode->getExtType().EnforceInteger(TP);
604
605 // This doesn't try to enforce any information on the OtherNode, it just
606 // validates it when information is determined.
607 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
Owen Anderson825b72b2009-08-11 20:47:22 +0000608 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
Bill Wendling7529ece2009-12-25 13:35:40 +0000609 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +0000610 }
611 case SDTCisOpSmallerThanOp: {
612 TreePatternNode *BigOperand =
613 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
Chris Lattner2cacec52010-03-15 06:00:16 +0000614 return NodeToApply->getExtType().
615 EnforceSmallerThan(BigOperand->getExtType(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000616 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000617 case SDTCisEltOfVec: {
Chris Lattner2cacec52010-03-15 06:00:16 +0000618 TreePatternNode *VecOperand =
619 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NumResults);
620 if (VecOperand->hasTypeSet()) {
621 if (!isVector(VecOperand->getType()))
Nate Begemanb5af3342008-02-09 01:37:05 +0000622 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Chris Lattner2cacec52010-03-15 06:00:16 +0000623 EVT IVT = VecOperand->getType();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000624 IVT = IVT.getVectorElementType();
Owen Anderson825b72b2009-08-11 20:47:22 +0000625 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000626 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000627
628 if (NodeToApply->hasTypeSet() && VecOperand->getExtType().hasVectorTypes()){
629 // Filter vector types out of VecOperand that don't have the right element
630 // type.
631 return VecOperand->getExtType().
632 EnforceVectorEltTypeIs(NodeToApply->getType(), TP);
633 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000634 return false;
635 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000636 }
637 return false;
638}
639
640//===----------------------------------------------------------------------===//
641// SDNodeInfo implementation
642//
643SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
644 EnumName = R->getValueAsString("Opcode");
645 SDClassName = R->getValueAsString("SDClass");
646 Record *TypeProfile = R->getValueAsDef("TypeProfile");
647 NumResults = TypeProfile->getValueAsInt("NumResults");
648 NumOperands = TypeProfile->getValueAsInt("NumOperands");
649
650 // Parse the properties.
651 Properties = 0;
652 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
653 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
654 if (PropList[i]->getName() == "SDNPCommutative") {
655 Properties |= 1 << SDNPCommutative;
656 } else if (PropList[i]->getName() == "SDNPAssociative") {
657 Properties |= 1 << SDNPAssociative;
658 } else if (PropList[i]->getName() == "SDNPHasChain") {
659 Properties |= 1 << SDNPHasChain;
660 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000661 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000662 } else if (PropList[i]->getName() == "SDNPInFlag") {
663 Properties |= 1 << SDNPInFlag;
664 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
665 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000666 } else if (PropList[i]->getName() == "SDNPMayStore") {
667 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000668 } else if (PropList[i]->getName() == "SDNPMayLoad") {
669 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000670 } else if (PropList[i]->getName() == "SDNPSideEffect") {
671 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000672 } else if (PropList[i]->getName() == "SDNPMemOperand") {
673 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +0000674 } else if (PropList[i]->getName() == "SDNPVariadic") {
675 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +0000676 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000677 errs() << "Unknown SD Node property '" << PropList[i]->getName()
678 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000679 exit(1);
680 }
681 }
682
683
684 // Parse the type constraints.
685 std::vector<Record*> ConstraintList =
686 TypeProfile->getValueAsListOfDefs("Constraints");
687 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
688}
689
Chris Lattner22579812010-02-28 00:22:30 +0000690/// getKnownType - If the type constraints on this node imply a fixed type
691/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000692/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
693MVT::SimpleValueType SDNodeInfo::getKnownType() const {
Chris Lattner22579812010-02-28 00:22:30 +0000694 unsigned NumResults = getNumResults();
695 assert(NumResults <= 1 &&
696 "We only work with nodes with zero or one result so far!");
697
698 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
699 // Make sure that this applies to the correct node result.
700 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
701 continue;
702
703 switch (TypeConstraints[i].ConstraintType) {
704 default: break;
705 case SDTypeConstraint::SDTCisVT:
706 return TypeConstraints[i].x.SDTCisVT_Info.VT;
707 case SDTypeConstraint::SDTCisPtrTy:
708 return MVT::iPTR;
709 }
710 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000711 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +0000712}
713
Chris Lattner6cefb772008-01-05 22:25:12 +0000714//===----------------------------------------------------------------------===//
715// TreePatternNode implementation
716//
717
718TreePatternNode::~TreePatternNode() {
719#if 0 // FIXME: implement refcounted tree nodes!
720 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
721 delete getChild(i);
722#endif
723}
724
Chris Lattnerba1cff42010-02-23 07:50:58 +0000725
Chris Lattner6cefb772008-01-05 22:25:12 +0000726
Daniel Dunbar1a551802009-07-03 00:10:29 +0000727void TreePatternNode::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000728 if (isLeaf()) {
729 OS << *getLeafValue();
730 } else {
Chris Lattnerba1cff42010-02-23 07:50:58 +0000731 OS << '(' << getOperator()->getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000732 }
733
Chris Lattner2cacec52010-03-15 06:00:16 +0000734 if (!isTypeCompletelyUnknown())
735 OS << ':' << getExtType().getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000736
737 if (!isLeaf()) {
738 if (getNumChildren() != 0) {
739 OS << " ";
740 getChild(0)->print(OS);
741 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
742 OS << ", ";
743 getChild(i)->print(OS);
744 }
745 }
746 OS << ")";
747 }
748
Dan Gohman0540e172008-10-15 06:17:21 +0000749 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
750 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000751 if (TransformFn)
752 OS << "<<X:" << TransformFn->getName() << ">>";
753 if (!getName().empty())
754 OS << ":$" << getName();
755
756}
757void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000758 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000759}
760
Scott Michel327d0652008-03-05 17:49:05 +0000761/// isIsomorphicTo - Return true if this node is recursively
762/// isomorphic to the specified node. For this comparison, the node's
763/// entire state is considered. The assigned name is ignored, since
764/// nodes with differing names are considered isomorphic. However, if
765/// the assigned name is present in the dependent variable set, then
766/// the assigned name is considered significant and the node is
767/// isomorphic if the names match.
768bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
769 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000770 if (N == this) return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000771 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000772 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000773 getTransformFn() != N->getTransformFn())
774 return false;
775
776 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000777 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
778 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000779 return ((DI->getDef() == NDI->getDef())
780 && (DepVars.find(getName()) == DepVars.end()
781 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000782 }
783 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000784 return getLeafValue() == N->getLeafValue();
785 }
786
787 if (N->getOperator() != getOperator() ||
788 N->getNumChildren() != getNumChildren()) return false;
789 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000790 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000791 return false;
792 return true;
793}
794
795/// clone - Make a copy of this tree and all of its children.
796///
797TreePatternNode *TreePatternNode::clone() const {
798 TreePatternNode *New;
799 if (isLeaf()) {
800 New = new TreePatternNode(getLeafValue());
801 } else {
802 std::vector<TreePatternNode*> CChildren;
803 CChildren.reserve(Children.size());
804 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
805 CChildren.push_back(getChild(i)->clone());
806 New = new TreePatternNode(getOperator(), CChildren);
807 }
808 New->setName(getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000809 New->setType(getExtType());
Dan Gohman0540e172008-10-15 06:17:21 +0000810 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000811 New->setTransformFn(getTransformFn());
812 return New;
813}
814
Chris Lattner47661322010-02-14 22:22:58 +0000815/// RemoveAllTypes - Recursively strip all the types of this tree.
816void TreePatternNode::RemoveAllTypes() {
Chris Lattner2cacec52010-03-15 06:00:16 +0000817 setType(EEVT::TypeSet()); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +0000818 if (isLeaf()) return;
819 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
820 getChild(i)->RemoveAllTypes();
821}
822
823
Chris Lattner6cefb772008-01-05 22:25:12 +0000824/// SubstituteFormalArguments - Replace the formal arguments in this tree
825/// with actual values specified by ArgMap.
826void TreePatternNode::
827SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
828 if (isLeaf()) return;
829
830 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
831 TreePatternNode *Child = getChild(i);
832 if (Child->isLeaf()) {
833 Init *Val = Child->getLeafValue();
834 if (dynamic_cast<DefInit*>(Val) &&
835 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
836 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000837 TreePatternNode *NewChild = ArgMap[Child->getName()];
838 assert(NewChild && "Couldn't find formal argument!");
839 assert((Child->getPredicateFns().empty() ||
840 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
841 "Non-empty child predicate clobbered!");
842 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000843 }
844 } else {
845 getChild(i)->SubstituteFormalArguments(ArgMap);
846 }
847 }
848}
849
850
851/// InlinePatternFragments - If this pattern refers to any pattern
852/// fragments, inline them into place, giving us a pattern without any
853/// PatFrag references.
854TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
855 if (isLeaf()) return this; // nothing to do.
856 Record *Op = getOperator();
857
858 if (!Op->isSubClassOf("PatFrag")) {
859 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000860 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
861 TreePatternNode *Child = getChild(i);
862 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
863
864 assert((Child->getPredicateFns().empty() ||
865 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
866 "Non-empty child predicate clobbered!");
867
868 setChild(i, NewChild);
869 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000870 return this;
871 }
872
873 // Otherwise, we found a reference to a fragment. First, look up its
874 // TreePattern record.
875 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
876
877 // Verify that we are passing the right number of operands.
878 if (Frag->getNumArgs() != Children.size())
879 TP.error("'" + Op->getName() + "' fragment requires " +
880 utostr(Frag->getNumArgs()) + " operands!");
881
882 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
883
Dan Gohman0540e172008-10-15 06:17:21 +0000884 std::string Code = Op->getValueAsCode("Predicate");
885 if (!Code.empty())
886 FragTree->addPredicateFn("Predicate_"+Op->getName());
887
Chris Lattner6cefb772008-01-05 22:25:12 +0000888 // Resolve formal arguments to their actual value.
889 if (Frag->getNumArgs()) {
890 // Compute the map of formal to actual arguments.
891 std::map<std::string, TreePatternNode*> ArgMap;
892 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
893 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
894
895 FragTree->SubstituteFormalArguments(ArgMap);
896 }
897
898 FragTree->setName(getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000899 FragTree->UpdateNodeType(getExtType(), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000900
901 // Transfer in the old predicates.
902 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
903 FragTree->addPredicateFn(getPredicateFns()[i]);
904
Chris Lattner6cefb772008-01-05 22:25:12 +0000905 // Get a new copy of this fragment to stitch into here.
906 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000907
908 // The fragment we inlined could have recursive inlining that is needed. See
909 // if there are any pattern fragments in it and inline them as needed.
910 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000911}
912
913/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000914/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +0000915/// references from the register file information, for example.
916///
Chris Lattner2cacec52010-03-15 06:00:16 +0000917static EEVT::TypeSet getImplicitType(Record *R, bool NotRegisters,
918 TreePattern &TP) {
919 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +0000920 if (R->isSubClassOf("RegisterClass")) {
921 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000922 return EEVT::TypeSet(); // Unknown.
923 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
924 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +0000925 } else if (R->isSubClassOf("PatFrag")) {
926 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +0000927 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000928 } else if (R->isSubClassOf("Register")) {
929 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000930 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000931 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +0000932 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6cefb772008-01-05 22:25:12 +0000933 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
934 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +0000935 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000936 } else if (R->isSubClassOf("ComplexPattern")) {
937 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +0000938 return EEVT::TypeSet(); // Unknown.
939 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
940 TP);
Chris Lattnera938ac62009-07-29 20:43:05 +0000941 } else if (R->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000942 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000943 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
944 R->getName() == "zero_reg") {
945 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +0000946 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +0000947 }
948
949 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +0000950 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000951}
952
Chris Lattnere67bde52008-01-06 05:36:50 +0000953
954/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
955/// CodeGenIntrinsic information for it, otherwise return a null pointer.
956const CodeGenIntrinsic *TreePatternNode::
957getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
958 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
959 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
960 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
961 return 0;
962
963 unsigned IID =
964 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
965 return &CDP.getIntrinsicInfo(IID);
966}
967
Chris Lattner47661322010-02-14 22:22:58 +0000968/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
969/// return the ComplexPattern information, otherwise return null.
970const ComplexPattern *
971TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
972 if (!isLeaf()) return 0;
973
974 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
975 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
976 return &CGP.getComplexPattern(DI->getDef());
977 return 0;
978}
979
980/// NodeHasProperty - Return true if this node has the specified property.
981bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +0000982 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +0000983 if (isLeaf()) {
984 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
985 return CP->hasProperty(Property);
986 return false;
987 }
988
989 Record *Operator = getOperator();
990 if (!Operator->isSubClassOf("SDNode")) return false;
991
992 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
993}
994
995
996
997
998/// TreeHasProperty - Return true if any node in this tree has the specified
999/// property.
1000bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001001 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001002 if (NodeHasProperty(Property, CGP))
1003 return true;
1004 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1005 if (getChild(i)->TreeHasProperty(Property, CGP))
1006 return true;
1007 return false;
1008}
1009
Evan Cheng6bd95672008-06-16 20:29:38 +00001010/// isCommutativeIntrinsic - Return true if the node corresponds to a
1011/// commutative intrinsic.
1012bool
1013TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1014 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1015 return Int->isCommutative;
1016 return false;
1017}
1018
Chris Lattnere67bde52008-01-06 05:36:50 +00001019
Bob Wilson6c01ca92009-01-05 17:23:09 +00001020/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001021/// this node and its children in the tree. This returns true if it makes a
1022/// change, false otherwise. If a type contradiction is found, throw an
1023/// exception.
1024bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +00001025 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001026 if (isLeaf()) {
1027 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1028 // If it's a regclass or something else known, include the type.
1029 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner523f6a52010-02-14 21:10:15 +00001030 }
1031
1032 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001033 // Int inits are always integers. :)
Chris Lattner2cacec52010-03-15 06:00:16 +00001034 bool MadeChange = Type.EnforceInteger(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001035
Chris Lattner2cacec52010-03-15 06:00:16 +00001036 if (!hasTypeSet())
1037 return MadeChange;
1038
1039 MVT::SimpleValueType VT = getType();
1040 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1041 return MadeChange;
1042
1043 unsigned Size = EVT(VT).getSizeInBits();
1044 // Make sure that the value is representable for this type.
1045 if (Size >= 32) return MadeChange;
1046
1047 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1048 if (Val == II->getValue()) return MadeChange;
1049
1050 // If sign-extended doesn't fit, does it fit as unsigned?
1051 unsigned ValueMask;
1052 unsigned UnsignedVal;
1053 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1054 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +00001055
Chris Lattner2cacec52010-03-15 06:00:16 +00001056 if ((ValueMask & UnsignedVal) == UnsignedVal)
1057 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001058
Chris Lattner2cacec52010-03-15 06:00:16 +00001059 TP.error("Integer value '" + itostr(II->getValue())+
1060 "' is out of range for type '" + getEnumName(getType()) + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001061 return MadeChange;
1062 }
1063 return false;
1064 }
1065
1066 // special handling for set, which isn't really an SDNode.
1067 if (getOperator()->getName() == "set") {
1068 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
1069 unsigned NC = getNumChildren();
1070 bool MadeChange = false;
1071 for (unsigned i = 0; i < NC-1; ++i) {
1072 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1073 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
1074
1075 // Types of operands must match.
Chris Lattner2cacec52010-03-15 06:00:16 +00001076 MadeChange |=getChild(i)->UpdateNodeType(getChild(NC-1)->getExtType(),TP);
1077 MadeChange |=getChild(NC-1)->UpdateNodeType(getChild(i)->getExtType(),TP);
1078 MadeChange |=UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001079 }
1080 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001081 }
1082
1083 if (getOperator()->getName() == "implicit" ||
1084 getOperator()->getName() == "parallel") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001085 bool MadeChange = false;
1086 for (unsigned i = 0; i < getNumChildren(); ++i)
1087 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Owen Anderson825b72b2009-08-11 20:47:22 +00001088 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001089 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001090 }
1091
1092 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +00001093 bool MadeChange = false;
1094 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1095 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner2cacec52010-03-15 06:00:16 +00001096
1097 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1098 // what type it gets, so if it didn't get a concrete type just give it the
1099 // first viable type from the reg class.
1100 if (!getChild(1)->hasTypeSet() &&
1101 !getChild(1)->getExtType().isCompletelyUnknown()) {
1102 MVT::SimpleValueType RCVT = getChild(1)->getExtType().getTypeList()[0];
1103 MadeChange |= getChild(1)->UpdateNodeType(RCVT, TP);
1104 }
Dan Gohmanf8c73942009-04-13 15:38:05 +00001105 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001106 }
1107
1108 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001109 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001110
Chris Lattner6cefb772008-01-05 22:25:12 +00001111 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001112 unsigned NumRetVTs = Int->IS.RetVTs.size();
1113 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001114
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001115 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1116 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1117
1118 if (getNumChildren() != NumParamVTs + NumRetVTs)
Chris Lattnere67bde52008-01-06 05:36:50 +00001119 TP.error("Intrinsic '" + Int->Name + "' expects " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001120 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1121 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001122
1123 // Apply type info to the intrinsic ID.
Owen Anderson825b72b2009-08-11 20:47:22 +00001124 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001125
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001126 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001127 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
Chris Lattner6cefb772008-01-05 22:25:12 +00001128 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1129 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1130 }
1131 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001132 }
1133
1134 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001135 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1136
1137 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1138 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1139 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1140 // Branch, etc. do not produce results and top-level forms in instr pattern
1141 // must have void types.
1142 if (NI.getNumResults() == 0)
Owen Anderson825b72b2009-08-11 20:47:22 +00001143 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001144
Chris Lattner6cefb772008-01-05 22:25:12 +00001145 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001146 }
1147
1148 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001149 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Daniel Dunbar65f35d52010-03-19 03:18:20 +00001150 assert(Inst.getNumResults() <= 1 &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001151 "Only supports zero or one result instrs!");
1152
1153 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001154 CDP.getTargetInfo().getInstruction(getOperator());
Chris Lattner6c6ba362010-03-18 23:15:10 +00001155
1156 EEVT::TypeSet ResultType;
1157
Chris Lattner6cefb772008-01-05 22:25:12 +00001158 // Apply the result type to the node
Chris Lattner6c6ba362010-03-18 23:15:10 +00001159 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
Chris Lattner6cefb772008-01-05 22:25:12 +00001160 Record *ResultNode = Inst.getResult(0);
1161
Chris Lattnera938ac62009-07-29 20:43:05 +00001162 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00001163 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001164 } else if (ResultNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001165 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001166 } else {
1167 assert(ResultNode->isSubClassOf("RegisterClass") &&
1168 "Operands should be register classes!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001169 const CodeGenRegisterClass &RC =
1170 CDP.getTargetInfo().getRegisterClass(ResultNode);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001171 ResultType = RC.getValueTypes();
Chris Lattner6cefb772008-01-05 22:25:12 +00001172 }
Chris Lattner6c6ba362010-03-18 23:15:10 +00001173 } else if (!InstInfo.ImplicitDefs.empty()) {
1174 // If the instruction has implicit defs, the first one defines the result
1175 // type.
Chris Lattner6c6ba362010-03-18 23:15:10 +00001176 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
Chris Lattner92879532010-03-18 23:57:40 +00001177 assert(FirstImplicitDef->isSubClassOf("Register"));
Chris Lattner6c6ba362010-03-18 23:15:10 +00001178 const std::vector<MVT::SimpleValueType> &RegVTs =
1179 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
Chris Lattner92879532010-03-18 23:57:40 +00001180 if (RegVTs.size() == 1)
Chris Lattner6c6ba362010-03-18 23:15:10 +00001181 ResultType = EEVT::TypeSet(RegVTs);
Chris Lattner92879532010-03-18 23:57:40 +00001182 else
1183 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
Chris Lattner6c6ba362010-03-18 23:15:10 +00001184 } else {
1185 // Otherwise, the instruction produces no value result.
1186 // FIXME: Model "no result" different than "one result that is void"
1187 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001188 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001189
Chris Lattner6c6ba362010-03-18 23:15:10 +00001190 bool MadeChange = UpdateNodeType(ResultType, TP);
1191
Chris Lattner2cacec52010-03-15 06:00:16 +00001192 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1193 // be the same.
1194 if (getOperator()->getName() == "INSERT_SUBREG") {
1195 MadeChange |= UpdateNodeType(getChild(0)->getExtType(), TP);
1196 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1197 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001198
1199 unsigned ChildNo = 0;
1200 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1201 Record *OperandNode = Inst.getOperand(i);
1202
1203 // If the instruction expects a predicate or optional def operand, we
1204 // codegen this by setting the operand to it's default value if it has a
1205 // non-empty DefaultOps field.
1206 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1207 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1208 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1209 continue;
1210
1211 // Verify that we didn't run out of provided operands.
1212 if (ChildNo >= getNumChildren())
1213 TP.error("Instruction '" + getOperator()->getName() +
1214 "' expects more operands than were provided.");
1215
Owen Anderson825b72b2009-08-11 20:47:22 +00001216 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001217 TreePatternNode *Child = getChild(ChildNo++);
1218 if (OperandNode->isSubClassOf("RegisterClass")) {
1219 const CodeGenRegisterClass &RC =
1220 CDP.getTargetInfo().getRegisterClass(OperandNode);
Chris Lattner2cacec52010-03-15 06:00:16 +00001221 MadeChange |= Child->UpdateNodeType(RC.getValueTypes(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001222 } else if (OperandNode->isSubClassOf("Operand")) {
1223 VT = getValueType(OperandNode->getValueAsDef("Type"));
1224 MadeChange |= Child->UpdateNodeType(VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001225 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001226 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001227 } else if (OperandNode->getName() == "unknown") {
Chris Lattner2cacec52010-03-15 06:00:16 +00001228 // Nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001229 } else {
1230 assert(0 && "Unknown operand type!");
1231 abort();
1232 }
1233 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1234 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001235
Christopher Lamb02f69372008-03-10 04:16:09 +00001236 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001237 TP.error("Instruction '" + getOperator()->getName() +
1238 "' was provided too many operands!");
1239
1240 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001241 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001242
1243 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1244
1245 // Node transforms always take one operand.
1246 if (getNumChildren() != 1)
1247 TP.error("Node transform '" + getOperator()->getName() +
1248 "' requires one operand!");
1249
Chris Lattner2cacec52010-03-15 06:00:16 +00001250 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1251
1252
Chris Lattner6eb30122010-02-23 05:51:07 +00001253 // If either the output or input of the xform does not have exact
1254 // type info. We assume they must be the same. Otherwise, it is perfectly
1255 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001256#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001257 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001258 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1259 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001260 return MadeChange;
1261 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001262#endif
1263 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001264}
1265
1266/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1267/// RHS of a commutative operation, not the on LHS.
1268static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1269 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1270 return true;
1271 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1272 return true;
1273 return false;
1274}
1275
1276
1277/// canPatternMatch - If it is impossible for this pattern to match on this
1278/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001279/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001280/// that can never possibly work), and to prevent the pattern permuter from
1281/// generating stuff that is useless.
1282bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001283 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001284 if (isLeaf()) return true;
1285
1286 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1287 if (!getChild(i)->canPatternMatch(Reason, CDP))
1288 return false;
1289
1290 // If this is an intrinsic, handle cases that would make it not match. For
1291 // example, if an operand is required to be an immediate.
1292 if (getOperator()->isSubClassOf("Intrinsic")) {
1293 // TODO:
1294 return true;
1295 }
1296
1297 // If this node is a commutative operator, check that the LHS isn't an
1298 // immediate.
1299 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001300 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1301 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001302 // Scan all of the operands of the node and make sure that only the last one
1303 // is a constant node, unless the RHS also is.
1304 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001305 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1306 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001307 if (OnlyOnRHSOfCommutative(getChild(i))) {
1308 Reason="Immediate value must be on the RHS of commutative operators!";
1309 return false;
1310 }
1311 }
1312 }
1313
1314 return true;
1315}
1316
1317//===----------------------------------------------------------------------===//
1318// TreePattern implementation
1319//
1320
1321TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001322 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner2cacec52010-03-15 06:00:16 +00001323 isInputPattern = isInput;
1324 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1325 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001326}
1327
1328TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001329 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001330 isInputPattern = isInput;
1331 Trees.push_back(ParseTreePattern(Pat));
1332}
1333
1334TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001335 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001336 isInputPattern = isInput;
1337 Trees.push_back(Pat);
1338}
1339
Chris Lattner6cefb772008-01-05 22:25:12 +00001340void TreePattern::error(const std::string &Msg) const {
1341 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001342 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001343}
1344
Chris Lattner2cacec52010-03-15 06:00:16 +00001345void TreePattern::ComputeNamedNodes() {
1346 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1347 ComputeNamedNodes(Trees[i]);
1348}
1349
1350void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1351 if (!N->getName().empty())
1352 NamedNodes[N->getName()].push_back(N);
1353
1354 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1355 ComputeNamedNodes(N->getChild(i));
1356}
1357
Chris Lattner6cefb772008-01-05 22:25:12 +00001358TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1359 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1360 if (!OpDef) error("Pattern has unexpected operator type!");
1361 Record *Operator = OpDef->getDef();
1362
1363 if (Operator->isSubClassOf("ValueType")) {
1364 // If the operator is a ValueType, then this must be "type cast" of a leaf
1365 // node.
1366 if (Dag->getNumArgs() != 1)
1367 error("Type cast only takes one operand!");
1368
1369 Init *Arg = Dag->getArg(0);
1370 TreePatternNode *New;
1371 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1372 Record *R = DI->getDef();
1373 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001374 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001375 std::vector<std::pair<Init*, std::string> >()));
1376 return ParseTreePattern(Dag);
1377 }
Chris Lattner43e47542010-03-08 18:36:19 +00001378
1379 // Input argument?
1380 if (R->getName() == "node") {
1381 if (Dag->getArgName(0).empty())
1382 error("'node' argument requires a name to match with operand list");
1383 Args.push_back(Dag->getArgName(0));
1384 }
1385
Chris Lattner6cefb772008-01-05 22:25:12 +00001386 New = new TreePatternNode(DI);
1387 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1388 New = ParseTreePattern(DI);
1389 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1390 New = new TreePatternNode(II);
1391 if (!Dag->getArgName(0).empty())
1392 error("Constant int argument should not have a name!");
1393 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1394 // Turn this into an IntInit.
1395 Init *II = BI->convertInitializerTo(new IntRecTy());
1396 if (II == 0 || !dynamic_cast<IntInit*>(II))
1397 error("Bits value must be constants!");
1398
1399 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1400 if (!Dag->getArgName(0).empty())
1401 error("Constant int argument should not have a name!");
1402 } else {
1403 Arg->dump();
1404 error("Unknown leaf value for tree pattern!");
1405 return 0;
1406 }
1407
1408 // Apply the type cast.
1409 New->UpdateNodeType(getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001410 if (New->getNumChildren() == 0)
1411 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001412 return New;
1413 }
1414
1415 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001416 if (!Operator->isSubClassOf("PatFrag") &&
1417 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001418 !Operator->isSubClassOf("Instruction") &&
1419 !Operator->isSubClassOf("SDNodeXForm") &&
1420 !Operator->isSubClassOf("Intrinsic") &&
1421 Operator->getName() != "set" &&
1422 Operator->getName() != "implicit" &&
1423 Operator->getName() != "parallel")
1424 error("Unrecognized node '" + Operator->getName() + "'!");
1425
1426 // Check to see if this is something that is illegal in an input pattern.
1427 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1428 Operator->isSubClassOf("SDNodeXForm")))
1429 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1430
1431 std::vector<TreePatternNode*> Children;
1432
1433 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1434 Init *Arg = Dag->getArg(i);
1435 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1436 Children.push_back(ParseTreePattern(DI));
1437 if (Children.back()->getName().empty())
1438 Children.back()->setName(Dag->getArgName(i));
1439 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1440 Record *R = DefI->getDef();
1441 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1442 // TreePatternNode if its own.
1443 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001444 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001445 std::vector<std::pair<Init*, std::string> >()));
1446 --i; // Revisit this node...
1447 } else {
1448 TreePatternNode *Node = new TreePatternNode(DefI);
1449 Node->setName(Dag->getArgName(i));
1450 Children.push_back(Node);
1451
1452 // Input argument?
1453 if (R->getName() == "node") {
1454 if (Dag->getArgName(i).empty())
1455 error("'node' argument requires a name to match with operand list");
1456 Args.push_back(Dag->getArgName(i));
1457 }
1458 }
1459 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1460 TreePatternNode *Node = new TreePatternNode(II);
1461 if (!Dag->getArgName(i).empty())
1462 error("Constant int argument should not have a name!");
1463 Children.push_back(Node);
1464 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1465 // Turn this into an IntInit.
1466 Init *II = BI->convertInitializerTo(new IntRecTy());
1467 if (II == 0 || !dynamic_cast<IntInit*>(II))
1468 error("Bits value must be constants!");
1469
1470 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1471 if (!Dag->getArgName(i).empty())
1472 error("Constant int argument should not have a name!");
1473 Children.push_back(Node);
1474 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001475 errs() << '"';
Chris Lattner6cefb772008-01-05 22:25:12 +00001476 Arg->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001477 errs() << "\": ";
Chris Lattner6cefb772008-01-05 22:25:12 +00001478 error("Unknown leaf value for tree pattern!");
1479 }
1480 }
1481
1482 // If the operator is an intrinsic, then this is just syntactic sugar for for
1483 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1484 // convert the intrinsic name to a number.
1485 if (Operator->isSubClassOf("Intrinsic")) {
1486 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1487 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1488
1489 // If this intrinsic returns void, it must have side-effects and thus a
1490 // chain.
Owen Anderson825b72b2009-08-11 20:47:22 +00001491 if (Int.IS.RetVTs[0] == MVT::isVoid) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001492 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1493 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1494 // Has side-effects, requires chain.
1495 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1496 } else {
1497 // Otherwise, no chain.
1498 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1499 }
1500
1501 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1502 Children.insert(Children.begin(), IIDNode);
1503 }
1504
Nate Begeman7cee8172009-03-19 05:21:56 +00001505 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1506 Result->setName(Dag->getName());
1507 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001508}
1509
1510/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001511/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001512/// otherwise. Throw an exception if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001513bool TreePattern::
1514InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1515 if (NamedNodes.empty())
1516 ComputeNamedNodes();
1517
Chris Lattner6cefb772008-01-05 22:25:12 +00001518 bool MadeChange = true;
1519 while (MadeChange) {
1520 MadeChange = false;
1521 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1522 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner2cacec52010-03-15 06:00:16 +00001523
1524 // If there are constraints on our named nodes, apply them.
1525 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1526 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1527 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1528
1529 // If we have input named node types, propagate their types to the named
1530 // values here.
1531 if (InNamedTypes) {
1532 // FIXME: Should be error?
1533 assert(InNamedTypes->count(I->getKey()) &&
1534 "Named node in output pattern but not input pattern?");
1535
1536 const SmallVectorImpl<TreePatternNode*> &InNodes =
1537 InNamedTypes->find(I->getKey())->second;
1538
1539 // The input types should be fully resolved by now.
1540 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1541 // If this node is a register class, and it is the root of the pattern
1542 // then we're mapping something onto an input register. We allow
1543 // changing the type of the input register in this case. This allows
1544 // us to match things like:
1545 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1546 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1547 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1548 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1549 continue;
1550 }
1551
1552 MadeChange |=Nodes[i]->UpdateNodeType(InNodes[0]->getExtType(),*this);
1553 }
1554 }
1555
1556 // If there are multiple nodes with the same name, they must all have the
1557 // same type.
1558 if (I->second.size() > 1) {
1559 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1560 MadeChange |=Nodes[i]->UpdateNodeType(Nodes[i+1]->getExtType(),*this);
1561 MadeChange |=Nodes[i+1]->UpdateNodeType(Nodes[i]->getExtType(),*this);
1562 }
1563 }
1564 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001565 }
1566
1567 bool HasUnresolvedTypes = false;
1568 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1569 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1570 return !HasUnresolvedTypes;
1571}
1572
Daniel Dunbar1a551802009-07-03 00:10:29 +00001573void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001574 OS << getRecord()->getName();
1575 if (!Args.empty()) {
1576 OS << "(" << Args[0];
1577 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1578 OS << ", " << Args[i];
1579 OS << ")";
1580 }
1581 OS << ": ";
1582
1583 if (Trees.size() > 1)
1584 OS << "[\n";
1585 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1586 OS << "\t";
1587 Trees[i]->print(OS);
1588 OS << "\n";
1589 }
1590
1591 if (Trees.size() > 1)
1592 OS << "]\n";
1593}
1594
Daniel Dunbar1a551802009-07-03 00:10:29 +00001595void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001596
1597//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001598// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001599//
1600
Chris Lattnerfe718932008-01-06 01:10:31 +00001601CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001602 Intrinsics = LoadIntrinsics(Records, false);
1603 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001604 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001605 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001606 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001607 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001608 ParseDefaultOperands();
1609 ParseInstructions();
1610 ParsePatterns();
1611
1612 // Generate variants. For example, commutative patterns can match
1613 // multiple ways. Add them to PatternsToMatch as well.
1614 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001615
1616 // Infer instruction flags. For example, we can detect loads,
1617 // stores, and side effects in many cases by examining an
1618 // instruction's pattern.
1619 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001620}
1621
Chris Lattnerfe718932008-01-06 01:10:31 +00001622CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001623 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001624 E = PatternFragments.end(); I != E; ++I)
1625 delete I->second;
1626}
1627
1628
Chris Lattnerfe718932008-01-06 01:10:31 +00001629Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001630 Record *N = Records.getDef(Name);
1631 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001632 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001633 exit(1);
1634 }
1635 return N;
1636}
1637
1638// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001639void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001640 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1641 while (!Nodes.empty()) {
1642 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1643 Nodes.pop_back();
1644 }
1645
Jim Grosbachda4231f2009-03-26 16:17:51 +00001646 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001647 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1648 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1649 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1650}
1651
1652/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1653/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001654void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001655 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1656 while (!Xforms.empty()) {
1657 Record *XFormNode = Xforms.back();
1658 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1659 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001660 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001661
1662 Xforms.pop_back();
1663 }
1664}
1665
Chris Lattnerfe718932008-01-06 01:10:31 +00001666void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001667 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1668 while (!AMs.empty()) {
1669 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1670 AMs.pop_back();
1671 }
1672}
1673
1674
1675/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1676/// file, building up the PatternFragments map. After we've collected them all,
1677/// inline fragments together as necessary, so that there are no references left
1678/// inside a pattern fragment to a pattern fragment.
1679///
Chris Lattnerfe718932008-01-06 01:10:31 +00001680void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001681 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1682
Chris Lattnerdc32f982008-01-05 22:43:57 +00001683 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001684 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1685 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1686 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1687 PatternFragments[Fragments[i]] = P;
1688
Chris Lattnerdc32f982008-01-05 22:43:57 +00001689 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001690 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001691 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001692
Chris Lattnerdc32f982008-01-05 22:43:57 +00001693 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001694 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1695
1696 // Parse the operands list.
1697 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1698 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1699 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001700 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001701 if (!OpsOp ||
1702 (OpsOp->getDef()->getName() != "ops" &&
1703 OpsOp->getDef()->getName() != "outs" &&
1704 OpsOp->getDef()->getName() != "ins"))
1705 P->error("Operands list should start with '(ops ... '!");
1706
1707 // Copy over the arguments.
1708 Args.clear();
1709 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1710 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1711 static_cast<DefInit*>(OpsList->getArg(j))->
1712 getDef()->getName() != "node")
1713 P->error("Operands list should all be 'node' values.");
1714 if (OpsList->getArgName(j).empty())
1715 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001716 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001717 P->error("'" + OpsList->getArgName(j) +
1718 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001719 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001720 Args.push_back(OpsList->getArgName(j));
1721 }
1722
Chris Lattnerdc32f982008-01-05 22:43:57 +00001723 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001724 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001725 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001726
Chris Lattnerdc32f982008-01-05 22:43:57 +00001727 // If there is a code init for this fragment, keep track of the fact that
1728 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001729 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001730 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001731 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001732
1733 // If there is a node transformation corresponding to this, keep track of
1734 // it.
1735 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1736 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1737 P->getOnlyTree()->setTransformFn(Transform);
1738 }
1739
Chris Lattner6cefb772008-01-05 22:25:12 +00001740 // Now that we've parsed all of the tree fragments, do a closure on them so
1741 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001742 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1743 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001744 ThePat->InlinePatternFragments();
1745
1746 // Infer as many types as possible. Don't worry about it if we don't infer
1747 // all of them, some may depend on the inputs of the pattern.
1748 try {
1749 ThePat->InferAllTypes();
1750 } catch (...) {
1751 // If this pattern fragment is not supported by this target (no types can
1752 // satisfy its constraints), just ignore it. If the bogus pattern is
1753 // actually used by instructions, the type consistency error will be
1754 // reported there.
1755 }
1756
1757 // If debugging, print out the pattern fragment result.
1758 DEBUG(ThePat->dump());
1759 }
1760}
1761
Chris Lattnerfe718932008-01-06 01:10:31 +00001762void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001763 std::vector<Record*> DefaultOps[2];
1764 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1765 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1766
1767 // Find some SDNode.
1768 assert(!SDNodes.empty() && "No SDNodes parsed?");
1769 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1770
1771 for (unsigned iter = 0; iter != 2; ++iter) {
1772 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1773 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1774
1775 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1776 // SomeSDnode so that we can parse this.
1777 std::vector<std::pair<Init*, std::string> > Ops;
1778 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1779 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1780 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001781 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001782
1783 // Create a TreePattern to parse this.
1784 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1785 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1786
1787 // Copy the operands over into a DAGDefaultOperand.
1788 DAGDefaultOperand DefaultOpInfo;
1789
1790 TreePatternNode *T = P.getTree(0);
1791 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1792 TreePatternNode *TPN = T->getChild(op);
1793 while (TPN->ApplyTypeConstraints(P, false))
1794 /* Resolve all types */;
1795
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001796 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001797 if (iter == 0)
1798 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001799 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00001800 else
1801 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001802 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001803 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001804 DefaultOpInfo.DefaultOps.push_back(TPN);
1805 }
1806
1807 // Insert it into the DefaultOperands map so we can find it later.
1808 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1809 }
1810 }
1811}
1812
1813/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1814/// instruction input. Return true if this is a real use.
1815static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1816 std::map<std::string, TreePatternNode*> &InstInputs,
1817 std::vector<Record*> &InstImpInputs) {
1818 // No name -> not interesting.
1819 if (Pat->getName().empty()) {
1820 if (Pat->isLeaf()) {
1821 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1822 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1823 I->error("Input " + DI->getDef()->getName() + " must be named!");
1824 else if (DI && DI->getDef()->isSubClassOf("Register"))
1825 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001826 }
1827 return false;
1828 }
1829
1830 Record *Rec;
1831 if (Pat->isLeaf()) {
1832 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1833 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1834 Rec = DI->getDef();
1835 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001836 Rec = Pat->getOperator();
1837 }
1838
1839 // SRCVALUE nodes are ignored.
1840 if (Rec->getName() == "srcvalue")
1841 return false;
1842
1843 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1844 if (!Slot) {
1845 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00001846 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00001847 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00001848 Record *SlotRec;
1849 if (Slot->isLeaf()) {
1850 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1851 } else {
1852 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1853 SlotRec = Slot->getOperator();
1854 }
1855
1856 // Ensure that the inputs agree if we've already seen this input.
1857 if (Rec != SlotRec)
1858 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner2cacec52010-03-15 06:00:16 +00001859 if (Slot->getExtType() != Pat->getExtType())
Chris Lattner53d09bd2010-02-23 05:59:10 +00001860 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00001861 return true;
1862}
1863
1864/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1865/// part of "I", the instruction), computing the set of inputs and outputs of
1866/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001867void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001868FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1869 std::map<std::string, TreePatternNode*> &InstInputs,
1870 std::map<std::string, TreePatternNode*>&InstResults,
1871 std::vector<Record*> &InstImpInputs,
1872 std::vector<Record*> &InstImpResults) {
1873 if (Pat->isLeaf()) {
1874 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1875 if (!isUse && Pat->getTransformFn())
1876 I->error("Cannot specify a transform function for a non-input value!");
1877 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001878 }
1879
1880 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001881 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1882 TreePatternNode *Dest = Pat->getChild(i);
1883 if (!Dest->isLeaf())
1884 I->error("implicitly defined value should be a register!");
1885
1886 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1887 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1888 I->error("implicitly defined value should be a register!");
1889 InstImpResults.push_back(Val->getDef());
1890 }
1891 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001892 }
1893
1894 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001895 // If this is not a set, verify that the children nodes are not void typed,
1896 // and recurse.
1897 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001898 if (Pat->getChild(i)->getType() == MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00001899 I->error("Cannot have void nodes inside of patterns!");
1900 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1901 InstImpInputs, InstImpResults);
1902 }
1903
1904 // If this is a non-leaf node with no children, treat it basically as if
1905 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00001906 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00001907
1908 if (!isUse && Pat->getTransformFn())
1909 I->error("Cannot specify a transform function for a non-input value!");
1910 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001911 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001912
1913 // Otherwise, this is a set, validate and collect instruction results.
1914 if (Pat->getNumChildren() == 0)
1915 I->error("set requires operands!");
1916
1917 if (Pat->getTransformFn())
1918 I->error("Cannot specify a transform function on a set node!");
1919
1920 // Check the set destinations.
1921 unsigned NumDests = Pat->getNumChildren()-1;
1922 for (unsigned i = 0; i != NumDests; ++i) {
1923 TreePatternNode *Dest = Pat->getChild(i);
1924 if (!Dest->isLeaf())
1925 I->error("set destination should be a register!");
1926
1927 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1928 if (!Val)
1929 I->error("set destination should be a register!");
1930
1931 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00001932 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001933 if (Dest->getName().empty())
1934 I->error("set destination must have a name!");
1935 if (InstResults.count(Dest->getName()))
1936 I->error("cannot set '" + Dest->getName() +"' multiple times");
1937 InstResults[Dest->getName()] = Dest;
1938 } else if (Val->getDef()->isSubClassOf("Register")) {
1939 InstImpResults.push_back(Val->getDef());
1940 } else {
1941 I->error("set destination should be a register!");
1942 }
1943 }
1944
1945 // Verify and collect info from the computation.
1946 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1947 InstInputs, InstResults,
1948 InstImpInputs, InstImpResults);
1949}
1950
Dan Gohmanee4fa192008-04-03 00:02:49 +00001951//===----------------------------------------------------------------------===//
1952// Instruction Analysis
1953//===----------------------------------------------------------------------===//
1954
1955class InstAnalyzer {
1956 const CodeGenDAGPatterns &CDP;
1957 bool &mayStore;
1958 bool &mayLoad;
1959 bool &HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00001960 bool &IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00001961public:
1962 InstAnalyzer(const CodeGenDAGPatterns &cdp,
Chris Lattner1e506312010-03-19 05:34:15 +00001963 bool &maystore, bool &mayload, bool &hse, bool &isv)
1964 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
1965 IsVariadic(isv) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00001966 }
1967
1968 /// Analyze - Analyze the specified instruction, returning true if the
1969 /// instruction had a pattern.
1970 bool Analyze(Record *InstRecord) {
1971 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1972 if (Pattern == 0) {
1973 HasSideEffects = 1;
1974 return false; // No pattern.
1975 }
1976
1977 // FIXME: Assume only the first tree is the pattern. The others are clobber
1978 // nodes.
1979 AnalyzeNode(Pattern->getTree(0));
1980 return true;
1981 }
1982
1983private:
1984 void AnalyzeNode(const TreePatternNode *N) {
1985 if (N->isLeaf()) {
1986 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1987 Record *LeafRec = DI->getDef();
1988 // Handle ComplexPattern leaves.
1989 if (LeafRec->isSubClassOf("ComplexPattern")) {
1990 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1991 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1992 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1993 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1994 }
1995 }
1996 return;
1997 }
1998
1999 // Analyze children.
2000 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2001 AnalyzeNode(N->getChild(i));
2002
2003 // Ignore set nodes, which are not SDNodes.
2004 if (N->getOperator()->getName() == "set")
2005 return;
2006
2007 // Get information about the SDNode for the operator.
2008 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2009
2010 // Notice properties of the node.
2011 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2012 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2013 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
Chris Lattner1e506312010-03-19 05:34:15 +00002014 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002015
2016 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2017 // If this is an intrinsic, analyze it.
2018 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2019 mayLoad = true;// These may load memory.
2020
2021 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2022 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2023
2024 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2025 // WriteMem intrinsics can have other strange effects.
2026 HasSideEffects = true;
2027 }
2028 }
2029
2030};
2031
2032static void InferFromPattern(const CodeGenInstruction &Inst,
2033 bool &MayStore, bool &MayLoad,
Chris Lattner1e506312010-03-19 05:34:15 +00002034 bool &HasSideEffects, bool &IsVariadic,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002035 const CodeGenDAGPatterns &CDP) {
Chris Lattner1e506312010-03-19 05:34:15 +00002036 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002037
2038 bool HadPattern =
Chris Lattner1e506312010-03-19 05:34:15 +00002039 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2040 .Analyze(Inst.TheDef);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002041
2042 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2043 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2044 // If we decided that this is a store from the pattern, then the .td file
2045 // entry is redundant.
2046 if (MayStore)
2047 fprintf(stderr,
2048 "Warning: mayStore flag explicitly set on instruction '%s'"
2049 " but flag already inferred from pattern.\n",
2050 Inst.TheDef->getName().c_str());
2051 MayStore = true;
2052 }
2053
2054 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2055 // If we decided that this is a load from the pattern, then the .td file
2056 // entry is redundant.
2057 if (MayLoad)
2058 fprintf(stderr,
2059 "Warning: mayLoad flag explicitly set on instruction '%s'"
2060 " but flag already inferred from pattern.\n",
2061 Inst.TheDef->getName().c_str());
2062 MayLoad = true;
2063 }
2064
2065 if (Inst.neverHasSideEffects) {
2066 if (HadPattern)
2067 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2068 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2069 HasSideEffects = false;
2070 }
2071
2072 if (Inst.hasSideEffects) {
2073 if (HasSideEffects)
2074 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2075 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2076 HasSideEffects = true;
2077 }
Chris Lattner1e506312010-03-19 05:34:15 +00002078
2079 if (Inst.isVariadic)
2080 IsVariadic = true; // Can warn if we want.
Dan Gohmanee4fa192008-04-03 00:02:49 +00002081}
2082
Chris Lattner6cefb772008-01-05 22:25:12 +00002083/// ParseInstructions - Parse all of the instructions, inlining and resolving
2084/// any fragments involved. This populates the Instructions list with fully
2085/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002086void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002087 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2088
2089 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2090 ListInit *LI = 0;
2091
2092 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2093 LI = Instrs[i]->getValueAsListInit("Pattern");
2094
2095 // If there is no pattern, only collect minimal information about the
2096 // instruction for its operand list. We have to assume that there is one
2097 // result, as we have no detailed info.
2098 if (!LI || LI->getSize() == 0) {
2099 std::vector<Record*> Results;
2100 std::vector<Record*> Operands;
2101
Chris Lattnerf30187a2010-03-19 00:07:20 +00002102 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002103
2104 if (InstInfo.OperandList.size() != 0) {
2105 if (InstInfo.NumDefs == 0) {
2106 // These produce no results
2107 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2108 Operands.push_back(InstInfo.OperandList[j].Rec);
2109 } else {
2110 // Assume the first operand is the result.
2111 Results.push_back(InstInfo.OperandList[0].Rec);
2112
2113 // The rest are inputs.
2114 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2115 Operands.push_back(InstInfo.OperandList[j].Rec);
2116 }
2117 }
2118
2119 // Create and insert the instruction.
2120 std::vector<Record*> ImpResults;
2121 std::vector<Record*> ImpOperands;
2122 Instructions.insert(std::make_pair(Instrs[i],
2123 DAGInstruction(0, Results, Operands, ImpResults,
2124 ImpOperands)));
2125 continue; // no pattern.
2126 }
2127
2128 // Parse the instruction.
2129 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2130 // Inline pattern fragments into it.
2131 I->InlinePatternFragments();
2132
2133 // Infer as many types as possible. If we cannot infer all of them, we can
2134 // never do anything with this instruction pattern: report it to the user.
2135 if (!I->InferAllTypes())
2136 I->error("Could not infer all types in pattern!");
2137
2138 // InstInputs - Keep track of all of the inputs of the instruction, along
2139 // with the record they are declared as.
2140 std::map<std::string, TreePatternNode*> InstInputs;
2141
2142 // InstResults - Keep track of all the virtual registers that are 'set'
2143 // in the instruction, including what reg class they are.
2144 std::map<std::string, TreePatternNode*> InstResults;
2145
2146 std::vector<Record*> InstImpInputs;
2147 std::vector<Record*> InstImpResults;
2148
2149 // Verify that the top-level forms in the instruction are of void type, and
2150 // fill in the InstResults map.
2151 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2152 TreePatternNode *Pat = I->getTree(j);
Chris Lattner2cacec52010-03-15 06:00:16 +00002153 if (!Pat->hasTypeSet() || Pat->getType() != MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00002154 I->error("Top-level forms in instruction pattern should have"
2155 " void types");
2156
2157 // Find inputs and outputs, and verify the structure of the uses/defs.
2158 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2159 InstImpInputs, InstImpResults);
2160 }
2161
2162 // Now that we have inputs and outputs of the pattern, inspect the operands
2163 // list for the instruction. This determines the order that operands are
2164 // added to the machine instruction the node corresponds to.
2165 unsigned NumResults = InstResults.size();
2166
2167 // Parse the operands list from the (ops) list, validating it.
2168 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002169 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002170
2171 // Check that all of the results occur first in the list.
2172 std::vector<Record*> Results;
2173 TreePatternNode *Res0Node = NULL;
2174 for (unsigned i = 0; i != NumResults; ++i) {
2175 if (i == CGI.OperandList.size())
2176 I->error("'" + InstResults.begin()->first +
2177 "' set but does not appear in operand list!");
2178 const std::string &OpName = CGI.OperandList[i].Name;
2179
2180 // Check that it exists in InstResults.
2181 TreePatternNode *RNode = InstResults[OpName];
2182 if (RNode == 0)
2183 I->error("Operand $" + OpName + " does not exist in operand list!");
2184
2185 if (i == 0)
2186 Res0Node = RNode;
2187 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2188 if (R == 0)
2189 I->error("Operand $" + OpName + " should be a set destination: all "
2190 "outputs must occur before inputs in operand list!");
2191
2192 if (CGI.OperandList[i].Rec != R)
2193 I->error("Operand $" + OpName + " class mismatch!");
2194
2195 // Remember the return type.
2196 Results.push_back(CGI.OperandList[i].Rec);
2197
2198 // Okay, this one checks out.
2199 InstResults.erase(OpName);
2200 }
2201
2202 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2203 // the copy while we're checking the inputs.
2204 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2205
2206 std::vector<TreePatternNode*> ResultNodeOperands;
2207 std::vector<Record*> Operands;
2208 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2209 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2210 const std::string &OpName = Op.Name;
2211 if (OpName.empty())
2212 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2213
2214 if (!InstInputsCheck.count(OpName)) {
2215 // If this is an predicate operand or optional def operand with an
2216 // DefaultOps set filled in, we can ignore this. When we codegen it,
2217 // we will do so as always executed.
2218 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2219 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2220 // Does it have a non-empty DefaultOps field? If so, ignore this
2221 // operand.
2222 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2223 continue;
2224 }
2225 I->error("Operand $" + OpName +
2226 " does not appear in the instruction pattern");
2227 }
2228 TreePatternNode *InVal = InstInputsCheck[OpName];
2229 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2230
2231 if (InVal->isLeaf() &&
2232 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2233 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2234 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2235 I->error("Operand $" + OpName + "'s register class disagrees"
2236 " between the operand and pattern");
2237 }
2238 Operands.push_back(Op.Rec);
2239
2240 // Construct the result for the dest-pattern operand list.
2241 TreePatternNode *OpNode = InVal->clone();
2242
2243 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002244 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002245
2246 // Promote the xform function to be an explicit node if set.
2247 if (Record *Xform = OpNode->getTransformFn()) {
2248 OpNode->setTransformFn(0);
2249 std::vector<TreePatternNode*> Children;
2250 Children.push_back(OpNode);
2251 OpNode = new TreePatternNode(Xform, Children);
2252 }
2253
2254 ResultNodeOperands.push_back(OpNode);
2255 }
2256
2257 if (!InstInputsCheck.empty())
2258 I->error("Input operand $" + InstInputsCheck.begin()->first +
2259 " occurs in pattern but not in operands list!");
2260
2261 TreePatternNode *ResultPattern =
2262 new TreePatternNode(I->getRecord(), ResultNodeOperands);
2263 // Copy fully inferred output node type to instruction result pattern.
2264 if (NumResults > 0)
Chris Lattner2cacec52010-03-15 06:00:16 +00002265 ResultPattern->setType(Res0Node->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002266
2267 // Create and insert the instruction.
2268 // FIXME: InstImpResults and InstImpInputs should not be part of
2269 // DAGInstruction.
2270 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2271 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2272
2273 // Use a temporary tree pattern to infer all types and make sure that the
2274 // constructed result is correct. This depends on the instruction already
2275 // being inserted into the Instructions map.
2276 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002277 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002278
2279 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2280 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2281
2282 DEBUG(I->dump());
2283 }
2284
2285 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002286 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2287 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002288 E = Instructions.end(); II != E; ++II) {
2289 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002290 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002291 if (I == 0) continue; // No pattern.
2292
2293 // FIXME: Assume only the first tree is the pattern. The others are clobber
2294 // nodes.
2295 TreePatternNode *Pattern = I->getTree(0);
2296 TreePatternNode *SrcPattern;
2297 if (Pattern->getOperator()->getName() == "set") {
2298 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2299 } else{
2300 // Not a set (store or something?)
2301 SrcPattern = Pattern;
2302 }
2303
Chris Lattner6cefb772008-01-05 22:25:12 +00002304 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002305 AddPatternToMatch(I,
2306 PatternToMatch(Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002307 SrcPattern,
2308 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002309 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002310 Instr->getValueAsInt("AddedComplexity"),
2311 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002312 }
2313}
2314
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002315
2316typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2317
Chris Lattner967d54a2010-02-23 06:35:45 +00002318static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002319 std::map<std::string, NameRecord> &Names,
2320 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002321 if (!P->getName().empty()) {
2322 NameRecord &Rec = Names[P->getName()];
2323 // If this is the first instance of the name, remember the node.
2324 if (Rec.second++ == 0)
2325 Rec.first = P;
Chris Lattner2cacec52010-03-15 06:00:16 +00002326 else if (Rec.first->getType() != P->getType())
Chris Lattnera27234e2010-02-23 07:22:28 +00002327 PatternTop->error("repetition of value: $" + P->getName() +
2328 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002329 }
Chris Lattner967d54a2010-02-23 06:35:45 +00002330
2331 if (!P->isLeaf()) {
2332 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002333 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002334 }
2335}
2336
Chris Lattner25b6f912010-02-23 06:16:51 +00002337void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2338 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002339 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002340 std::string Reason;
2341 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002342 Pattern->error("Pattern can never match: " + Reason);
Chris Lattner25b6f912010-02-23 06:16:51 +00002343
Chris Lattner405f1252010-03-01 22:29:19 +00002344 // If the source pattern's root is a complex pattern, that complex pattern
2345 // must specify the nodes it can potentially match.
2346 if (const ComplexPattern *CP =
2347 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2348 if (CP->getRootNodes().empty())
2349 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2350 " could match");
2351
2352
Chris Lattner967d54a2010-02-23 06:35:45 +00002353 // Find all of the named values in the input and output, ensure they have the
2354 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002355 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002356 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2357 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002358
2359 // Scan all of the named values in the destination pattern, rejecting them if
2360 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002361 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002362 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002363 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002364 Pattern->error("Pattern has input without matching name in output: $" +
2365 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002366 }
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002367
2368 // Scan all of the named values in the source pattern, rejecting them if the
2369 // name isn't used in the dest, and isn't used to tie two values together.
2370 for (std::map<std::string, NameRecord>::iterator
2371 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2372 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2373 Pattern->error("Pattern has dead named input: $" + I->first);
2374
Chris Lattner25b6f912010-02-23 06:16:51 +00002375 PatternsToMatch.push_back(PTM);
2376}
2377
2378
Dan Gohmanee4fa192008-04-03 00:02:49 +00002379
2380void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002381 const std::vector<const CodeGenInstruction*> &Instructions =
2382 Target.getInstructionsByEnumValue();
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002383 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2384 CodeGenInstruction &InstInfo =
2385 const_cast<CodeGenInstruction &>(*Instructions[i]);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002386 // Determine properties of the instruction from its pattern.
Chris Lattner1e506312010-03-19 05:34:15 +00002387 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2388 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2389 *this);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002390 InstInfo.mayStore = MayStore;
2391 InstInfo.mayLoad = MayLoad;
2392 InstInfo.hasSideEffects = HasSideEffects;
Chris Lattner1e506312010-03-19 05:34:15 +00002393 InstInfo.isVariadic = IsVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002394 }
2395}
2396
Chris Lattner2cacec52010-03-15 06:00:16 +00002397/// Given a pattern result with an unresolved type, see if we can find one
2398/// instruction with an unresolved result type. Force this result type to an
2399/// arbitrary element if it's possible types to converge results.
2400static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2401 if (N->isLeaf())
2402 return false;
2403
2404 // Analyze children.
2405 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2406 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2407 return true;
2408
2409 if (!N->getOperator()->isSubClassOf("Instruction"))
2410 return false;
2411
2412 // If this type is already concrete or completely unknown we can't do
2413 // anything.
2414 if (N->getExtType().isCompletelyUnknown() || N->getExtType().isConcrete())
2415 return false;
2416
2417 // Otherwise, force its type to the first possibility (an arbitrary choice).
2418 return N->getExtType().MergeInTypeInfo(N->getExtType().getTypeList()[0], TP);
2419}
2420
Chris Lattnerfe718932008-01-06 01:10:31 +00002421void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002422 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2423
2424 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2425 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2426 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2427 Record *Operator = OpDef->getDef();
2428 TreePattern *Pattern;
2429 if (Operator->getName() != "parallel")
2430 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2431 else {
2432 std::vector<Init*> Values;
David Greenee1b46912009-06-08 20:23:18 +00002433 RecTy *ListTy = 0;
2434 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002435 Values.push_back(Tree->getArg(j));
David Greenee1b46912009-06-08 20:23:18 +00002436 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2437 if (TArg == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002438 errs() << "In dag: " << Tree->getAsString();
2439 errs() << " -- Untyped argument in pattern\n";
David Greenee1b46912009-06-08 20:23:18 +00002440 assert(0 && "Untyped argument in pattern");
2441 }
2442 if (ListTy != 0) {
2443 ListTy = resolveTypes(ListTy, TArg->getType());
2444 if (ListTy == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002445 errs() << "In dag: " << Tree->getAsString();
2446 errs() << " -- Incompatible types in pattern arguments\n";
David Greenee1b46912009-06-08 20:23:18 +00002447 assert(0 && "Incompatible types in pattern arguments");
2448 }
2449 }
2450 else {
Bill Wendlingee1f6b02009-06-09 18:49:42 +00002451 ListTy = TArg->getType();
David Greenee1b46912009-06-08 20:23:18 +00002452 }
2453 }
2454 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
Chris Lattner6cefb772008-01-05 22:25:12 +00002455 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2456 }
2457
2458 // Inline pattern fragments into it.
2459 Pattern->InlinePatternFragments();
2460
2461 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2462 if (LI->getSize() == 0) continue; // no pattern.
2463
2464 // Parse the instruction.
2465 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2466
2467 // Inline pattern fragments into it.
2468 Result->InlinePatternFragments();
2469
2470 if (Result->getNumTrees() != 1)
2471 Result->error("Cannot handle instructions producing instructions "
2472 "with temporaries yet!");
2473
2474 bool IterateInference;
2475 bool InferredAllPatternTypes, InferredAllResultTypes;
2476 do {
2477 // Infer as many types as possible. If we cannot infer all of them, we
2478 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002479 InferredAllPatternTypes =
2480 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002481
2482 // Infer as many types as possible. If we cannot infer all of them, we
2483 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00002484 InferredAllResultTypes =
2485 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002486
Chris Lattner6c6ba362010-03-18 23:15:10 +00002487 IterateInference = false;
2488
Chris Lattner6cefb772008-01-05 22:25:12 +00002489 // Apply the type of the result to the source pattern. This helps us
2490 // resolve cases where the input type is known to be a pointer type (which
2491 // is considered resolved), but the result knows it needs to be 32- or
2492 // 64-bits. Infer the other way for good measure.
Chris Lattner6c6ba362010-03-18 23:15:10 +00002493 if (!Result->getTree(0)->getExtType().isVoid() &&
2494 !Pattern->getTree(0)->getExtType().isVoid()) {
2495 IterateInference = Pattern->getTree(0)->
2496 UpdateNodeType(Result->getTree(0)->getExtType(), *Result);
2497 IterateInference |= Result->getTree(0)->
2498 UpdateNodeType(Pattern->getTree(0)->getExtType(), *Result);
2499 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002500
2501 // If our iteration has converged and the input pattern's types are fully
2502 // resolved but the result pattern is not fully resolved, we may have a
2503 // situation where we have two instructions in the result pattern and
2504 // the instructions require a common register class, but don't care about
2505 // what actual MVT is used. This is actually a bug in our modelling:
2506 // output patterns should have register classes, not MVTs.
2507 //
2508 // In any case, to handle this, we just go through and disambiguate some
2509 // arbitrary types to the result pattern's nodes.
2510 if (!IterateInference && InferredAllPatternTypes &&
2511 !InferredAllResultTypes)
2512 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2513 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00002514 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002515
Chris Lattner6cefb772008-01-05 22:25:12 +00002516 // Verify that we inferred enough types that we can do something with the
2517 // pattern and result. If these fire the user has to add type casts.
2518 if (!InferredAllPatternTypes)
2519 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002520 if (!InferredAllResultTypes) {
2521 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00002522 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00002523 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002524
2525 // Validate that the input pattern is correct.
2526 std::map<std::string, TreePatternNode*> InstInputs;
2527 std::map<std::string, TreePatternNode*> InstResults;
2528 std::vector<Record*> InstImpInputs;
2529 std::vector<Record*> InstImpResults;
2530 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2531 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2532 InstInputs, InstResults,
2533 InstImpInputs, InstImpResults);
2534
2535 // Promote the xform function to be an explicit node if set.
2536 TreePatternNode *DstPattern = Result->getOnlyTree();
2537 std::vector<TreePatternNode*> ResultNodeOperands;
2538 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2539 TreePatternNode *OpNode = DstPattern->getChild(ii);
2540 if (Record *Xform = OpNode->getTransformFn()) {
2541 OpNode->setTransformFn(0);
2542 std::vector<TreePatternNode*> Children;
2543 Children.push_back(OpNode);
2544 OpNode = new TreePatternNode(Xform, Children);
2545 }
2546 ResultNodeOperands.push_back(OpNode);
2547 }
2548 DstPattern = Result->getOnlyTree();
2549 if (!DstPattern->isLeaf())
2550 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2551 ResultNodeOperands);
Chris Lattner2cacec52010-03-15 06:00:16 +00002552 DstPattern->setType(Result->getOnlyTree()->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002553 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2554 Temp.InferAllTypes();
2555
Chris Lattner6cefb772008-01-05 22:25:12 +00002556
Chris Lattner25b6f912010-02-23 06:16:51 +00002557 AddPatternToMatch(Pattern,
2558 PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2559 Pattern->getTree(0),
2560 Temp.getOnlyTree(), InstImpResults,
Chris Lattner117ccb72010-03-01 22:09:11 +00002561 Patterns[i]->getValueAsInt("AddedComplexity"),
2562 Patterns[i]->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002563 }
2564}
2565
2566/// CombineChildVariants - Given a bunch of permutations of each child of the
2567/// 'operator' node, put them together in all possible ways.
2568static void CombineChildVariants(TreePatternNode *Orig,
2569 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2570 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002571 CodeGenDAGPatterns &CDP,
2572 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002573 // Make sure that each operand has at least one variant to choose from.
2574 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2575 if (ChildVariants[i].empty())
2576 return;
2577
2578 // The end result is an all-pairs construction of the resultant pattern.
2579 std::vector<unsigned> Idxs;
2580 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002581 bool NotDone;
2582 do {
2583#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002584 DEBUG(if (!Idxs.empty()) {
2585 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2586 for (unsigned i = 0; i < Idxs.size(); ++i) {
2587 errs() << Idxs[i] << " ";
2588 }
2589 errs() << "]\n";
2590 });
Scott Michel327d0652008-03-05 17:49:05 +00002591#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002592 // Create the variant and add it to the output list.
2593 std::vector<TreePatternNode*> NewChildren;
2594 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2595 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2596 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2597
2598 // Copy over properties.
2599 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002600 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002601 R->setTransformFn(Orig->getTransformFn());
Chris Lattner2cacec52010-03-15 06:00:16 +00002602 R->setType(Orig->getExtType());
Chris Lattner6cefb772008-01-05 22:25:12 +00002603
Scott Michel327d0652008-03-05 17:49:05 +00002604 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002605 std::string ErrString;
2606 if (!R->canPatternMatch(ErrString, CDP)) {
2607 delete R;
2608 } else {
2609 bool AlreadyExists = false;
2610
2611 // Scan to see if this pattern has already been emitted. We can get
2612 // duplication due to things like commuting:
2613 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2614 // which are the same pattern. Ignore the dups.
2615 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002616 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002617 AlreadyExists = true;
2618 break;
2619 }
2620
2621 if (AlreadyExists)
2622 delete R;
2623 else
2624 OutVariants.push_back(R);
2625 }
2626
Scott Michel327d0652008-03-05 17:49:05 +00002627 // Increment indices to the next permutation by incrementing the
2628 // indicies from last index backward, e.g., generate the sequence
2629 // [0, 0], [0, 1], [1, 0], [1, 1].
2630 int IdxsIdx;
2631 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2632 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2633 Idxs[IdxsIdx] = 0;
2634 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002635 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002636 }
Scott Michel327d0652008-03-05 17:49:05 +00002637 NotDone = (IdxsIdx >= 0);
2638 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002639}
2640
2641/// CombineChildVariants - A helper function for binary operators.
2642///
2643static void CombineChildVariants(TreePatternNode *Orig,
2644 const std::vector<TreePatternNode*> &LHS,
2645 const std::vector<TreePatternNode*> &RHS,
2646 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002647 CodeGenDAGPatterns &CDP,
2648 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002649 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2650 ChildVariants.push_back(LHS);
2651 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002652 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002653}
2654
2655
2656static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2657 std::vector<TreePatternNode *> &Children) {
2658 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2659 Record *Operator = N->getOperator();
2660
2661 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002662 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002663 N->getTransformFn()) {
2664 Children.push_back(N);
2665 return;
2666 }
2667
2668 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2669 Children.push_back(N->getChild(0));
2670 else
2671 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2672
2673 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2674 Children.push_back(N->getChild(1));
2675 else
2676 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2677}
2678
2679/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2680/// the (potentially recursive) pattern by using algebraic laws.
2681///
2682static void GenerateVariantsOf(TreePatternNode *N,
2683 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002684 CodeGenDAGPatterns &CDP,
2685 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002686 // We cannot permute leaves.
2687 if (N->isLeaf()) {
2688 OutVariants.push_back(N);
2689 return;
2690 }
2691
2692 // Look up interesting info about the node.
2693 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2694
Jim Grosbachda4231f2009-03-26 16:17:51 +00002695 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002696 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002697 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002698 std::vector<TreePatternNode*> MaximalChildren;
2699 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2700
2701 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2702 // permutations.
2703 if (MaximalChildren.size() == 3) {
2704 // Find the variants of all of our maximal children.
2705 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002706 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2707 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2708 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002709
2710 // There are only two ways we can permute the tree:
2711 // (A op B) op C and A op (B op C)
2712 // Within these forms, we can also permute A/B/C.
2713
2714 // Generate legal pair permutations of A/B/C.
2715 std::vector<TreePatternNode*> ABVariants;
2716 std::vector<TreePatternNode*> BAVariants;
2717 std::vector<TreePatternNode*> ACVariants;
2718 std::vector<TreePatternNode*> CAVariants;
2719 std::vector<TreePatternNode*> BCVariants;
2720 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002721 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2722 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2723 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2724 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2725 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2726 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002727
2728 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002729 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2730 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2731 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2732 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2733 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2734 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002735
2736 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002737 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2738 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2739 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2740 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2741 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2742 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002743 return;
2744 }
2745 }
2746
2747 // Compute permutations of all children.
2748 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2749 ChildVariants.resize(N->getNumChildren());
2750 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002751 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002752
2753 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002754 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002755
2756 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002757 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2758 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2759 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2760 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002761 // Don't count children which are actually register references.
2762 unsigned NC = 0;
2763 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2764 TreePatternNode *Child = N->getChild(i);
2765 if (Child->isLeaf())
2766 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2767 Record *RR = DI->getDef();
2768 if (RR->isSubClassOf("Register"))
2769 continue;
2770 }
2771 NC++;
2772 }
2773 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002774 if (isCommIntrinsic) {
2775 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2776 // operands are the commutative operands, and there might be more operands
2777 // after those.
2778 assert(NC >= 3 &&
2779 "Commutative intrinsic should have at least 3 childrean!");
2780 std::vector<std::vector<TreePatternNode*> > Variants;
2781 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2782 Variants.push_back(ChildVariants[2]);
2783 Variants.push_back(ChildVariants[1]);
2784 for (unsigned i = 3; i != NC; ++i)
2785 Variants.push_back(ChildVariants[i]);
2786 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2787 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002788 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002789 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002790 }
2791}
2792
2793
2794// GenerateVariants - Generate variants. For example, commutative patterns can
2795// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002796void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002797 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002798
2799 // Loop over all of the patterns we've collected, checking to see if we can
2800 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002801 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002802 // the .td file having to contain tons of variants of instructions.
2803 //
2804 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2805 // intentionally do not reconsider these. Any variants of added patterns have
2806 // already been added.
2807 //
2808 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002809 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002810 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002811 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002812 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002813 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002814 DEBUG(errs() << "\n");
Scott Michel327d0652008-03-05 17:49:05 +00002815 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002816
2817 assert(!Variants.empty() && "Must create at least original variant!");
2818 Variants.erase(Variants.begin()); // Remove the original pattern.
2819
2820 if (Variants.empty()) // No variants for this pattern.
2821 continue;
2822
Chris Lattner569f1212009-08-23 04:44:11 +00002823 DEBUG(errs() << "FOUND VARIANTS OF: ";
2824 PatternsToMatch[i].getSrcPattern()->dump();
2825 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002826
2827 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2828 TreePatternNode *Variant = Variants[v];
2829
Chris Lattner569f1212009-08-23 04:44:11 +00002830 DEBUG(errs() << " VAR#" << v << ": ";
2831 Variant->dump();
2832 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002833
2834 // Scan to see if an instruction or explicit pattern already matches this.
2835 bool AlreadyExists = false;
2836 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00002837 // Skip if the top level predicates do not match.
2838 if (PatternsToMatch[i].getPredicates() !=
2839 PatternsToMatch[p].getPredicates())
2840 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00002841 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002842 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00002843 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002844 AlreadyExists = true;
2845 break;
2846 }
2847 }
2848 // If we already have it, ignore the variant.
2849 if (AlreadyExists) continue;
2850
2851 // Otherwise, add it to the list of patterns we have.
2852 PatternsToMatch.
2853 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2854 Variant, PatternsToMatch[i].getDstPattern(),
2855 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002856 PatternsToMatch[i].getAddedComplexity(),
2857 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002858 }
2859
Chris Lattner569f1212009-08-23 04:44:11 +00002860 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002861 }
2862}
2863