blob: d35a2631ffb2e7f5bc6ad2701041533ffdd555d6 [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 Lattner2cacec52010-03-15 06:00:16 +000016#include "llvm/ADT/STLExtras.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000017#include "llvm/ADT/StringExtras.h"
Jim Grosbach9b29ea42012-04-18 17:46:41 +000018#include "llvm/ADT/Twine.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include "llvm/Support/Debug.h"
David Blaikiefdebc382012-01-17 04:43:56 +000020#include "llvm/Support/ErrorHandling.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000021#include "llvm/TableGen/Error.h"
22#include "llvm/TableGen/Record.h"
Chuck Rose III9a79de32008-01-15 21:43:17 +000023#include <algorithm>
Benjamin Kramer901b8582012-03-23 11:35:30 +000024#include <cstdio>
25#include <set>
Chris Lattner6cefb772008-01-05 22:25:12 +000026using namespace llvm;
27
28//===----------------------------------------------------------------------===//
Chris Lattner2cacec52010-03-15 06:00:16 +000029// EEVT::TypeSet Implementation
30//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +000031
Owen Anderson825b72b2009-08-11 20:47:22 +000032static inline bool isInteger(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000033 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000034}
Owen Anderson825b72b2009-08-11 20:47:22 +000035static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000036 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000037}
Owen Anderson825b72b2009-08-11 20:47:22 +000038static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000039 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000040}
Chris Lattner774ce292010-03-19 17:41:26 +000041static inline bool isScalar(MVT::SimpleValueType VT) {
42 return !EVT(VT).isVector();
43}
Duncan Sands83ec4b62008-06-06 12:08:01 +000044
Chris Lattner2cacec52010-03-15 06:00:16 +000045EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
46 if (VT == MVT::iAny)
47 EnforceInteger(TP);
48 else if (VT == MVT::fAny)
49 EnforceFloatingPoint(TP);
50 else if (VT == MVT::vAny)
51 EnforceVector(TP);
52 else {
53 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
54 VT == MVT::iPTRAny) && "Not a concrete type!");
55 TypeVec.push_back(VT);
56 }
Chris Lattner6cefb772008-01-05 22:25:12 +000057}
58
Chris Lattner2cacec52010-03-15 06:00:16 +000059
Jakob Stoklund Olesen26369a92013-03-17 17:26:09 +000060EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
Chris Lattner2cacec52010-03-15 06:00:16 +000061 assert(!VTList.empty() && "empty list?");
62 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +000063
Chris Lattner2cacec52010-03-15 06:00:16 +000064 if (!VTList.empty())
65 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
66 VTList[0] != MVT::fAny);
Jim Grosbachfbadcd02010-12-21 16:16:00 +000067
Chris Lattner0d7952e2010-03-27 20:32:26 +000068 // Verify no duplicates.
Chris Lattner2cacec52010-03-15 06:00:16 +000069 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner0d7952e2010-03-27 20:32:26 +000070 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner6cefb772008-01-05 22:25:12 +000071}
72
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000073/// FillWithPossibleTypes - Set to all legal types and return true, only valid
74/// on completely unknown type sets.
Chris Lattner774ce292010-03-19 17:41:26 +000075bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
76 bool (*Pred)(MVT::SimpleValueType),
77 const char *PredicateName) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000078 assert(isCompletelyUnknown());
Jakob Stoklund Olesen26369a92013-03-17 17:26:09 +000079 ArrayRef<MVT::SimpleValueType> LegalTypes =
Chris Lattner774ce292010-03-19 17:41:26 +000080 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +000081
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +000082 if (TP.hasError())
83 return false;
84
Chris Lattner774ce292010-03-19 17:41:26 +000085 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
86 if (Pred == 0 || Pred(LegalTypes[i]))
87 TypeVec.push_back(LegalTypes[i]);
88
89 // If we have nothing that matches the predicate, bail out.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +000090 if (TypeVec.empty()) {
Chris Lattner774ce292010-03-19 17:41:26 +000091 TP.error("Type inference contradiction found, no " +
Jim Grosbachfbadcd02010-12-21 16:16:00 +000092 std::string(PredicateName) + " types found");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +000093 return false;
94 }
Chris Lattner774ce292010-03-19 17:41:26 +000095 // No need to sort with one element.
96 if (TypeVec.size() == 1) return true;
97
98 // Remove duplicates.
99 array_pod_sort(TypeVec.begin(), TypeVec.end());
100 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000101
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000102 return true;
103}
Chris Lattner2cacec52010-03-15 06:00:16 +0000104
105/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
106/// integer value type.
107bool EEVT::TypeSet::hasIntegerTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isInteger(TypeVec[i]))
110 return true;
111 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000112}
Chris Lattner2cacec52010-03-15 06:00:16 +0000113
114/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
115/// a floating point value type.
116bool EEVT::TypeSet::hasFloatingPointTypes() const {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isFloatingPoint(TypeVec[i]))
119 return true;
120 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000121}
Chris Lattner2cacec52010-03-15 06:00:16 +0000122
123/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
124/// value type.
125bool EEVT::TypeSet::hasVectorTypes() const {
126 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
127 if (isVector(TypeVec[i]))
128 return true;
129 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +0000130}
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000131
Chris Lattner2cacec52010-03-15 06:00:16 +0000132
133std::string EEVT::TypeSet::getName() const {
Chris Lattneraac5b5b2010-03-19 01:14:27 +0000134 if (TypeVec.empty()) return "<empty>";
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000135
Chris Lattner2cacec52010-03-15 06:00:16 +0000136 std::string Result;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000137
Chris Lattner2cacec52010-03-15 06:00:16 +0000138 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
139 std::string VTName = llvm::getEnumName(TypeVec[i]);
140 // Strip off MVT:: prefix if present.
141 if (VTName.substr(0,5) == "MVT::")
142 VTName = VTName.substr(5);
143 if (i) Result += ':';
144 Result += VTName;
145 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000146
Chris Lattner2cacec52010-03-15 06:00:16 +0000147 if (TypeVec.size() == 1)
148 return Result;
149 return "{" + Result + "}";
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000150}
Chris Lattner2cacec52010-03-15 06:00:16 +0000151
152/// MergeInTypeInfo - This merges in type information from the specified
153/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000154/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattner2cacec52010-03-15 06:00:16 +0000155bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000156 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattner2cacec52010-03-15 06:00:16 +0000157 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000158
Chris Lattner2cacec52010-03-15 06:00:16 +0000159 if (isCompletelyUnknown()) {
160 *this = InVT;
161 return true;
162 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000163
Chris Lattner2cacec52010-03-15 06:00:16 +0000164 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000165
Chris Lattner2cacec52010-03-15 06:00:16 +0000166 // Handle the abstract cases, seeing if we can resolve them better.
167 switch (TypeVec[0]) {
168 default: break;
169 case MVT::iPTR:
170 case MVT::iPTRAny:
171 if (InVT.hasIntegerTypes()) {
172 EEVT::TypeSet InCopy(InVT);
173 InCopy.EnforceInteger(TP);
174 InCopy.EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000175
Chris Lattner2cacec52010-03-15 06:00:16 +0000176 if (InCopy.isConcrete()) {
177 // If the RHS has one integer type, upgrade iPTR to i32.
178 TypeVec[0] = InVT.TypeVec[0];
179 return true;
180 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000181
Chris Lattner2cacec52010-03-15 06:00:16 +0000182 // If the input has multiple scalar integers, this doesn't add any info.
183 if (!InCopy.isCompletelyUnknown())
184 return false;
185 }
186 break;
187 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000188
Chris Lattner2cacec52010-03-15 06:00:16 +0000189 // If the input constraint is iAny/iPTR and this is an integer type list,
190 // remove non-integer types from the list.
191 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
192 hasIntegerTypes()) {
193 bool MadeChange = EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000194
Chris Lattner2cacec52010-03-15 06:00:16 +0000195 // If we're merging in iPTR/iPTRAny and the node currently has a list of
196 // multiple different integer types, replace them with a single iPTR.
197 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
198 TypeVec.size() != 1) {
199 TypeVec.resize(1);
200 TypeVec[0] = InVT.TypeVec[0];
201 MadeChange = true;
202 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000203
Chris Lattner2cacec52010-03-15 06:00:16 +0000204 return MadeChange;
205 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000206
Chris Lattner2cacec52010-03-15 06:00:16 +0000207 // If this is a type list and the RHS is a typelist as well, eliminate entries
208 // from this list that aren't in the other one.
209 bool MadeChange = false;
210 TypeSet InputSet(*this);
211
212 for (unsigned i = 0; i != TypeVec.size(); ++i) {
213 bool InInVT = false;
214 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
215 if (TypeVec[i] == InVT.TypeVec[j]) {
216 InInVT = true;
217 break;
218 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000219
Chris Lattner2cacec52010-03-15 06:00:16 +0000220 if (InInVT) continue;
221 TypeVec.erase(TypeVec.begin()+i--);
222 MadeChange = true;
223 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000224
Chris Lattner2cacec52010-03-15 06:00:16 +0000225 // If we removed all of our types, we have a type contradiction.
226 if (!TypeVec.empty())
227 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000228
Chris Lattner2cacec52010-03-15 06:00:16 +0000229 // FIXME: Really want an SMLoc here!
230 TP.error("Type inference contradiction found, merging '" +
231 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000232 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +0000233}
234
235/// EnforceInteger - Remove all non-integer types from this set.
236bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000237 if (TP.hasError())
238 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +0000239 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000240 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000241 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattner2cacec52010-03-15 06:00:16 +0000242 if (!hasFloatingPointTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000243 return false;
244
245 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000246
Chris Lattner2cacec52010-03-15 06:00:16 +0000247 // Filter out all the fp types.
248 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000249 if (!isInteger(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000250 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000251
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000252 if (TypeVec.empty()) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000253 TP.error("Type inference contradiction found, '" +
254 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000255 return false;
256 }
Chris Lattner774ce292010-03-19 17:41:26 +0000257 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000258}
259
260/// EnforceFloatingPoint - Remove all integer types from this set.
261bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000262 if (TP.hasError())
263 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +0000264 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000265 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000266 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
267
Chris Lattner2cacec52010-03-15 06:00:16 +0000268 if (!hasIntegerTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000269 return false;
270
271 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000272
Chris Lattner2cacec52010-03-15 06:00:16 +0000273 // Filter out all the fp types.
274 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000275 if (!isFloatingPoint(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000276 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000277
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000278 if (TypeVec.empty()) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000279 TP.error("Type inference contradiction found, '" +
280 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000281 return false;
282 }
Chris Lattner774ce292010-03-19 17:41:26 +0000283 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000284}
285
286/// EnforceScalar - Remove all vector types from this.
287bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000288 if (TP.hasError())
289 return false;
290
Chris Lattner2cacec52010-03-15 06:00:16 +0000291 // If we know nothing, then get the full set.
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000292 if (TypeVec.empty())
Chris Lattner774ce292010-03-19 17:41:26 +0000293 return FillWithPossibleTypes(TP, isScalar, "scalar");
294
Chris Lattner2cacec52010-03-15 06:00:16 +0000295 if (!hasVectorTypes())
Chris Lattner774ce292010-03-19 17:41:26 +0000296 return false;
297
298 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000299
Chris Lattner2cacec52010-03-15 06:00:16 +0000300 // Filter out all the vector types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000302 if (!isScalar(TypeVec[i]))
Chris Lattner2cacec52010-03-15 06:00:16 +0000303 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000304
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000305 if (TypeVec.empty()) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000306 TP.error("Type inference contradiction found, '" +
307 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000308 return false;
309 }
Chris Lattner774ce292010-03-19 17:41:26 +0000310 return true;
Chris Lattner2cacec52010-03-15 06:00:16 +0000311}
312
313/// EnforceVector - Remove all vector types from this.
314bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000315 if (TP.hasError())
316 return false;
317
Chris Lattner774ce292010-03-19 17:41:26 +0000318 // If we know nothing, then get the full set.
319 if (TypeVec.empty())
320 return FillWithPossibleTypes(TP, isVector, "vector");
321
Chris Lattner2cacec52010-03-15 06:00:16 +0000322 TypeSet InputSet(*this);
323 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000324
Chris Lattner2cacec52010-03-15 06:00:16 +0000325 // Filter out all the scalar types.
326 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner774ce292010-03-19 17:41:26 +0000327 if (!isVector(TypeVec[i])) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000328 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner774ce292010-03-19 17:41:26 +0000329 MadeChange = true;
330 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000331
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000332 if (TypeVec.empty()) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000333 TP.error("Type inference contradiction found, '" +
334 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000335 return false;
336 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000337 return MadeChange;
338}
339
340
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000341
Chris Lattner2cacec52010-03-15 06:00:16 +0000342/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
343/// this an other based on this information.
344bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000345 if (TP.hasError())
346 return false;
347
Chris Lattner2cacec52010-03-15 06:00:16 +0000348 // Both operands must be integer or FP, but we don't care which.
349 bool MadeChange = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000350
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000351 if (isCompletelyUnknown())
352 MadeChange = FillWithPossibleTypes(TP);
353
354 if (Other.isCompletelyUnknown())
355 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000356
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000357 // If one side is known to be integer or known to be FP but the other side has
358 // no information, get at least the type integrality info in there.
359 if (!hasFloatingPointTypes())
360 MadeChange |= Other.EnforceInteger(TP);
361 else if (!hasIntegerTypes())
362 MadeChange |= Other.EnforceFloatingPoint(TP);
363 if (!Other.hasFloatingPointTypes())
364 MadeChange |= EnforceInteger(TP);
365 else if (!Other.hasIntegerTypes())
366 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000367
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000368 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
369 "Should have a type list now");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000370
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000371 // If one contains vectors but the other doesn't pull vectors out.
372 if (!hasVectorTypes())
373 MadeChange |= Other.EnforceScalar(TP);
374 if (!hasVectorTypes())
375 MadeChange |= EnforceScalar(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000376
David Greene9d7f0112011-02-01 19:12:32 +0000377 if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
378 // If we are down to concrete types, this code does not currently
379 // handle nodes which have multiple types, where some types are
380 // integer, and some are fp. Assert that this is not the case.
381 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
382 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
383 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
384
385 // Otherwise, if these are both vector types, either this vector
386 // must have a larger bitsize than the other, or this element type
387 // must be larger than the other.
388 EVT Type(TypeVec[0]);
389 EVT OtherType(Other.TypeVec[0]);
390
391 if (hasVectorTypes() && Other.hasVectorTypes()) {
392 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
393 if (Type.getVectorElementType().getSizeInBits()
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000394 >= OtherType.getVectorElementType().getSizeInBits()) {
David Greene9d7f0112011-02-01 19:12:32 +0000395 TP.error("Type inference contradiction found, '" +
396 getName() + "' element type not smaller than '" +
397 Other.getName() +"'!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000398 return false;
399 }
David Greene9d7f0112011-02-01 19:12:32 +0000400 }
401 else
402 // For scalar types, the bitsize of this type must be larger
403 // than that of the other.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000404 if (Type.getSizeInBits() >= OtherType.getSizeInBits()) {
David Greene9d7f0112011-02-01 19:12:32 +0000405 TP.error("Type inference contradiction found, '" +
406 getName() + "' is not smaller than '" +
407 Other.getName() +"'!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000408 return false;
409 }
David Greene9d7f0112011-02-01 19:12:32 +0000410 }
411
412
413 // Handle int and fp as disjoint sets. This won't work for patterns
414 // that have mixed fp/int types but those are likely rare and would
415 // not have been accepted by this code previously.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000416
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000417 // Okay, find the smallest type from the current set and remove it from the
418 // largest set.
David Greenec83e2032011-02-04 17:01:53 +0000419 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000420 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
421 if (isInteger(TypeVec[i])) {
422 SmallestInt = TypeVec[i];
423 break;
424 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000425 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000426 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
427 SmallestInt = TypeVec[i];
428
David Greenec83e2032011-02-04 17:01:53 +0000429 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
David Greene9d7f0112011-02-01 19:12:32 +0000430 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
431 if (isFloatingPoint(TypeVec[i])) {
432 SmallestFP = TypeVec[i];
433 break;
434 }
435 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
436 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
437 SmallestFP = TypeVec[i];
438
439 int OtherIntSize = 0;
440 int OtherFPSize = 0;
441 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
442 Other.TypeVec.begin();
443 TVI != Other.TypeVec.end();
444 /* NULL */) {
445 if (isInteger(*TVI)) {
446 ++OtherIntSize;
447 if (*TVI == SmallestInt) {
448 TVI = Other.TypeVec.erase(TVI);
449 --OtherIntSize;
450 MadeChange = true;
451 continue;
452 }
453 }
454 else if (isFloatingPoint(*TVI)) {
455 ++OtherFPSize;
456 if (*TVI == SmallestFP) {
457 TVI = Other.TypeVec.erase(TVI);
458 --OtherFPSize;
459 MadeChange = true;
460 continue;
461 }
462 }
463 ++TVI;
464 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000465
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000466 // If this is the only type in the large set, the constraint can never be
467 // satisfied.
David Greene9d7f0112011-02-01 19:12:32 +0000468 if ((Other.hasIntegerTypes() && OtherIntSize == 0)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000469 || (Other.hasFloatingPointTypes() && OtherFPSize == 0)) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000470 TP.error("Type inference contradiction found, '" +
471 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000472 return false;
473 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000474
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000475 // Okay, find the largest type in the Other set and remove it from the
476 // current set.
David Greenec83e2032011-02-04 17:01:53 +0000477 MVT::SimpleValueType LargestInt = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000478 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
479 if (isInteger(Other.TypeVec[i])) {
480 LargestInt = Other.TypeVec[i];
481 break;
482 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000483 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
David Greene9d7f0112011-02-01 19:12:32 +0000484 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
485 LargestInt = Other.TypeVec[i];
486
David Greenec83e2032011-02-04 17:01:53 +0000487 MVT::SimpleValueType LargestFP = MVT::Other;
David Greene9d7f0112011-02-01 19:12:32 +0000488 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
489 if (isFloatingPoint(Other.TypeVec[i])) {
490 LargestFP = Other.TypeVec[i];
491 break;
492 }
493 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
494 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
495 LargestFP = Other.TypeVec[i];
496
497 int IntSize = 0;
498 int FPSize = 0;
499 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
500 TypeVec.begin();
501 TVI != TypeVec.end();
502 /* NULL */) {
503 if (isInteger(*TVI)) {
504 ++IntSize;
505 if (*TVI == LargestInt) {
506 TVI = TypeVec.erase(TVI);
507 --IntSize;
508 MadeChange = true;
509 continue;
510 }
511 }
512 else if (isFloatingPoint(*TVI)) {
513 ++FPSize;
514 if (*TVI == LargestFP) {
515 TVI = TypeVec.erase(TVI);
516 --FPSize;
517 MadeChange = true;
518 continue;
519 }
520 }
521 ++TVI;
522 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000523
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000524 // If this is the only type in the small set, the constraint can never be
525 // satisfied.
David Greene9d7f0112011-02-01 19:12:32 +0000526 if ((hasIntegerTypes() && IntSize == 0)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000527 || (hasFloatingPointTypes() && FPSize == 0)) {
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000528 TP.error("Type inference contradiction found, '" +
529 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000530 return false;
531 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000532
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000533 return MadeChange;
Chris Lattner2cacec52010-03-15 06:00:16 +0000534}
535
536/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner66fb9d22010-03-24 00:01:16 +0000537/// whose element is specified by VTOperand.
538bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattner2cacec52010-03-15 06:00:16 +0000539 TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000540 if (TP.hasError())
541 return false;
542
Chris Lattner66fb9d22010-03-24 00:01:16 +0000543 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattner2cacec52010-03-15 06:00:16 +0000544 bool MadeChange = false;
Chris Lattner66fb9d22010-03-24 00:01:16 +0000545 MadeChange |= EnforceVector(TP);
546 MadeChange |= VTOperand.EnforceScalar(TP);
547
548 // If we know the vector type, it forces the scalar to agree.
549 if (isConcrete()) {
550 EVT IVT = getConcrete();
551 IVT = IVT.getVectorElementType();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000552 return MadeChange |
Chris Lattner66fb9d22010-03-24 00:01:16 +0000553 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
554 }
555
556 // If the scalar type is known, filter out vector types whose element types
557 // disagree.
558 if (!VTOperand.isConcrete())
559 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000560
Chris Lattner66fb9d22010-03-24 00:01:16 +0000561 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000562
Chris Lattner66fb9d22010-03-24 00:01:16 +0000563 TypeSet InputSet(*this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000564
Chris Lattner66fb9d22010-03-24 00:01:16 +0000565 // Filter out all the types which don't have the right element type.
566 for (unsigned i = 0; i != TypeVec.size(); ++i) {
567 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
568 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
Chris Lattner2cacec52010-03-15 06:00:16 +0000569 TypeVec.erase(TypeVec.begin()+i--);
570 MadeChange = true;
571 }
Chris Lattner66fb9d22010-03-24 00:01:16 +0000572 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000573
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000574 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattner2cacec52010-03-15 06:00:16 +0000575 TP.error("Type inference contradiction found, forcing '" +
576 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000577 return false;
578 }
Chris Lattner2cacec52010-03-15 06:00:16 +0000579 return MadeChange;
580}
581
David Greene60322692011-01-24 20:53:18 +0000582/// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
583/// vector type specified by VTOperand.
584bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
585 TreePattern &TP) {
586 // "This" must be a vector and "VTOperand" must be a vector.
587 bool MadeChange = false;
588 MadeChange |= EnforceVector(TP);
589 MadeChange |= VTOperand.EnforceVector(TP);
590
591 // "This" must be larger than "VTOperand."
592 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
593
594 // If we know the vector type, it forces the scalar types to agree.
595 if (isConcrete()) {
596 EVT IVT = getConcrete();
597 IVT = IVT.getVectorElementType();
598
599 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
600 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
601 } else if (VTOperand.isConcrete()) {
602 EVT IVT = VTOperand.getConcrete();
603 IVT = IVT.getVectorElementType();
604
605 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
606 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
607 }
608
609 return MadeChange;
610}
611
Chris Lattner2cacec52010-03-15 06:00:16 +0000612//===----------------------------------------------------------------------===//
613// Helpers for working with extended types.
Chris Lattner6cefb772008-01-05 22:25:12 +0000614
Scott Michel327d0652008-03-05 17:49:05 +0000615/// Dependent variable map for CodeGenDAGPattern variant generation
616typedef std::map<std::string, int> DepVarMap;
617
618/// Const iterator shorthand for DepVarMap
619typedef DepVarMap::const_iterator DepVarMap_citer;
620
Chris Lattner54379062011-04-17 21:38:24 +0000621static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel327d0652008-03-05 17:49:05 +0000622 if (N->isLeaf()) {
Sean Silva3f7b7f82012-10-10 20:24:47 +0000623 if (isa<DefInit>(N->getLeafValue()))
Scott Michel327d0652008-03-05 17:49:05 +0000624 DepMap[N->getName()]++;
Scott Michel327d0652008-03-05 17:49:05 +0000625 } else {
626 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
627 FindDepVarsOf(N->getChild(i), DepMap);
628 }
629}
Chris Lattner54379062011-04-17 21:38:24 +0000630
631/// Find dependent variables within child patterns
632static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000633 DepVarMap depcounts;
634 FindDepVarsOf(N, depcounts);
635 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner54379062011-04-17 21:38:24 +0000636 if (i->second > 1) // std::pair<std::string, int>
Scott Michel327d0652008-03-05 17:49:05 +0000637 DepVars.insert(i->first);
Scott Michel327d0652008-03-05 17:49:05 +0000638 }
639}
640
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000641#ifndef NDEBUG
Chris Lattner54379062011-04-17 21:38:24 +0000642/// Dump the dependent variable set:
643static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel327d0652008-03-05 17:49:05 +0000644 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000645 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000646 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000647 DEBUG(errs() << "[ ");
Jim Grosbachbb168242010-10-08 18:13:57 +0000648 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
649 e = DepVars.end(); i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000650 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000651 }
Chris Lattner569f1212009-08-23 04:44:11 +0000652 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000653 }
654}
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000655#endif
656
Chris Lattner54379062011-04-17 21:38:24 +0000657
658//===----------------------------------------------------------------------===//
659// TreePredicateFn Implementation
660//===----------------------------------------------------------------------===//
661
Chris Lattner7ed13912011-04-17 22:05:17 +0000662/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
663TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
664 assert((getPredCode().empty() || getImmCode().empty()) &&
665 ".td file corrupt: can't have a node predicate *and* an imm predicate");
666}
667
Chris Lattner54379062011-04-17 21:38:24 +0000668std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +0000669 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner54379062011-04-17 21:38:24 +0000670}
671
Chris Lattner7ed13912011-04-17 22:05:17 +0000672std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +0000673 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner7ed13912011-04-17 22:05:17 +0000674}
675
Chris Lattner54379062011-04-17 21:38:24 +0000676
677/// isAlwaysTrue - Return true if this is a noop predicate.
678bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000679 return getPredCode().empty() && getImmCode().empty();
Chris Lattner54379062011-04-17 21:38:24 +0000680}
681
682/// Return the name to use in the generated code to reference this, this is
683/// "Predicate_foo" if from a pattern fragment "foo".
684std::string TreePredicateFn::getFnName() const {
685 return "Predicate_" + PatFragRec->getRecord()->getName();
686}
687
688/// getCodeToRunOnSDNode - Return the code for the function body that
689/// evaluates this predicate. The argument is expected to be in "Node",
690/// not N. This handles casting and conversion to a concrete node type as
691/// appropriate.
692std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner7ed13912011-04-17 22:05:17 +0000693 // Handle immediate predicates first.
694 std::string ImmCode = getImmCode();
695 if (!ImmCode.empty()) {
696 std::string Result =
697 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner7ed13912011-04-17 22:05:17 +0000698 return Result + ImmCode;
699 }
700
701 // Handle arbitrary node predicates.
702 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner54379062011-04-17 21:38:24 +0000703 std::string ClassName;
704 if (PatFragRec->getOnlyTree()->isLeaf())
705 ClassName = "SDNode";
706 else {
707 Record *Op = PatFragRec->getOnlyTree()->getOperator();
708 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
709 }
710 std::string Result;
711 if (ClassName == "SDNode")
712 Result = " SDNode *N = Node;\n";
713 else
714 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
715
716 return Result + getPredCode();
Scott Michel327d0652008-03-05 17:49:05 +0000717}
718
Chris Lattner6cefb772008-01-05 22:25:12 +0000719//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000720// PatternToMatch implementation
721//
722
Chris Lattner48e86db2010-03-29 01:40:38 +0000723
724/// getPatternSize - Return the 'size' of this pattern. We want to match large
725/// patterns before small ones. This is used to determine the size of a
726/// pattern.
727static unsigned getPatternSize(const TreePatternNode *P,
728 const CodeGenDAGPatterns &CGP) {
729 unsigned Size = 3; // The node itself.
730 // If the root node is a ConstantSDNode, increases its size.
731 // e.g. (set R32:$dst, 0).
Sean Silva3f7b7f82012-10-10 20:24:47 +0000732 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000733 Size += 2;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000734
Chris Lattner48e86db2010-03-29 01:40:38 +0000735 // FIXME: This is a hack to statically increase the priority of patterns
736 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
737 // Later we can allow complexity / cost for each pattern to be (optionally)
738 // specified. To get best possible pattern match we'll need to dynamically
739 // calculate the complexity of all patterns a dag can potentially map to.
740 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
741 if (AM)
742 Size += AM->getNumOperands() * 3;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000743
Chris Lattner48e86db2010-03-29 01:40:38 +0000744 // If this node has some predicate function that must match, it adds to the
745 // complexity of this node.
746 if (!P->getPredicateFns().empty())
747 ++Size;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000748
Chris Lattner48e86db2010-03-29 01:40:38 +0000749 // Count children in the count if they are also nodes.
750 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
751 TreePatternNode *Child = P->getChild(i);
752 if (!Child->isLeaf() && Child->getNumTypes() &&
753 Child->getType(0) != MVT::Other)
754 Size += getPatternSize(Child, CGP);
755 else if (Child->isLeaf()) {
Sean Silva3f7b7f82012-10-10 20:24:47 +0000756 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +0000757 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
758 else if (Child->getComplexPatternInfo(CGP))
759 Size += getPatternSize(Child, CGP);
760 else if (!Child->getPredicateFns().empty())
761 ++Size;
762 }
763 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000764
Chris Lattner48e86db2010-03-29 01:40:38 +0000765 return Size;
766}
767
768/// Compute the complexity metric for the input pattern. This roughly
769/// corresponds to the number of nodes that are covered.
770unsigned PatternToMatch::
771getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
772 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
773}
774
775
Dan Gohman22bb3112008-08-22 00:20:26 +0000776/// getPredicateCheck - Return a single string containing all of this
777/// pattern's predicates concatenated with "&&" operators.
778///
779std::string PatternToMatch::getPredicateCheck() const {
780 std::string PredicateCheck;
781 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
Sean Silva6cfc8062012-10-10 20:24:43 +0000782 if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
Dan Gohman22bb3112008-08-22 00:20:26 +0000783 Record *Def = Pred->getDef();
784 if (!Def->isSubClassOf("Predicate")) {
785#ifndef NDEBUG
786 Def->dump();
787#endif
Craig Topper655b8de2012-02-05 07:21:30 +0000788 llvm_unreachable("Unknown predicate type!");
Dan Gohman22bb3112008-08-22 00:20:26 +0000789 }
790 if (!PredicateCheck.empty())
791 PredicateCheck += " && ";
792 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
793 }
794 }
795
796 return PredicateCheck;
797}
798
799//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000800// SDTypeConstraint implementation
801//
802
803SDTypeConstraint::SDTypeConstraint(Record *R) {
804 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000805
Chris Lattner6cefb772008-01-05 22:25:12 +0000806 if (R->isSubClassOf("SDTCisVT")) {
807 ConstraintType = SDTCisVT;
808 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerc8122612010-03-28 06:04:39 +0000809 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000810 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000811
Chris Lattner6cefb772008-01-05 22:25:12 +0000812 } else if (R->isSubClassOf("SDTCisPtrTy")) {
813 ConstraintType = SDTCisPtrTy;
814 } else if (R->isSubClassOf("SDTCisInt")) {
815 ConstraintType = SDTCisInt;
816 } else if (R->isSubClassOf("SDTCisFP")) {
817 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000818 } else if (R->isSubClassOf("SDTCisVec")) {
819 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000820 } else if (R->isSubClassOf("SDTCisSameAs")) {
821 ConstraintType = SDTCisSameAs;
822 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
823 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
824 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000825 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000826 R->getValueAsInt("OtherOperandNum");
827 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
828 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000829 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +0000830 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000831 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
832 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +0000833 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene60322692011-01-24 20:53:18 +0000834 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
835 ConstraintType = SDTCisSubVecOfVec;
836 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
837 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000838 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000839 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000840 exit(1);
841 }
842}
843
844/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +0000845/// N, and the result number in ResNo.
846static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
847 const SDNodeInfo &NodeInfo,
848 unsigned &ResNo) {
849 unsigned NumResults = NodeInfo.getNumResults();
850 if (OpNo < NumResults) {
851 ResNo = OpNo;
852 return N;
853 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000854
Chris Lattner2e68a022010-03-19 21:56:21 +0000855 OpNo -= NumResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000856
Chris Lattner2e68a022010-03-19 21:56:21 +0000857 if (OpNo >= N->getNumChildren()) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000858 errs() << "Invalid operand number in type constraint "
Chris Lattner2e68a022010-03-19 21:56:21 +0000859 << (OpNo+NumResults) << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000860 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000861 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000862 exit(1);
863 }
864
Chris Lattner2e68a022010-03-19 21:56:21 +0000865 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +0000866}
867
868/// ApplyTypeConstraint - Given a node in a pattern, apply this type
869/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000870/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner6cefb772008-01-05 22:25:12 +0000871bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
872 const SDNodeInfo &NodeInfo,
873 TreePattern &TP) const {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000874 if (TP.hasError())
875 return false;
876
Chris Lattner2e68a022010-03-19 21:56:21 +0000877 unsigned ResNo = 0; // The result number being referenced.
878 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000879
Chris Lattner6cefb772008-01-05 22:25:12 +0000880 switch (ConstraintType) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000881 case SDTCisVT:
882 // Operand must be a particular type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000883 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000884 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +0000885 // Operand must be same as target pointer type.
Chris Lattnerd7349192010-03-19 21:37:09 +0000886 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000887 case SDTCisInt:
888 // Require it to be one of the legal integer VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000889 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000890 case SDTCisFP:
891 // Require it to be one of the legal fp VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000892 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattner2cacec52010-03-15 06:00:16 +0000893 case SDTCisVec:
894 // Require it to be one of the legal vector VTs.
Chris Lattnerd7349192010-03-19 21:37:09 +0000895 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000896 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000897 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000898 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000899 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000900 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
901 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000902 }
903 case SDTCisVTSmallerThanOp: {
904 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
905 // have an integer type that is smaller than the VT.
906 if (!NodeToApply->isLeaf() ||
Sean Silva3f7b7f82012-10-10 20:24:47 +0000907 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greene05bce0b2011-07-29 22:43:06 +0000908 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000909 ->isSubClassOf("ValueType")) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000910 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000911 return false;
912 }
Owen Anderson825b72b2009-08-11 20:47:22 +0000913 MVT::SimpleValueType VT =
David Greene05bce0b2011-07-29 22:43:06 +0000914 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000915
Chris Lattnercc878302010-03-24 00:06:46 +0000916 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000917
Chris Lattner2e68a022010-03-19 21:56:21 +0000918 unsigned OResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000919 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +0000920 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
921 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +0000922
Chris Lattnercc878302010-03-24 00:06:46 +0000923 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000924 }
925 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000926 unsigned BResNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000927 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000928 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
929 BResNo);
Chris Lattnerd7349192010-03-19 21:37:09 +0000930 return NodeToApply->getExtType(ResNo).
931 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000932 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000933 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +0000934 unsigned VResNo = 0;
Chris Lattner2cacec52010-03-15 06:00:16 +0000935 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +0000936 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
937 VResNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000938
Chris Lattner66fb9d22010-03-24 00:01:16 +0000939 // Filter vector types out of VecOperand that don't have the right element
940 // type.
941 return VecOperand->getExtType(VResNo).
942 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000943 }
David Greene60322692011-01-24 20:53:18 +0000944 case SDTCisSubVecOfVec: {
945 unsigned VResNo = 0;
946 TreePatternNode *BigVecOperand =
947 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
948 VResNo);
949
950 // Filter vector types out of BigVecOperand that don't have the
951 // right subvector type.
952 return BigVecOperand->getExtType(VResNo).
953 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
954 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000955 }
David Blaikie58bd1512012-01-17 07:00:13 +0000956 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner6cefb772008-01-05 22:25:12 +0000957}
958
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +0000959// Update the node type to match an instruction operand or result as specified
960// in the ins or outs lists on the instruction definition. Return true if the
961// type was actually changed.
962bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
963 Record *Operand,
964 TreePattern &TP) {
965 // The 'unknown' operand indicates that types should be inferred from the
966 // context.
967 if (Operand->isSubClassOf("unknown_class"))
968 return false;
969
970 // The Operand class specifies a type directly.
971 if (Operand->isSubClassOf("Operand"))
972 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
973 TP);
974
975 // PointerLikeRegClass has a type that is determined at runtime.
976 if (Operand->isSubClassOf("PointerLikeRegClass"))
977 return UpdateNodeType(ResNo, MVT::iPTR, TP);
978
979 // Both RegisterClass and RegisterOperand operands derive their types from a
980 // register class def.
981 Record *RC = 0;
982 if (Operand->isSubClassOf("RegisterClass"))
983 RC = Operand;
984 else if (Operand->isSubClassOf("RegisterOperand"))
985 RC = Operand->getValueAsDef("RegClass");
986
987 assert(RC && "Unknown operand type");
988 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
989 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
990}
991
992
Chris Lattner6cefb772008-01-05 22:25:12 +0000993//===----------------------------------------------------------------------===//
994// SDNodeInfo implementation
995//
996SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
997 EnumName = R->getValueAsString("Opcode");
998 SDClassName = R->getValueAsString("SDClass");
999 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1000 NumResults = TypeProfile->getValueAsInt("NumResults");
1001 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001002
Chris Lattner6cefb772008-01-05 22:25:12 +00001003 // Parse the properties.
1004 Properties = 0;
1005 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1006 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1007 if (PropList[i]->getName() == "SDNPCommutative") {
1008 Properties |= 1 << SDNPCommutative;
1009 } else if (PropList[i]->getName() == "SDNPAssociative") {
1010 Properties |= 1 << SDNPAssociative;
1011 } else if (PropList[i]->getName() == "SDNPHasChain") {
1012 Properties |= 1 << SDNPHasChain;
Chris Lattner036609b2010-12-23 18:28:41 +00001013 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1014 Properties |= 1 << SDNPOutGlue;
1015 } else if (PropList[i]->getName() == "SDNPInGlue") {
1016 Properties |= 1 << SDNPInGlue;
1017 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1018 Properties |= 1 << SDNPOptInGlue;
Chris Lattnerc8478d82008-01-06 06:44:58 +00001019 } else if (PropList[i]->getName() == "SDNPMayStore") {
1020 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +00001021 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1022 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +00001023 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1024 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +00001025 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1026 Properties |= 1 << SDNPMemOperand;
Chris Lattnere8cabf32010-03-19 05:07:09 +00001027 } else if (PropList[i]->getName() == "SDNPVariadic") {
1028 Properties |= 1 << SDNPVariadic;
Chris Lattner6cefb772008-01-05 22:25:12 +00001029 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001030 errs() << "Unknown SD Node property '" << PropList[i]->getName()
1031 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001032 exit(1);
1033 }
1034 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001035
1036
Chris Lattner6cefb772008-01-05 22:25:12 +00001037 // Parse the type constraints.
1038 std::vector<Record*> ConstraintList =
1039 TypeProfile->getValueAsListOfDefs("Constraints");
1040 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1041}
1042
Chris Lattner22579812010-02-28 00:22:30 +00001043/// getKnownType - If the type constraints on this node imply a fixed type
1044/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +00001045/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +00001046MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +00001047 unsigned NumResults = getNumResults();
1048 assert(NumResults <= 1 &&
1049 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +00001050 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001051
Chris Lattner22579812010-02-28 00:22:30 +00001052 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1053 // Make sure that this applies to the correct node result.
1054 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1055 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001056
Chris Lattner22579812010-02-28 00:22:30 +00001057 switch (TypeConstraints[i].ConstraintType) {
1058 default: break;
1059 case SDTypeConstraint::SDTCisVT:
1060 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1061 case SDTypeConstraint::SDTCisPtrTy:
1062 return MVT::iPTR;
1063 }
1064 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +00001065 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +00001066}
1067
Chris Lattner6cefb772008-01-05 22:25:12 +00001068//===----------------------------------------------------------------------===//
1069// TreePatternNode implementation
1070//
1071
1072TreePatternNode::~TreePatternNode() {
1073#if 0 // FIXME: implement refcounted tree nodes!
1074 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1075 delete getChild(i);
1076#endif
1077}
1078
Chris Lattnerd7349192010-03-19 21:37:09 +00001079static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1080 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +00001081 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +00001082 return 0; // All return nothing.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001083
Chris Lattner93dc92e2010-03-22 20:56:36 +00001084 if (Operator->isSubClassOf("Intrinsic"))
1085 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001086
Chris Lattnerd7349192010-03-19 21:37:09 +00001087 if (Operator->isSubClassOf("SDNode"))
1088 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001089
Chris Lattnerd7349192010-03-19 21:37:09 +00001090 if (Operator->isSubClassOf("PatFrag")) {
1091 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1092 // the forward reference case where one pattern fragment references another
1093 // before it is processed.
1094 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1095 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001096
Chris Lattnerd7349192010-03-19 21:37:09 +00001097 // Get the result tree.
David Greene05bce0b2011-07-29 22:43:06 +00001098 DagInit *Tree = Operator->getValueAsDag("Fragment");
Chris Lattnerd7349192010-03-19 21:37:09 +00001099 Record *Op = 0;
Sean Silva3f7b7f82012-10-10 20:24:47 +00001100 if (Tree)
1101 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1102 Op = DI->getDef();
Chris Lattnerd7349192010-03-19 21:37:09 +00001103 assert(Op && "Invalid Fragment");
1104 return GetNumNodeResults(Op, CDP);
1105 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001106
Chris Lattnerd7349192010-03-19 21:37:09 +00001107 if (Operator->isSubClassOf("Instruction")) {
1108 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001109
1110 // FIXME: Should allow access to all the results here.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001111 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001112
Chris Lattner9414ae52010-03-27 20:09:24 +00001113 // Add on one implicit def if it has a resolvable type.
1114 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1115 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001116 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +00001117 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001118
Chris Lattnerd7349192010-03-19 21:37:09 +00001119 if (Operator->isSubClassOf("SDNodeXForm"))
1120 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001121
Chris Lattnerd7349192010-03-19 21:37:09 +00001122 Operator->dump();
1123 errs() << "Unhandled node in GetNumNodeResults\n";
1124 exit(1);
1125}
1126
1127void TreePatternNode::print(raw_ostream &OS) const {
1128 if (isLeaf())
1129 OS << *getLeafValue();
1130 else
1131 OS << '(' << getOperator()->getName();
1132
1133 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1134 OS << ':' << getExtType(i).getName();
Chris Lattner6cefb772008-01-05 22:25:12 +00001135
1136 if (!isLeaf()) {
1137 if (getNumChildren() != 0) {
1138 OS << " ";
1139 getChild(0)->print(OS);
1140 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1141 OS << ", ";
1142 getChild(i)->print(OS);
1143 }
1144 }
1145 OS << ")";
1146 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001147
Dan Gohman0540e172008-10-15 06:17:21 +00001148 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner54379062011-04-17 21:38:24 +00001149 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +00001150 if (TransformFn)
1151 OS << "<<X:" << TransformFn->getName() << ">>";
1152 if (!getName().empty())
1153 OS << ":$" << getName();
1154
1155}
1156void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001157 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +00001158}
1159
Scott Michel327d0652008-03-05 17:49:05 +00001160/// isIsomorphicTo - Return true if this node is recursively
1161/// isomorphic to the specified node. For this comparison, the node's
1162/// entire state is considered. The assigned name is ignored, since
1163/// nodes with differing names are considered isomorphic. However, if
1164/// the assigned name is present in the dependent variable set, then
1165/// the assigned name is considered significant and the node is
1166/// isomorphic if the names match.
1167bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1168 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001169 if (N == this) return true;
Chris Lattnerd7349192010-03-19 21:37:09 +00001170 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +00001171 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00001172 getTransformFn() != N->getTransformFn())
1173 return false;
1174
1175 if (isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00001176 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1177 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +00001178 return ((DI->getDef() == NDI->getDef())
1179 && (DepVars.find(getName()) == DepVars.end()
1180 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +00001181 }
1182 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001183 return getLeafValue() == N->getLeafValue();
1184 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001185
Chris Lattner6cefb772008-01-05 22:25:12 +00001186 if (N->getOperator() != getOperator() ||
1187 N->getNumChildren() != getNumChildren()) return false;
1188 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00001189 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +00001190 return false;
1191 return true;
1192}
1193
1194/// clone - Make a copy of this tree and all of its children.
1195///
1196TreePatternNode *TreePatternNode::clone() const {
1197 TreePatternNode *New;
1198 if (isLeaf()) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001199 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001200 } else {
1201 std::vector<TreePatternNode*> CChildren;
1202 CChildren.reserve(Children.size());
1203 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1204 CChildren.push_back(getChild(i)->clone());
Chris Lattnerd7349192010-03-19 21:37:09 +00001205 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001206 }
1207 New->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001208 New->Types = Types;
Dan Gohman0540e172008-10-15 06:17:21 +00001209 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00001210 New->setTransformFn(getTransformFn());
1211 return New;
1212}
1213
Chris Lattner47661322010-02-14 22:22:58 +00001214/// RemoveAllTypes - Recursively strip all the types of this tree.
1215void TreePatternNode::RemoveAllTypes() {
Chris Lattnerd7349192010-03-19 21:37:09 +00001216 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1217 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner47661322010-02-14 22:22:58 +00001218 if (isLeaf()) return;
1219 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1220 getChild(i)->RemoveAllTypes();
1221}
1222
1223
Chris Lattner6cefb772008-01-05 22:25:12 +00001224/// SubstituteFormalArguments - Replace the formal arguments in this tree
1225/// with actual values specified by ArgMap.
1226void TreePatternNode::
1227SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1228 if (isLeaf()) return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001229
Chris Lattner6cefb772008-01-05 22:25:12 +00001230 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1231 TreePatternNode *Child = getChild(i);
1232 if (Child->isLeaf()) {
David Greene05bce0b2011-07-29 22:43:06 +00001233 Init *Val = Child->getLeafValue();
Sean Silva3f7b7f82012-10-10 20:24:47 +00001234 if (isa<DefInit>(Val) &&
1235 cast<DefInit>(Val)->getDef()->getName() == "node") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001236 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +00001237 TreePatternNode *NewChild = ArgMap[Child->getName()];
1238 assert(NewChild && "Couldn't find formal argument!");
1239 assert((Child->getPredicateFns().empty() ||
1240 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1241 "Non-empty child predicate clobbered!");
1242 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +00001243 }
1244 } else {
1245 getChild(i)->SubstituteFormalArguments(ArgMap);
1246 }
1247 }
1248}
1249
1250
1251/// InlinePatternFragments - If this pattern refers to any pattern
1252/// fragments, inline them into place, giving us a pattern without any
1253/// PatFrag references.
1254TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001255 if (TP.hasError())
Kaelyn Uhrain50a61022012-10-25 21:25:08 +00001256 return 0;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001257
1258 if (isLeaf())
1259 return this; // nothing to do.
Chris Lattner6cefb772008-01-05 22:25:12 +00001260 Record *Op = getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001261
Chris Lattner6cefb772008-01-05 22:25:12 +00001262 if (!Op->isSubClassOf("PatFrag")) {
1263 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00001264 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1265 TreePatternNode *Child = getChild(i);
1266 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1267
1268 assert((Child->getPredicateFns().empty() ||
1269 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1270 "Non-empty child predicate clobbered!");
1271
1272 setChild(i, NewChild);
1273 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001274 return this;
1275 }
1276
1277 // Otherwise, we found a reference to a fragment. First, look up its
1278 // TreePattern record.
1279 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001280
Chris Lattner6cefb772008-01-05 22:25:12 +00001281 // Verify that we are passing the right number of operands.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001282 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001283 TP.error("'" + Op->getName() + "' fragment requires " +
1284 utostr(Frag->getNumArgs()) + " operands!");
Kaelyn Uhrain50a61022012-10-25 21:25:08 +00001285 return 0;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001286 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001287
1288 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1289
Chris Lattner54379062011-04-17 21:38:24 +00001290 TreePredicateFn PredFn(Frag);
1291 if (!PredFn.isAlwaysTrue())
1292 FragTree->addPredicateFn(PredFn);
Dan Gohman0540e172008-10-15 06:17:21 +00001293
Chris Lattner6cefb772008-01-05 22:25:12 +00001294 // Resolve formal arguments to their actual value.
1295 if (Frag->getNumArgs()) {
1296 // Compute the map of formal to actual arguments.
1297 std::map<std::string, TreePatternNode*> ArgMap;
1298 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1299 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001300
Chris Lattner6cefb772008-01-05 22:25:12 +00001301 FragTree->SubstituteFormalArguments(ArgMap);
1302 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001303
Chris Lattner6cefb772008-01-05 22:25:12 +00001304 FragTree->setName(getName());
Chris Lattnerd7349192010-03-19 21:37:09 +00001305 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1306 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman0540e172008-10-15 06:17:21 +00001307
1308 // Transfer in the old predicates.
1309 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1310 FragTree->addPredicateFn(getPredicateFns()[i]);
1311
Chris Lattner6cefb772008-01-05 22:25:12 +00001312 // Get a new copy of this fragment to stitch into here.
1313 //delete this; // FIXME: implement refcounting!
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001314
Chris Lattner2ca698d2008-06-30 03:02:03 +00001315 // The fragment we inlined could have recursive inlining that is needed. See
1316 // if there are any pattern fragments in it and inline them as needed.
1317 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001318}
1319
1320/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +00001321/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +00001322/// references from the register file information, for example.
1323///
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00001324/// When Unnamed is set, return the type of a DAG operand with no name, such as
1325/// the F8RC register class argument in:
1326///
1327/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1328///
1329/// When Unnamed is false, return the type of a named DAG operand such as the
1330/// GPR:$src operand above.
1331///
Chris Lattnerd7349192010-03-19 21:37:09 +00001332static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00001333 bool NotRegisters,
1334 bool Unnamed,
1335 TreePattern &TP) {
Owen Andersonbea6f612011-06-27 21:06:21 +00001336 // Check to see if this is a register operand.
1337 if (R->isSubClassOf("RegisterOperand")) {
1338 assert(ResNo == 0 && "Regoperand ref only has one result!");
1339 if (NotRegisters)
1340 return EEVT::TypeSet(); // Unknown.
1341 Record *RegClass = R->getValueAsDef("RegClass");
1342 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1343 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1344 }
1345
Chris Lattner2cacec52010-03-15 06:00:16 +00001346 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00001347 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00001348 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00001349 // An unnamed register class represents itself as an i32 immediate, for
1350 // example on a COPY_TO_REGCLASS instruction.
1351 if (Unnamed)
1352 return EEVT::TypeSet(MVT::i32, TP);
1353
1354 // In a named operand, the register class provides the possible set of
1355 // types.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001356 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001357 return EEVT::TypeSet(); // Unknown.
1358 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1359 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00001360 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001361
Chris Lattner640a3f52010-03-23 23:50:31 +00001362 if (R->isSubClassOf("PatFrag")) {
1363 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001364 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner2cacec52010-03-15 06:00:16 +00001365 return EEVT::TypeSet(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00001366 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001367
Chris Lattner640a3f52010-03-23 23:50:31 +00001368 if (R->isSubClassOf("Register")) {
1369 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001370 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001371 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001372 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattner2cacec52010-03-15 06:00:16 +00001373 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00001374 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00001375
1376 if (R->isSubClassOf("SubRegIndex")) {
1377 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1378 return EEVT::TypeSet();
1379 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001380
Chris Lattner640a3f52010-03-23 23:50:31 +00001381 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1382 assert(ResNo == 0 && "This node only has one result!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001383 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner2cacec52010-03-15 06:00:16 +00001384 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001385 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001386
Chris Lattner640a3f52010-03-23 23:50:31 +00001387 if (R->isSubClassOf("ComplexPattern")) {
1388 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001389 if (NotRegisters)
Chris Lattner2cacec52010-03-15 06:00:16 +00001390 return EEVT::TypeSet(); // Unknown.
1391 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1392 TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001393 }
1394 if (R->isSubClassOf("PointerLikeRegClass")) {
1395 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00001396 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner640a3f52010-03-23 23:50:31 +00001397 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001398
Chris Lattner640a3f52010-03-23 23:50:31 +00001399 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1400 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001401 // Placeholder.
Chris Lattner2cacec52010-03-15 06:00:16 +00001402 return EEVT::TypeSet(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00001403 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001404
Chris Lattner6cefb772008-01-05 22:25:12 +00001405 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner2cacec52010-03-15 06:00:16 +00001406 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001407}
1408
Chris Lattnere67bde52008-01-06 05:36:50 +00001409
1410/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1411/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1412const CodeGenIntrinsic *TreePatternNode::
1413getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1414 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1415 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1416 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1417 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001418
Sean Silva3f7b7f82012-10-10 20:24:47 +00001419 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattnere67bde52008-01-06 05:36:50 +00001420 return &CDP.getIntrinsicInfo(IID);
1421}
1422
Chris Lattner47661322010-02-14 22:22:58 +00001423/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1424/// return the ComplexPattern information, otherwise return null.
1425const ComplexPattern *
1426TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1427 if (!isLeaf()) return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001428
Sean Silva6cfc8062012-10-10 20:24:43 +00001429 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
Chris Lattner47661322010-02-14 22:22:58 +00001430 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1431 return &CGP.getComplexPattern(DI->getDef());
1432 return 0;
1433}
1434
1435/// NodeHasProperty - Return true if this node has the specified property.
1436bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001437 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001438 if (isLeaf()) {
1439 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1440 return CP->hasProperty(Property);
1441 return false;
1442 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001443
Chris Lattner47661322010-02-14 22:22:58 +00001444 Record *Operator = getOperator();
1445 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001446
Chris Lattner47661322010-02-14 22:22:58 +00001447 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1448}
1449
1450
1451
1452
1453/// TreeHasProperty - Return true if any node in this tree has the specified
1454/// property.
1455bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00001456 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00001457 if (NodeHasProperty(Property, CGP))
1458 return true;
1459 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1460 if (getChild(i)->TreeHasProperty(Property, CGP))
1461 return true;
1462 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001463}
Chris Lattner47661322010-02-14 22:22:58 +00001464
Evan Cheng6bd95672008-06-16 20:29:38 +00001465/// isCommutativeIntrinsic - Return true if the node corresponds to a
1466/// commutative intrinsic.
1467bool
1468TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1469 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1470 return Int->isCommutative;
1471 return false;
1472}
1473
Chris Lattnere67bde52008-01-06 05:36:50 +00001474
Bob Wilson6c01ca92009-01-05 17:23:09 +00001475/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00001476/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001477/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner6cefb772008-01-05 22:25:12 +00001478bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001479 if (TP.hasError())
1480 return false;
1481
Chris Lattnerfe718932008-01-06 01:10:31 +00001482 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001483 if (isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00001484 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001485 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00001486 bool MadeChange = false;
1487 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1488 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00001489 NotRegisters,
1490 !hasName(), TP), TP);
Chris Lattnerd7349192010-03-19 21:37:09 +00001491 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00001492 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001493
Sean Silva6cfc8062012-10-10 20:24:43 +00001494 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001495 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001496
Chris Lattnerd7349192010-03-19 21:37:09 +00001497 // Int inits are always integers. :)
1498 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001499
Chris Lattnerd7349192010-03-19 21:37:09 +00001500 if (!Types[0].isConcrete())
Chris Lattner2cacec52010-03-15 06:00:16 +00001501 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001502
Chris Lattnerd7349192010-03-19 21:37:09 +00001503 MVT::SimpleValueType VT = getType(0);
Chris Lattner2cacec52010-03-15 06:00:16 +00001504 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1505 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001506
Chris Lattner2cacec52010-03-15 06:00:16 +00001507 unsigned Size = EVT(VT).getSizeInBits();
1508 // Make sure that the value is representable for this type.
1509 if (Size >= 32) return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001510
Richard Smith1144af32012-08-24 23:29:28 +00001511 // Check that the value doesn't use more bits than we have. It must either
1512 // be a sign- or zero-extended equivalent of the original.
1513 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1514 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattner2cacec52010-03-15 06:00:16 +00001515 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001516
Richard Smith1144af32012-08-24 23:29:28 +00001517 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerd7349192010-03-19 21:37:09 +00001518 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001519 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +00001520 }
1521 return false;
1522 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001523
Chris Lattner6cefb772008-01-05 22:25:12 +00001524 // special handling for set, which isn't really an SDNode.
1525 if (getOperator()->getName() == "set") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001526 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1527 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner6cefb772008-01-05 22:25:12 +00001528 unsigned NC = getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001529
Chris Lattnerd7349192010-03-19 21:37:09 +00001530 TreePatternNode *SetVal = getChild(NC-1);
1531 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1532
Chris Lattner6cefb772008-01-05 22:25:12 +00001533 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001534 TreePatternNode *Child = getChild(i);
1535 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001536
Chris Lattner6cefb772008-01-05 22:25:12 +00001537 // Types of operands must match.
Chris Lattnerd7349192010-03-19 21:37:09 +00001538 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1539 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001540 }
1541 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001542 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001543
Chris Lattner310adf12010-03-27 02:53:27 +00001544 if (getOperator()->getName() == "implicit") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001545 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1546
Chris Lattner6cefb772008-01-05 22:25:12 +00001547 bool MadeChange = false;
1548 for (unsigned i = 0; i < getNumChildren(); ++i)
1549 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001550 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001551 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001552
Chris Lattner6eb30122010-02-23 05:51:07 +00001553 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001554 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001555
Chris Lattner6cefb772008-01-05 22:25:12 +00001556 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001557 unsigned NumRetVTs = Int->IS.RetVTs.size();
1558 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001559
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001560 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00001561 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001562
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001563 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattnere67bde52008-01-06 05:36:50 +00001564 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerd7349192010-03-19 21:37:09 +00001565 utostr(NumParamVTs) + " operands, not " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001566 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001567 return false;
1568 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001569
1570 // Apply type info to the intrinsic ID.
Chris Lattnerd7349192010-03-19 21:37:09 +00001571 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001572
Chris Lattnerd7349192010-03-19 21:37:09 +00001573 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1574 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001575
Chris Lattnerd7349192010-03-19 21:37:09 +00001576 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1577 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1578 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001579 }
1580 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001581 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001582
Chris Lattner6eb30122010-02-23 05:51:07 +00001583 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001584 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001585
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001586 // Check that the number of operands is sane. Negative operands -> varargs.
1587 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001588 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001589 TP.error(getOperator()->getName() + " node requires exactly " +
1590 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001591 return false;
1592 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001593
Chris Lattner6cefb772008-01-05 22:25:12 +00001594 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1595 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1596 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerd7349192010-03-19 21:37:09 +00001597 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001598 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001599
Chris Lattner6eb30122010-02-23 05:51:07 +00001600 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001601 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001602 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00001603 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001604
Chris Lattner0be6fe72010-03-27 19:15:02 +00001605 bool MadeChange = false;
1606
1607 // Apply the result types to the node, these come from the things in the
1608 // (outs) list of the instruction.
1609 // FIXME: Cap at one result so far.
Chris Lattnerc240bb02010-11-01 04:03:32 +00001610 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +00001611 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1612 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001613
Chris Lattner0be6fe72010-03-27 19:15:02 +00001614 // If the instruction has implicit defs, we apply the first one as a result.
1615 // FIXME: This sucks, it should apply all implicit defs.
1616 if (!InstInfo.ImplicitDefs.empty()) {
1617 unsigned ResNo = NumResultsToAdd;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001618
Chris Lattner9414ae52010-03-27 20:09:24 +00001619 // FIXME: Generalize to multiple possible types and multiple possible
1620 // ImplicitDefs.
1621 MVT::SimpleValueType VT =
1622 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001623
Chris Lattner9414ae52010-03-27 20:09:24 +00001624 if (VT != MVT::Other)
1625 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001626 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001627
Chris Lattner2cacec52010-03-15 06:00:16 +00001628 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1629 // be the same.
1630 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerd7349192010-03-19 21:37:09 +00001631 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1632 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1633 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001634 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001635
1636 unsigned ChildNo = 0;
1637 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1638 Record *OperandNode = Inst.getOperand(i);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001639
Chris Lattner6cefb772008-01-05 22:25:12 +00001640 // If the instruction expects a predicate or optional def operand, we
1641 // codegen this by setting the operand to it's default value if it has a
1642 // non-empty DefaultOps field.
Tom Stellard6d3d7652012-09-06 14:15:52 +00001643 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001644 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1645 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001646
Chris Lattner6cefb772008-01-05 22:25:12 +00001647 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001648 if (ChildNo >= getNumChildren()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001649 TP.error("Instruction '" + getOperator()->getName() +
1650 "' expects more operands than were provided.");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001651 return false;
1652 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001653
Chris Lattner6cefb772008-01-05 22:25:12 +00001654 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001655 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigandec8d1a52013-03-19 19:51:09 +00001656
1657 // If the operand has sub-operands, they may be provided by distinct
1658 // child patterns, so attempt to match each sub-operand separately.
1659 if (OperandNode->isSubClassOf("Operand")) {
1660 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1661 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1662 // But don't do that if the whole operand is being provided by
1663 // a single ComplexPattern.
1664 const ComplexPattern *AM = Child->getComplexPatternInfo(CDP);
1665 if (!AM || AM->getNumOperands() < NumArgs) {
1666 // Match first sub-operand against the child we already have.
1667 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1668 MadeChange |=
1669 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1670
1671 // And the remaining sub-operands against subsequent children.
1672 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1673 if (ChildNo >= getNumChildren()) {
1674 TP.error("Instruction '" + getOperator()->getName() +
1675 "' expects more operands than were provided.");
1676 return false;
1677 }
1678 Child = getChild(ChildNo++);
1679
1680 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1681 MadeChange |=
1682 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1683 }
1684 continue;
1685 }
1686 }
1687 }
1688
1689 // If we didn't match by pieces above, attempt to match the whole
1690 // operand now.
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +00001691 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001692 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001693
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001694 if (ChildNo != getNumChildren()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001695 TP.error("Instruction '" + getOperator()->getName() +
1696 "' was provided too many operands!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001697 return false;
1698 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001699
Ulrich Weigandec8d1a52013-03-19 19:51:09 +00001700 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1701 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00001702 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001703 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001704
Chris Lattner6eb30122010-02-23 05:51:07 +00001705 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001706
Chris Lattner6eb30122010-02-23 05:51:07 +00001707 // Node transforms always take one operand.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001708 if (getNumChildren() != 1) {
Chris Lattner6eb30122010-02-23 05:51:07 +00001709 TP.error("Node transform '" + getOperator()->getName() +
1710 "' requires one operand!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001711 return false;
1712 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001713
Chris Lattner2cacec52010-03-15 06:00:16 +00001714 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1715
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001716
Chris Lattner6eb30122010-02-23 05:51:07 +00001717 // If either the output or input of the xform does not have exact
1718 // type info. We assume they must be the same. Otherwise, it is perfectly
1719 // legal to transform from one type to a completely different type.
Chris Lattner2cacec52010-03-15 06:00:16 +00001720#if 0
Chris Lattner6eb30122010-02-23 05:51:07 +00001721 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001722 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1723 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattner6eb30122010-02-23 05:51:07 +00001724 return MadeChange;
1725 }
Chris Lattner2cacec52010-03-15 06:00:16 +00001726#endif
1727 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001728}
1729
1730/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1731/// RHS of a commutative operation, not the on LHS.
1732static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1733 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1734 return true;
Sean Silva3f7b7f82012-10-10 20:24:47 +00001735 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner6cefb772008-01-05 22:25:12 +00001736 return true;
1737 return false;
1738}
1739
1740
1741/// canPatternMatch - If it is impossible for this pattern to match on this
1742/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001743/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001744/// that can never possibly work), and to prevent the pattern permuter from
1745/// generating stuff that is useless.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001746bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001747 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001748 if (isLeaf()) return true;
1749
1750 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1751 if (!getChild(i)->canPatternMatch(Reason, CDP))
1752 return false;
1753
1754 // If this is an intrinsic, handle cases that would make it not match. For
1755 // example, if an operand is required to be an immediate.
1756 if (getOperator()->isSubClassOf("Intrinsic")) {
1757 // TODO:
1758 return true;
1759 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001760
Chris Lattner6cefb772008-01-05 22:25:12 +00001761 // If this node is a commutative operator, check that the LHS isn't an
1762 // immediate.
1763 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001764 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1765 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001766 // Scan all of the operands of the node and make sure that only the last one
1767 // is a constant node, unless the RHS also is.
1768 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001769 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1770 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001771 if (OnlyOnRHSOfCommutative(getChild(i))) {
1772 Reason="Immediate value must be on the RHS of commutative operators!";
1773 return false;
1774 }
1775 }
1776 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001777
Chris Lattner6cefb772008-01-05 22:25:12 +00001778 return true;
1779}
1780
1781//===----------------------------------------------------------------------===//
1782// TreePattern implementation
1783//
1784
David Greene05bce0b2011-07-29 22:43:06 +00001785TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001786 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1787 isInputPattern(isInput), HasError(false) {
Chris Lattner2cacec52010-03-15 06:00:16 +00001788 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattnerc2173052010-03-28 06:50:34 +00001789 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001790}
1791
David Greene05bce0b2011-07-29 22:43:06 +00001792TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001793 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1794 isInputPattern(isInput), HasError(false) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001795 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00001796}
1797
1798TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001799 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1800 isInputPattern(isInput), HasError(false) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001801 Trees.push_back(Pat);
1802}
1803
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001804void TreePattern::error(const std::string &Msg) {
1805 if (HasError)
1806 return;
Chris Lattner6cefb772008-01-05 22:25:12 +00001807 dump();
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001808 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1809 HasError = true;
Chris Lattner6cefb772008-01-05 22:25:12 +00001810}
1811
Chris Lattner2cacec52010-03-15 06:00:16 +00001812void TreePattern::ComputeNamedNodes() {
1813 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1814 ComputeNamedNodes(Trees[i]);
1815}
1816
1817void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1818 if (!N->getName().empty())
1819 NamedNodes[N->getName()].push_back(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001820
Chris Lattner2cacec52010-03-15 06:00:16 +00001821 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1822 ComputeNamedNodes(N->getChild(i));
1823}
1824
Chris Lattnerd7349192010-03-19 21:37:09 +00001825
David Greene05bce0b2011-07-29 22:43:06 +00001826TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silva6cfc8062012-10-10 20:24:43 +00001827 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001828 Record *R = DI->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001829
Chris Lattnerc2173052010-03-28 06:50:34 +00001830 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbach66c9ee72011-07-06 23:38:13 +00001831 // TreePatternNode of its own. For example:
Chris Lattnerc2173052010-03-28 06:50:34 +00001832 /// (foo GPR, imm) -> (foo GPR, (imm))
1833 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenedcd35c72011-07-29 19:07:07 +00001834 return ParseTreePattern(
1835 DagInit::get(DI, "",
David Greene05bce0b2011-07-29 22:43:06 +00001836 std::vector<std::pair<Init*, std::string> >()),
David Greenedcd35c72011-07-29 19:07:07 +00001837 OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001838
Chris Lattnerc2173052010-03-28 06:50:34 +00001839 // Input argument?
1840 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner2a22cdc2010-03-28 08:48:47 +00001841 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001842 if (OpName.empty())
1843 error("'node' argument requires a name to match with operand list");
1844 Args.push_back(OpName);
1845 }
1846
1847 Res->setName(OpName);
1848 return Res;
1849 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001850
Sean Silva6cfc8062012-10-10 20:24:43 +00001851 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001852 if (!OpName.empty())
1853 error("Constant int argument should not have a name!");
1854 return new TreePatternNode(II, 1);
1855 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001856
Sean Silva6cfc8062012-10-10 20:24:43 +00001857 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00001858 // Turn this into an IntInit.
David Greene05bce0b2011-07-29 22:43:06 +00001859 Init *II = BI->convertInitializerTo(IntRecTy::get());
Sean Silva3f7b7f82012-10-10 20:24:47 +00001860 if (II == 0 || !isa<IntInit>(II))
Chris Lattnerc2173052010-03-28 06:50:34 +00001861 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001862 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00001863 }
1864
Sean Silva6cfc8062012-10-10 20:24:43 +00001865 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattnerc2173052010-03-28 06:50:34 +00001866 if (!Dag) {
1867 TheInit->dump();
1868 error("Pattern has unexpected init kind!");
1869 }
Sean Silva6cfc8062012-10-10 20:24:43 +00001870 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00001871 if (!OpDef) error("Pattern has unexpected operator type!");
1872 Record *Operator = OpDef->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001873
Chris Lattner6cefb772008-01-05 22:25:12 +00001874 if (Operator->isSubClassOf("ValueType")) {
1875 // If the operator is a ValueType, then this must be "type cast" of a leaf
1876 // node.
1877 if (Dag->getNumArgs() != 1)
1878 error("Type cast only takes one operand!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001879
Chris Lattnerc2173052010-03-28 06:50:34 +00001880 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001881
Chris Lattner6cefb772008-01-05 22:25:12 +00001882 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00001883 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1884 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001885
Chris Lattnerc2173052010-03-28 06:50:34 +00001886 if (!OpName.empty())
1887 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001888 return New;
1889 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001890
Chris Lattner6cefb772008-01-05 22:25:12 +00001891 // Verify that this is something that makes sense for an operator.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001892 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begeman7cee8172009-03-19 05:21:56 +00001893 !Operator->isSubClassOf("SDNode") &&
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001894 !Operator->isSubClassOf("Instruction") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001895 !Operator->isSubClassOf("SDNodeXForm") &&
1896 !Operator->isSubClassOf("Intrinsic") &&
1897 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00001898 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00001899 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001900
Chris Lattner6cefb772008-01-05 22:25:12 +00001901 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001902 if (isInputPattern) {
1903 if (Operator->isSubClassOf("Instruction") ||
1904 Operator->isSubClassOf("SDNodeXForm"))
1905 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1906 } else {
1907 if (Operator->isSubClassOf("Intrinsic"))
1908 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001909
Chris Lattnerb775b1e2010-03-28 06:57:56 +00001910 if (Operator->isSubClassOf("SDNode") &&
1911 Operator->getName() != "imm" &&
1912 Operator->getName() != "fpimm" &&
1913 Operator->getName() != "tglobaltlsaddr" &&
1914 Operator->getName() != "tconstpool" &&
1915 Operator->getName() != "tjumptable" &&
1916 Operator->getName() != "tframeindex" &&
1917 Operator->getName() != "texternalsym" &&
1918 Operator->getName() != "tblockaddress" &&
1919 Operator->getName() != "tglobaladdr" &&
1920 Operator->getName() != "bb" &&
1921 Operator->getName() != "vt")
1922 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1923 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001924
Chris Lattner6cefb772008-01-05 22:25:12 +00001925 std::vector<TreePatternNode*> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00001926
1927 // Parse all the operands.
1928 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1929 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001930
Chris Lattner6cefb772008-01-05 22:25:12 +00001931 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001932 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner6cefb772008-01-05 22:25:12 +00001933 // convert the intrinsic name to a number.
1934 if (Operator->isSubClassOf("Intrinsic")) {
1935 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1936 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1937
1938 // If this intrinsic returns void, it must have side-effects and thus a
1939 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00001940 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001941 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001942 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00001943 // Has side-effects, requires chain.
1944 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00001945 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00001946 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001947
David Greenedcd35c72011-07-29 19:07:07 +00001948 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner6cefb772008-01-05 22:25:12 +00001949 Children.insert(Children.begin(), IIDNode);
1950 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001951
Chris Lattnerd7349192010-03-19 21:37:09 +00001952 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1953 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00001954 Result->setName(OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001955
Chris Lattnerc2173052010-03-28 06:50:34 +00001956 if (!Dag->getName().empty()) {
1957 assert(Result->getName().empty());
1958 Result->setName(Dag->getName());
1959 }
Nate Begeman7cee8172009-03-19 05:21:56 +00001960 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001961}
1962
Chris Lattner7a0eb912010-03-28 08:38:32 +00001963/// SimplifyTree - See if we can simplify this tree to eliminate something that
1964/// will never match in favor of something obvious that will. This is here
1965/// strictly as a convenience to target authors because it allows them to write
1966/// more type generic things and have useless type casts fold away.
1967///
1968/// This returns true if any change is made.
1969static bool SimplifyTree(TreePatternNode *&N) {
1970 if (N->isLeaf())
1971 return false;
1972
1973 // If we have a bitconvert with a resolved type and if the source and
1974 // destination types are the same, then the bitconvert is useless, remove it.
1975 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattner7a0eb912010-03-28 08:38:32 +00001976 N->getExtType(0).isConcrete() &&
1977 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1978 N->getName().empty()) {
1979 N = N->getChild(0);
1980 SimplifyTree(N);
1981 return true;
1982 }
1983
1984 // Walk all children.
1985 bool MadeChange = false;
1986 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1987 TreePatternNode *Child = N->getChild(i);
1988 MadeChange |= SimplifyTree(Child);
1989 N->setChild(i, Child);
1990 }
1991 return MadeChange;
1992}
1993
1994
1995
Chris Lattner6cefb772008-01-05 22:25:12 +00001996/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001997/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001998/// otherwise. Flags an error if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00001999bool TreePattern::
2000InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2001 if (NamedNodes.empty())
2002 ComputeNamedNodes();
2003
Chris Lattner6cefb772008-01-05 22:25:12 +00002004 bool MadeChange = true;
2005 while (MadeChange) {
2006 MadeChange = false;
Chris Lattner7a0eb912010-03-28 08:38:32 +00002007 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002008 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner7a0eb912010-03-28 08:38:32 +00002009 MadeChange |= SimplifyTree(Trees[i]);
2010 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002011
2012 // If there are constraints on our named nodes, apply them.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002013 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattner2cacec52010-03-15 06:00:16 +00002014 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2015 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002016
Chris Lattner2cacec52010-03-15 06:00:16 +00002017 // If we have input named node types, propagate their types to the named
2018 // values here.
2019 if (InNamedTypes) {
2020 // FIXME: Should be error?
2021 assert(InNamedTypes->count(I->getKey()) &&
2022 "Named node in output pattern but not input pattern?");
2023
2024 const SmallVectorImpl<TreePatternNode*> &InNodes =
2025 InNamedTypes->find(I->getKey())->second;
2026
2027 // The input types should be fully resolved by now.
2028 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2029 // If this node is a register class, and it is the root of the pattern
2030 // then we're mapping something onto an input register. We allow
2031 // changing the type of the input register in this case. This allows
2032 // us to match things like:
2033 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2034 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002035 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00002036 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2037 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner2cacec52010-03-15 06:00:16 +00002038 continue;
2039 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002040
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00002041 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00002042 InNodes[0]->getNumTypes() == 1 &&
2043 "FIXME: cannot name multiple result nodes yet");
2044 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2045 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002046 }
2047 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002048
Chris Lattner2cacec52010-03-15 06:00:16 +00002049 // If there are multiple nodes with the same name, they must all have the
2050 // same type.
2051 if (I->second.size() > 1) {
2052 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002053 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00002054 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00002055 "FIXME: cannot name multiple result nodes yet");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002056
Chris Lattnerd7349192010-03-19 21:37:09 +00002057 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2058 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002059 }
2060 }
2061 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002062 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002063
Chris Lattner6cefb772008-01-05 22:25:12 +00002064 bool HasUnresolvedTypes = false;
2065 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2066 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2067 return !HasUnresolvedTypes;
2068}
2069
Daniel Dunbar1a551802009-07-03 00:10:29 +00002070void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00002071 OS << getRecord()->getName();
2072 if (!Args.empty()) {
2073 OS << "(" << Args[0];
2074 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2075 OS << ", " << Args[i];
2076 OS << ")";
2077 }
2078 OS << ": ";
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002079
Chris Lattner6cefb772008-01-05 22:25:12 +00002080 if (Trees.size() > 1)
2081 OS << "[\n";
2082 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2083 OS << "\t";
2084 Trees[i]->print(OS);
2085 OS << "\n";
2086 }
2087
2088 if (Trees.size() > 1)
2089 OS << "]\n";
2090}
2091
Daniel Dunbar1a551802009-07-03 00:10:29 +00002092void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00002093
2094//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00002095// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00002096//
2097
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002098CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner67db8832010-12-13 00:23:57 +00002099 Records(R), Target(R) {
2100
Dale Johannesen49de9822009-02-05 01:49:45 +00002101 Intrinsics = LoadIntrinsics(Records, false);
2102 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00002103 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00002104 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00002105 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002106 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00002107 ParseDefaultOperands();
2108 ParseInstructions();
2109 ParsePatterns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002110
Chris Lattner6cefb772008-01-05 22:25:12 +00002111 // Generate variants. For example, commutative patterns can match
2112 // multiple ways. Add them to PatternsToMatch as well.
2113 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00002114
2115 // Infer instruction flags. For example, we can detect loads,
2116 // stores, and side effects in many cases by examining an
2117 // instruction's pattern.
2118 InferInstructionFlags();
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00002119
2120 // Verify that instruction flags match the patterns.
2121 VerifyInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00002122}
2123
Chris Lattnerfe718932008-01-06 01:10:31 +00002124CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002125 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002126 E = PatternFragments.end(); I != E; ++I)
2127 delete I->second;
2128}
2129
2130
Chris Lattnerfe718932008-01-06 01:10:31 +00002131Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00002132 Record *N = Records.getDef(Name);
2133 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002134 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00002135 exit(1);
2136 }
2137 return N;
2138}
2139
2140// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00002141void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002142 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2143 while (!Nodes.empty()) {
2144 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2145 Nodes.pop_back();
2146 }
2147
Jim Grosbachda4231f2009-03-26 16:17:51 +00002148 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00002149 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2150 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2151 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2152}
2153
2154/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2155/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002156void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002157 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2158 while (!Xforms.empty()) {
2159 Record *XFormNode = Xforms.back();
2160 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +00002161 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00002162 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002163
2164 Xforms.pop_back();
2165 }
2166}
2167
Chris Lattnerfe718932008-01-06 01:10:31 +00002168void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002169 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2170 while (!AMs.empty()) {
2171 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2172 AMs.pop_back();
2173 }
2174}
2175
2176
2177/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2178/// file, building up the PatternFragments map. After we've collected them all,
2179/// inline fragments together as necessary, so that there are no references left
2180/// inside a pattern fragment to a pattern fragment.
2181///
Chris Lattnerfe718932008-01-06 01:10:31 +00002182void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002183 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002184
Chris Lattnerdc32f982008-01-05 22:43:57 +00002185 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002186 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00002187 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattner6cefb772008-01-05 22:25:12 +00002188 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2189 PatternFragments[Fragments[i]] = P;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002190
Chris Lattnerdc32f982008-01-05 22:43:57 +00002191 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00002192 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002193 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002194
Chris Lattnerdc32f982008-01-05 22:43:57 +00002195 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00002196 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002197
Chris Lattner6cefb772008-01-05 22:25:12 +00002198 // Parse the operands list.
David Greene05bce0b2011-07-29 22:43:06 +00002199 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Sean Silva6cfc8062012-10-10 20:24:43 +00002200 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00002201 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00002202 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00002203 if (!OpsOp ||
2204 (OpsOp->getDef()->getName() != "ops" &&
2205 OpsOp->getDef()->getName() != "outs" &&
2206 OpsOp->getDef()->getName() != "ins"))
2207 P->error("Operands list should start with '(ops ... '!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002208
2209 // Copy over the arguments.
Chris Lattner6cefb772008-01-05 22:25:12 +00002210 Args.clear();
2211 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva3f7b7f82012-10-10 20:24:47 +00002212 if (!isa<DefInit>(OpsList->getArg(j)) ||
2213 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner6cefb772008-01-05 22:25:12 +00002214 P->error("Operands list should all be 'node' values.");
2215 if (OpsList->getArgName(j).empty())
2216 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002217 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00002218 P->error("'" + OpsList->getArgName(j) +
2219 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00002220 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00002221 Args.push_back(OpsList->getArgName(j));
2222 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002223
Chris Lattnerdc32f982008-01-05 22:43:57 +00002224 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00002225 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00002226 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002227
Chris Lattnerdc32f982008-01-05 22:43:57 +00002228 // If there is a code init for this fragment, keep track of the fact that
2229 // this fragment uses it.
Chris Lattner54379062011-04-17 21:38:24 +00002230 TreePredicateFn PredFn(P);
2231 if (!PredFn.isAlwaysTrue())
2232 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002233
Chris Lattner6cefb772008-01-05 22:25:12 +00002234 // If there is a node transformation corresponding to this, keep track of
2235 // it.
2236 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2237 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2238 P->getOnlyTree()->setTransformFn(Transform);
2239 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002240
Chris Lattner6cefb772008-01-05 22:25:12 +00002241 // Now that we've parsed all of the tree fragments, do a closure on them so
2242 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00002243 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2244 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00002245 ThePat->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002246
Chris Lattner6cefb772008-01-05 22:25:12 +00002247 // Infer as many types as possible. Don't worry about it if we don't infer
2248 // all of them, some may depend on the inputs of the pattern.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002249 ThePat->InferAllTypes();
2250 ThePat->resetError();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002251
Chris Lattner6cefb772008-01-05 22:25:12 +00002252 // If debugging, print out the pattern fragment result.
2253 DEBUG(ThePat->dump());
2254 }
2255}
2256
Chris Lattnerfe718932008-01-06 01:10:31 +00002257void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellard6d3d7652012-09-06 14:15:52 +00002258 std::vector<Record*> DefaultOps;
2259 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner6cefb772008-01-05 22:25:12 +00002260
2261 // Find some SDNode.
2262 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greene05bce0b2011-07-29 22:43:06 +00002263 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002264
Tom Stellard6d3d7652012-09-06 14:15:52 +00002265 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2266 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002267
Tom Stellard6d3d7652012-09-06 14:15:52 +00002268 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2269 // SomeSDnode so that we can parse this.
2270 std::vector<std::pair<Init*, std::string> > Ops;
2271 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2272 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2273 DefaultInfo->getArgName(op)));
2274 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002275
Tom Stellard6d3d7652012-09-06 14:15:52 +00002276 // Create a TreePattern to parse this.
2277 TreePattern P(DefaultOps[i], DI, false, *this);
2278 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002279
Tom Stellard6d3d7652012-09-06 14:15:52 +00002280 // Copy the operands over into a DAGDefaultOperand.
2281 DAGDefaultOperand DefaultOpInfo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002282
Tom Stellard6d3d7652012-09-06 14:15:52 +00002283 TreePatternNode *T = P.getTree(0);
2284 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2285 TreePatternNode *TPN = T->getChild(op);
2286 while (TPN->ApplyTypeConstraints(P, false))
2287 /* Resolve all types */;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002288
Tom Stellard6d3d7652012-09-06 14:15:52 +00002289 if (TPN->ContainsUnresolvedType()) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002290 PrintFatalError("Value #" + utostr(i) + " of OperandWithDefaultOps '" +
2291 DefaultOps[i]->getName() +"' doesn't have a concrete type!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002292 }
Tom Stellard6d3d7652012-09-06 14:15:52 +00002293 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner6cefb772008-01-05 22:25:12 +00002294 }
Tom Stellard6d3d7652012-09-06 14:15:52 +00002295
2296 // Insert it into the DefaultOperands map so we can find it later.
2297 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner6cefb772008-01-05 22:25:12 +00002298 }
2299}
2300
2301/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2302/// instruction input. Return true if this is a real use.
2303static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002304 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002305 // No name -> not interesting.
2306 if (Pat->getName().empty()) {
2307 if (Pat->isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002308 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00002309 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2310 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002311 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002312 }
2313 return false;
2314 }
2315
2316 Record *Rec;
2317 if (Pat->isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002318 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002319 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2320 Rec = DI->getDef();
2321 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00002322 Rec = Pat->getOperator();
2323 }
2324
2325 // SRCVALUE nodes are ignored.
2326 if (Rec->getName() == "srcvalue")
2327 return false;
2328
2329 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2330 if (!Slot) {
2331 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00002332 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00002333 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00002334 Record *SlotRec;
2335 if (Slot->isLeaf()) {
Sean Silva3f7b7f82012-10-10 20:24:47 +00002336 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattner53d09bd2010-02-23 05:59:10 +00002337 } else {
2338 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2339 SlotRec = Slot->getOperator();
2340 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002341
Chris Lattner53d09bd2010-02-23 05:59:10 +00002342 // Ensure that the inputs agree if we've already seen this input.
2343 if (Rec != SlotRec)
2344 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerd7349192010-03-19 21:37:09 +00002345 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattner53d09bd2010-02-23 05:59:10 +00002346 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00002347 return true;
2348}
2349
2350/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2351/// part of "I", the instruction), computing the set of inputs and outputs of
2352/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00002353void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00002354FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2355 std::map<std::string, TreePatternNode*> &InstInputs,
2356 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner6cefb772008-01-05 22:25:12 +00002357 std::vector<Record*> &InstImpResults) {
2358 if (Pat->isLeaf()) {
Chris Lattneracfb70f2010-04-20 06:30:25 +00002359 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00002360 if (!isUse && Pat->getTransformFn())
2361 I->error("Cannot specify a transform function for a non-input value!");
2362 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002363 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002364
Chris Lattner84aa60b2010-02-17 06:53:36 +00002365 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002366 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2367 TreePatternNode *Dest = Pat->getChild(i);
2368 if (!Dest->isLeaf())
2369 I->error("implicitly defined value should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002370
Sean Silva6cfc8062012-10-10 20:24:43 +00002371 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002372 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2373 I->error("implicitly defined value should be a register!");
2374 InstImpResults.push_back(Val->getDef());
2375 }
2376 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002377 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002378
Chris Lattner84aa60b2010-02-17 06:53:36 +00002379 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002380 // If this is not a set, verify that the children nodes are not void typed,
2381 // and recurse.
2382 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002383 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002384 I->error("Cannot have void nodes inside of patterns!");
2385 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002386 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002387 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002388
Chris Lattner6cefb772008-01-05 22:25:12 +00002389 // If this is a non-leaf node with no children, treat it basically as if
2390 // it were a leaf. This handles nodes like (imm).
Chris Lattneracfb70f2010-04-20 06:30:25 +00002391 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002392
Chris Lattner6cefb772008-01-05 22:25:12 +00002393 if (!isUse && Pat->getTransformFn())
2394 I->error("Cannot specify a transform function for a non-input value!");
2395 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00002396 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002397
Chris Lattner6cefb772008-01-05 22:25:12 +00002398 // Otherwise, this is a set, validate and collect instruction results.
2399 if (Pat->getNumChildren() == 0)
2400 I->error("set requires operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002401
Chris Lattner6cefb772008-01-05 22:25:12 +00002402 if (Pat->getTransformFn())
2403 I->error("Cannot specify a transform function on a set node!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002404
Chris Lattner6cefb772008-01-05 22:25:12 +00002405 // Check the set destinations.
2406 unsigned NumDests = Pat->getNumChildren()-1;
2407 for (unsigned i = 0; i != NumDests; ++i) {
2408 TreePatternNode *Dest = Pat->getChild(i);
2409 if (!Dest->isLeaf())
2410 I->error("set destination should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002411
Sean Silva6cfc8062012-10-10 20:24:43 +00002412 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00002413 if (!Val)
2414 I->error("set destination should be a register!");
2415
2416 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Owen Andersonbea6f612011-06-27 21:06:21 +00002417 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00002418 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002419 if (Dest->getName().empty())
2420 I->error("set destination must have a name!");
2421 if (InstResults.count(Dest->getName()))
2422 I->error("cannot set '" + Dest->getName() +"' multiple times");
2423 InstResults[Dest->getName()] = Dest;
2424 } else if (Val->getDef()->isSubClassOf("Register")) {
2425 InstImpResults.push_back(Val->getDef());
2426 } else {
2427 I->error("set destination should be a register!");
2428 }
2429 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002430
Chris Lattner6cefb772008-01-05 22:25:12 +00002431 // Verify and collect info from the computation.
2432 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattneracfb70f2010-04-20 06:30:25 +00002433 InstInputs, InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002434}
2435
Dan Gohmanee4fa192008-04-03 00:02:49 +00002436//===----------------------------------------------------------------------===//
2437// Instruction Analysis
2438//===----------------------------------------------------------------------===//
2439
2440class InstAnalyzer {
2441 const CodeGenDAGPatterns &CDP;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002442public:
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002443 bool hasSideEffects;
2444 bool mayStore;
2445 bool mayLoad;
2446 bool isBitcast;
2447 bool isVariadic;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002448
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002449 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2450 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2451 isBitcast(false), isVariadic(false) {}
Dan Gohmanee4fa192008-04-03 00:02:49 +00002452
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002453 void Analyze(const TreePattern *Pat) {
2454 // Assume only the first tree is the pattern. The others are clobber nodes.
2455 AnalyzeNode(Pat->getTree(0));
Dan Gohmanee4fa192008-04-03 00:02:49 +00002456 }
2457
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00002458 void Analyze(const PatternToMatch *Pat) {
2459 AnalyzeNode(Pat->getSrcPattern());
2460 }
2461
Dan Gohmanee4fa192008-04-03 00:02:49 +00002462private:
Evan Cheng0f040a22011-03-15 05:09:26 +00002463 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002464 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng0f040a22011-03-15 05:09:26 +00002465 return false;
2466
2467 if (N->getNumChildren() != 2)
2468 return false;
2469
2470 const TreePatternNode *N0 = N->getChild(0);
Sean Silva3f7b7f82012-10-10 20:24:47 +00002471 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng0f040a22011-03-15 05:09:26 +00002472 return false;
2473
2474 const TreePatternNode *N1 = N->getChild(1);
2475 if (N1->isLeaf())
2476 return false;
2477 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2478 return false;
2479
2480 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2481 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2482 return false;
2483 return OpInfo.getEnumName() == "ISD::BITCAST";
2484 }
2485
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00002486public:
Dan Gohmanee4fa192008-04-03 00:02:49 +00002487 void AnalyzeNode(const TreePatternNode *N) {
2488 if (N->isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002489 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00002490 Record *LeafRec = DI->getDef();
2491 // Handle ComplexPattern leaves.
2492 if (LeafRec->isSubClassOf("ComplexPattern")) {
2493 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2494 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2495 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002496 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002497 }
2498 }
2499 return;
2500 }
2501
2502 // Analyze children.
2503 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2504 AnalyzeNode(N->getChild(i));
2505
2506 // Ignore set nodes, which are not SDNodes.
Evan Cheng0f040a22011-03-15 05:09:26 +00002507 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002508 isBitcast = IsNodeBitcast(N);
Dan Gohmanee4fa192008-04-03 00:02:49 +00002509 return;
Evan Cheng0f040a22011-03-15 05:09:26 +00002510 }
Dan Gohmanee4fa192008-04-03 00:02:49 +00002511
2512 // Get information about the SDNode for the operator.
2513 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2514
2515 // Notice properties of the node.
2516 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2517 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002518 if (OpInfo.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2519 if (OpInfo.hasProperty(SDNPVariadic)) isVariadic = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002520
2521 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2522 // If this is an intrinsic, analyze it.
2523 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2524 mayLoad = true;// These may load memory.
2525
Dan Gohman7365c092010-08-05 23:36:21 +00002526 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002527 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2528
Dan Gohman7365c092010-08-05 23:36:21 +00002529 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanee4fa192008-04-03 00:02:49 +00002530 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002531 hasSideEffects = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002532 }
2533 }
2534
2535};
2536
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002537static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002538 const InstAnalyzer &PatInfo,
2539 Record *PatDef) {
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002540 bool Error = false;
2541
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002542 // Remember where InstInfo got its flags.
2543 if (InstInfo.hasUndefFlags())
2544 InstInfo.InferredFrom = PatDef;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002545
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002546 // Check explicitly set flags for consistency.
2547 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2548 !InstInfo.hasSideEffects_Unset) {
2549 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2550 // the pattern has no side effects. That could be useful for div/rem
2551 // instructions that may trap.
2552 if (!InstInfo.hasSideEffects) {
2553 Error = true;
2554 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2555 Twine(InstInfo.hasSideEffects));
2556 }
2557 }
2558
2559 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2560 Error = true;
2561 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2562 Twine(InstInfo.mayStore));
2563 }
2564
2565 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2566 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2567 // Some targets translate imediates to loads.
2568 if (!InstInfo.mayLoad) {
2569 Error = true;
2570 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2571 Twine(InstInfo.mayLoad));
2572 }
2573 }
2574
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002575 // Transfer inferred flags.
2576 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2577 InstInfo.mayStore |= PatInfo.mayStore;
2578 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002579
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002580 // These flags are silently added without any verification.
2581 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenaaaecfc2012-08-24 21:08:09 +00002582
2583 // Don't infer isVariadic. This flag means something different on SDNodes and
2584 // instructions. For example, a CALL SDNode is variadic because it has the
2585 // call arguments as operands, but a CALL instruction is not variadic - it
2586 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002587
2588 return Error;
Dan Gohmanee4fa192008-04-03 00:02:49 +00002589}
2590
Jim Grosbachac915b42012-07-17 00:47:06 +00002591/// hasNullFragReference - Return true if the DAG has any reference to the
2592/// null_frag operator.
2593static bool hasNullFragReference(DagInit *DI) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002594 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbachac915b42012-07-17 00:47:06 +00002595 if (!OpDef) return false;
2596 Record *Operator = OpDef->getDef();
2597
2598 // If this is the null fragment, return true.
2599 if (Operator->getName() == "null_frag") return true;
2600 // If any of the arguments reference the null fragment, return true.
2601 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002602 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbachac915b42012-07-17 00:47:06 +00002603 if (Arg && hasNullFragReference(Arg))
2604 return true;
2605 }
2606
2607 return false;
2608}
2609
2610/// hasNullFragReference - Return true if any DAG in the list references
2611/// the null_frag operator.
2612static bool hasNullFragReference(ListInit *LI) {
2613 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002614 DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
Jim Grosbachac915b42012-07-17 00:47:06 +00002615 assert(DI && "non-dag in an instruction Pattern list?!");
2616 if (hasNullFragReference(DI))
2617 return true;
2618 }
2619 return false;
2620}
2621
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00002622/// Get all the instructions in a tree.
2623static void
2624getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2625 if (Tree->isLeaf())
2626 return;
2627 if (Tree->getOperator()->isSubClassOf("Instruction"))
2628 Instrs.push_back(Tree->getOperator());
2629 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2630 getInstructionsInTree(Tree->getChild(i), Instrs);
2631}
2632
Chris Lattner6cefb772008-01-05 22:25:12 +00002633/// ParseInstructions - Parse all of the instructions, inlining and resolving
2634/// any fragments involved. This populates the Instructions list with fully
2635/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002636void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002637 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002638
Chris Lattner6cefb772008-01-05 22:25:12 +00002639 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
David Greene05bce0b2011-07-29 22:43:06 +00002640 ListInit *LI = 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002641
Sean Silva3f7b7f82012-10-10 20:24:47 +00002642 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
Chris Lattner6cefb772008-01-05 22:25:12 +00002643 LI = Instrs[i]->getValueAsListInit("Pattern");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002644
Chris Lattner6cefb772008-01-05 22:25:12 +00002645 // If there is no pattern, only collect minimal information about the
2646 // instruction for its operand list. We have to assume that there is one
Jim Grosbachac915b42012-07-17 00:47:06 +00002647 // result, as we have no detailed info. A pattern which references the
2648 // null_frag operator is as-if no pattern were specified. Normally this
2649 // is from a multiclass expansion w/ a SDPatternOperator passed in as
2650 // null_frag.
2651 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002652 std::vector<Record*> Results;
2653 std::vector<Record*> Operands;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002654
Chris Lattnerf30187a2010-03-19 00:07:20 +00002655 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002656
Chris Lattnerc240bb02010-11-01 04:03:32 +00002657 if (InstInfo.Operands.size() != 0) {
2658 if (InstInfo.Operands.NumDefs == 0) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002659 // These produce no results
Chris Lattnerc240bb02010-11-01 04:03:32 +00002660 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2661 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002662 } else {
2663 // Assume the first operand is the result.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002664 Results.push_back(InstInfo.Operands[0].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002665
Chris Lattner6cefb772008-01-05 22:25:12 +00002666 // The rest are inputs.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002667 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2668 Operands.push_back(InstInfo.Operands[j].Rec);
Chris Lattner6cefb772008-01-05 22:25:12 +00002669 }
2670 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002671
Chris Lattner6cefb772008-01-05 22:25:12 +00002672 // Create and insert the instruction.
2673 std::vector<Record*> ImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002674 Instructions.insert(std::make_pair(Instrs[i],
Chris Lattner62bcec82010-04-20 06:28:43 +00002675 DAGInstruction(0, Results, Operands, ImpResults)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002676 continue; // no pattern.
2677 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002678
Chris Lattner6cefb772008-01-05 22:25:12 +00002679 // Parse the instruction.
2680 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2681 // Inline pattern fragments into it.
2682 I->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002683
Chris Lattner6cefb772008-01-05 22:25:12 +00002684 // Infer as many types as possible. If we cannot infer all of them, we can
2685 // never do anything with this instruction pattern: report it to the user.
2686 if (!I->InferAllTypes())
2687 I->error("Could not infer all types in pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002688
2689 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner6cefb772008-01-05 22:25:12 +00002690 // with the record they are declared as.
2691 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002692
Chris Lattner6cefb772008-01-05 22:25:12 +00002693 // InstResults - Keep track of all the virtual registers that are 'set'
2694 // in the instruction, including what reg class they are.
2695 std::map<std::string, TreePatternNode*> InstResults;
2696
Chris Lattner6cefb772008-01-05 22:25:12 +00002697 std::vector<Record*> InstImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002698
Chris Lattner6cefb772008-01-05 22:25:12 +00002699 // Verify that the top-level forms in the instruction are of void type, and
2700 // fill in the InstResults map.
2701 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2702 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerd7349192010-03-19 21:37:09 +00002703 if (Pat->getNumTypes() != 0)
Chris Lattner6cefb772008-01-05 22:25:12 +00002704 I->error("Top-level forms in instruction pattern should have"
2705 " void types");
2706
2707 // Find inputs and outputs, and verify the structure of the uses/defs.
2708 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00002709 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002710 }
2711
2712 // Now that we have inputs and outputs of the pattern, inspect the operands
2713 // list for the instruction. This determines the order that operands are
2714 // added to the machine instruction the node corresponds to.
2715 unsigned NumResults = InstResults.size();
2716
2717 // Parse the operands list from the (ops) list, validating it.
2718 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattnerf30187a2010-03-19 00:07:20 +00002719 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00002720
2721 // Check that all of the results occur first in the list.
2722 std::vector<Record*> Results;
Chris Lattnerd7349192010-03-19 21:37:09 +00002723 TreePatternNode *Res0Node = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +00002724 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerc240bb02010-11-01 04:03:32 +00002725 if (i == CGI.Operands.size())
Chris Lattner6cefb772008-01-05 22:25:12 +00002726 I->error("'" + InstResults.begin()->first +
2727 "' set but does not appear in operand list!");
Chris Lattnerc240bb02010-11-01 04:03:32 +00002728 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002729
Chris Lattner6cefb772008-01-05 22:25:12 +00002730 // Check that it exists in InstResults.
2731 TreePatternNode *RNode = InstResults[OpName];
2732 if (RNode == 0)
2733 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002734
Chris Lattner6cefb772008-01-05 22:25:12 +00002735 if (i == 0)
2736 Res0Node = RNode;
Sean Silva3f7b7f82012-10-10 20:24:47 +00002737 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Chris Lattner6cefb772008-01-05 22:25:12 +00002738 if (R == 0)
2739 I->error("Operand $" + OpName + " should be a set destination: all "
2740 "outputs must occur before inputs in operand list!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002741
Chris Lattnerc240bb02010-11-01 04:03:32 +00002742 if (CGI.Operands[i].Rec != R)
Chris Lattner6cefb772008-01-05 22:25:12 +00002743 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002744
Chris Lattner6cefb772008-01-05 22:25:12 +00002745 // Remember the return type.
Chris Lattnerc240bb02010-11-01 04:03:32 +00002746 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002747
Chris Lattner6cefb772008-01-05 22:25:12 +00002748 // Okay, this one checks out.
2749 InstResults.erase(OpName);
2750 }
2751
2752 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2753 // the copy while we're checking the inputs.
2754 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2755
2756 std::vector<TreePatternNode*> ResultNodeOperands;
2757 std::vector<Record*> Operands;
Chris Lattnerc240bb02010-11-01 04:03:32 +00002758 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2759 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner6cefb772008-01-05 22:25:12 +00002760 const std::string &OpName = Op.Name;
2761 if (OpName.empty())
2762 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2763
2764 if (!InstInputsCheck.count(OpName)) {
Tom Stellard6d3d7652012-09-06 14:15:52 +00002765 // If this is an operand with a DefaultOps set filled in, we can ignore
2766 // this. When we codegen it, we will do so as always executed.
2767 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002768 // Does it have a non-empty DefaultOps field? If so, ignore this
2769 // operand.
2770 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2771 continue;
2772 }
2773 I->error("Operand $" + OpName +
2774 " does not appear in the instruction pattern");
2775 }
2776 TreePatternNode *InVal = InstInputsCheck[OpName];
2777 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002778
Sean Silva3f7b7f82012-10-10 20:24:47 +00002779 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
David Greene05bce0b2011-07-29 22:43:06 +00002780 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Chris Lattner6cefb772008-01-05 22:25:12 +00002781 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2782 I->error("Operand $" + OpName + "'s register class disagrees"
2783 " between the operand and pattern");
2784 }
2785 Operands.push_back(Op.Rec);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002786
Chris Lattner6cefb772008-01-05 22:25:12 +00002787 // Construct the result for the dest-pattern operand list.
2788 TreePatternNode *OpNode = InVal->clone();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002789
Chris Lattner6cefb772008-01-05 22:25:12 +00002790 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002791 OpNode->clearPredicateFns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002792
Chris Lattner6cefb772008-01-05 22:25:12 +00002793 // Promote the xform function to be an explicit node if set.
2794 if (Record *Xform = OpNode->getTransformFn()) {
2795 OpNode->setTransformFn(0);
2796 std::vector<TreePatternNode*> Children;
2797 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00002798 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00002799 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002800
Chris Lattner6cefb772008-01-05 22:25:12 +00002801 ResultNodeOperands.push_back(OpNode);
2802 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002803
Chris Lattner6cefb772008-01-05 22:25:12 +00002804 if (!InstInputsCheck.empty())
2805 I->error("Input operand $" + InstInputsCheck.begin()->first +
2806 " occurs in pattern but not in operands list!");
2807
2808 TreePatternNode *ResultPattern =
Chris Lattnerd7349192010-03-19 21:37:09 +00002809 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2810 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner6cefb772008-01-05 22:25:12 +00002811 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerd7349192010-03-19 21:37:09 +00002812 for (unsigned i = 0; i != NumResults; ++i)
2813 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner6cefb772008-01-05 22:25:12 +00002814
2815 // Create and insert the instruction.
Chris Lattneracfb70f2010-04-20 06:30:25 +00002816 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner62bcec82010-04-20 06:28:43 +00002817 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00002818 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2819
2820 // Use a temporary tree pattern to infer all types and make sure that the
2821 // constructed result is correct. This depends on the instruction already
2822 // being inserted into the Instructions map.
2823 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002824 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00002825
2826 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2827 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002828
Chris Lattner6cefb772008-01-05 22:25:12 +00002829 DEBUG(I->dump());
2830 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002831
Chris Lattner6cefb772008-01-05 22:25:12 +00002832 // If we can, convert the instructions to be patterns that are matched!
Sean Silva90fee072012-09-19 01:47:00 +00002833 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002834 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002835 E = Instructions.end(); II != E; ++II) {
2836 DAGInstruction &TheInst = II->second;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002837 TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002838 if (I == 0) continue; // No pattern.
2839
2840 // FIXME: Assume only the first tree is the pattern. The others are clobber
2841 // nodes.
2842 TreePatternNode *Pattern = I->getTree(0);
2843 TreePatternNode *SrcPattern;
2844 if (Pattern->getOperator()->getName() == "set") {
2845 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2846 } else{
2847 // Not a set (store or something?)
2848 SrcPattern = Pattern;
2849 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002850
Chris Lattner6cefb772008-01-05 22:25:12 +00002851 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002852 AddPatternToMatch(I,
Jim Grosbach997759a2010-12-07 23:05:49 +00002853 PatternToMatch(Instr,
2854 Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002855 SrcPattern,
2856 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002857 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002858 Instr->getValueAsInt("AddedComplexity"),
2859 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002860 }
2861}
2862
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002863
2864typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2865
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002866static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002867 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002868 TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002869 if (!P->getName().empty()) {
2870 NameRecord &Rec = Names[P->getName()];
2871 // If this is the first instance of the name, remember the node.
2872 if (Rec.second++ == 0)
2873 Rec.first = P;
Chris Lattnerd7349192010-03-19 21:37:09 +00002874 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattnera27234e2010-02-23 07:22:28 +00002875 PatternTop->error("repetition of value: $" + P->getName() +
2876 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002877 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002878
Chris Lattner967d54a2010-02-23 06:35:45 +00002879 if (!P->isLeaf()) {
2880 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002881 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002882 }
2883}
2884
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002885void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner25b6f912010-02-23 06:16:51 +00002886 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002887 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002888 std::string Reason;
Owen Andersoneb79b542012-09-19 22:15:06 +00002889 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
2890 PrintWarning(Pattern->getRecord()->getLoc(),
2891 Twine("Pattern can never match: ") + Reason);
2892 return;
2893 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002894
Chris Lattner405f1252010-03-01 22:29:19 +00002895 // If the source pattern's root is a complex pattern, that complex pattern
2896 // must specify the nodes it can potentially match.
2897 if (const ComplexPattern *CP =
2898 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2899 if (CP->getRootNodes().empty())
2900 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2901 " could match");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002902
2903
Chris Lattner967d54a2010-02-23 06:35:45 +00002904 // Find all of the named values in the input and output, ensure they have the
2905 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002906 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002907 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2908 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002909
2910 // Scan all of the named values in the destination pattern, rejecting them if
2911 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002912 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002913 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002914 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002915 Pattern->error("Pattern has input without matching name in output: $" +
2916 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002917 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002918
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002919 // Scan all of the named values in the source pattern, rejecting them if the
2920 // name isn't used in the dest, and isn't used to tie two values together.
2921 for (std::map<std::string, NameRecord>::iterator
2922 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2923 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2924 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002925
Chris Lattner25b6f912010-02-23 06:16:51 +00002926 PatternsToMatch.push_back(PTM);
2927}
2928
2929
Dan Gohmanee4fa192008-04-03 00:02:49 +00002930
2931void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattnerf6502782010-03-19 00:34:35 +00002932 const std::vector<const CodeGenInstruction*> &Instructions =
2933 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002934
2935 // First try to infer flags from the primary instruction pattern, if any.
2936 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002937 unsigned Errors = 0;
Chris Lattnerb61e09d2010-03-19 00:18:23 +00002938 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2939 CodeGenInstruction &InstInfo =
2940 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesenccbe6032011-10-14 01:00:49 +00002941
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002942 // Treat neverHasSideEffects = 1 as the equivalent of hasSideEffects = 0.
2943 // This flag is obsolete and will be removed.
2944 if (InstInfo.neverHasSideEffects) {
2945 assert(!InstInfo.hasSideEffects);
2946 InstInfo.hasSideEffects_Unset = false;
2947 }
2948
2949 // Get the primary instruction pattern.
2950 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
2951 if (!Pattern) {
2952 if (InstInfo.hasUndefFlags())
2953 Revisit.push_back(&InstInfo);
2954 continue;
2955 }
2956 InstAnalyzer PatInfo(*this);
2957 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002958 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002959 }
2960
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00002961 // Second, look for single-instruction patterns defined outside the
2962 // instruction.
2963 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
2964 const PatternToMatch &PTM = *I;
2965
2966 // We can only infer from single-instruction patterns, otherwise we won't
2967 // know which instruction should get the flags.
2968 SmallVector<Record*, 8> PatInstrs;
2969 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
2970 if (PatInstrs.size() != 1)
2971 continue;
2972
2973 // Get the single instruction.
2974 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
2975
2976 // Only infer properties from the first pattern. We'll verify the others.
2977 if (InstInfo.InferredFrom)
2978 continue;
2979
2980 InstAnalyzer PatInfo(*this);
2981 PatInfo.Analyze(&PTM);
2982 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
2983 }
2984
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002985 if (Errors)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002986 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00002987
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00002988 // Revisit instructions with undefined flags and no pattern.
2989 if (Target.guessInstructionProperties()) {
2990 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
2991 CodeGenInstruction &InstInfo = *Revisit[i];
2992 if (InstInfo.InferredFrom)
2993 continue;
2994 // The mayLoad and mayStore flags default to false.
2995 // Conservatively assume hasSideEffects if it wasn't explicit.
2996 if (InstInfo.hasSideEffects_Unset)
2997 InstInfo.hasSideEffects = true;
2998 }
2999 return;
3000 }
3001
3002 // Complain about any flags that are still undefined.
3003 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3004 CodeGenInstruction &InstInfo = *Revisit[i];
3005 if (InstInfo.InferredFrom)
3006 continue;
3007 if (InstInfo.hasSideEffects_Unset)
3008 PrintError(InstInfo.TheDef->getLoc(),
3009 "Can't infer hasSideEffects from patterns");
3010 if (InstInfo.mayStore_Unset)
3011 PrintError(InstInfo.TheDef->getLoc(),
3012 "Can't infer mayStore from patterns");
3013 if (InstInfo.mayLoad_Unset)
3014 PrintError(InstInfo.TheDef->getLoc(),
3015 "Can't infer mayLoad from patterns");
Dan Gohmanee4fa192008-04-03 00:02:49 +00003016 }
3017}
3018
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003019
3020/// Verify instruction flags against pattern node properties.
3021void CodeGenDAGPatterns::VerifyInstructionFlags() {
3022 unsigned Errors = 0;
3023 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3024 const PatternToMatch &PTM = *I;
3025 SmallVector<Record*, 8> Instrs;
3026 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3027 if (Instrs.empty())
3028 continue;
3029
3030 // Count the number of instructions with each flag set.
3031 unsigned NumSideEffects = 0;
3032 unsigned NumStores = 0;
3033 unsigned NumLoads = 0;
3034 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3035 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3036 NumSideEffects += InstInfo.hasSideEffects;
3037 NumStores += InstInfo.mayStore;
3038 NumLoads += InstInfo.mayLoad;
3039 }
3040
3041 // Analyze the source pattern.
3042 InstAnalyzer PatInfo(*this);
3043 PatInfo.Analyze(&PTM);
3044
3045 // Collect error messages.
3046 SmallVector<std::string, 4> Msgs;
3047
3048 // Check for missing flags in the output.
3049 // Permit extra flags for now at least.
3050 if (PatInfo.hasSideEffects && !NumSideEffects)
3051 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3052
3053 // Don't verify store flags on instructions with side effects. At least for
3054 // intrinsics, side effects implies mayStore.
3055 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3056 Msgs.push_back("pattern may store, but mayStore isn't set");
3057
3058 // Similarly, mayStore implies mayLoad on intrinsics.
3059 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3060 Msgs.push_back("pattern may load, but mayLoad isn't set");
3061
3062 // Print error messages.
3063 if (Msgs.empty())
3064 continue;
3065 ++Errors;
3066
3067 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3068 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3069 (Instrs.size() == 1 ?
3070 "instruction" : "output instructions"));
3071 // Provide the location of the relevant instruction definitions.
3072 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3073 if (Instrs[i] != PTM.getSrcRecord())
3074 PrintError(Instrs[i]->getLoc(), "defined here");
3075 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3076 if (InstInfo.InferredFrom &&
3077 InstInfo.InferredFrom != InstInfo.TheDef &&
3078 InstInfo.InferredFrom != PTM.getSrcRecord())
3079 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
3080 }
3081 }
3082 if (Errors)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00003083 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003084}
3085
Chris Lattner2cacec52010-03-15 06:00:16 +00003086/// Given a pattern result with an unresolved type, see if we can find one
3087/// instruction with an unresolved result type. Force this result type to an
3088/// arbitrary element if it's possible types to converge results.
3089static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3090 if (N->isLeaf())
3091 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003092
Chris Lattner2cacec52010-03-15 06:00:16 +00003093 // Analyze children.
3094 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3095 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3096 return true;
3097
3098 if (!N->getOperator()->isSubClassOf("Instruction"))
3099 return false;
3100
3101 // If this type is already concrete or completely unknown we can't do
3102 // anything.
Chris Lattnerd7349192010-03-19 21:37:09 +00003103 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3104 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3105 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003106
Chris Lattnerd7349192010-03-19 21:37:09 +00003107 // Otherwise, force its type to the first possibility (an arbitrary choice).
3108 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3109 return true;
3110 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003111
Chris Lattnerd7349192010-03-19 21:37:09 +00003112 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00003113}
3114
Chris Lattnerfe718932008-01-06 01:10:31 +00003115void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00003116 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3117
3118 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00003119 Record *CurPattern = Patterns[i];
David Greene05bce0b2011-07-29 22:43:06 +00003120 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachd3e31212012-07-17 18:39:36 +00003121
3122 // If the pattern references the null_frag, there's nothing to do.
3123 if (hasNullFragReference(Tree))
3124 continue;
3125
Chris Lattner310adf12010-03-27 02:53:27 +00003126 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00003127
3128 // Inline pattern fragments into it.
3129 Pattern->InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003130
David Greene05bce0b2011-07-29 22:43:06 +00003131 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner6cefb772008-01-05 22:25:12 +00003132 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003133
Chris Lattner6cefb772008-01-05 22:25:12 +00003134 // Parse the instruction.
Chris Lattnerd7349192010-03-19 21:37:09 +00003135 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003136
Chris Lattner6cefb772008-01-05 22:25:12 +00003137 // Inline pattern fragments into it.
3138 Result->InlinePatternFragments();
3139
3140 if (Result->getNumTrees() != 1)
3141 Result->error("Cannot handle instructions producing instructions "
3142 "with temporaries yet!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003143
Chris Lattner6cefb772008-01-05 22:25:12 +00003144 bool IterateInference;
3145 bool InferredAllPatternTypes, InferredAllResultTypes;
3146 do {
3147 // Infer as many types as possible. If we cannot infer all of them, we
3148 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00003149 InferredAllPatternTypes =
3150 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003151
Chris Lattner6cefb772008-01-05 22:25:12 +00003152 // Infer as many types as possible. If we cannot infer all of them, we
3153 // can never do anything with this pattern: report it to the user.
Chris Lattner2cacec52010-03-15 06:00:16 +00003154 InferredAllResultTypes =
3155 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner6cefb772008-01-05 22:25:12 +00003156
Chris Lattner6c6ba362010-03-18 23:15:10 +00003157 IterateInference = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003158
Chris Lattner6cefb772008-01-05 22:25:12 +00003159 // Apply the type of the result to the source pattern. This helps us
3160 // resolve cases where the input type is known to be a pointer type (which
3161 // is considered resolved), but the result knows it needs to be 32- or
3162 // 64-bits. Infer the other way for good measure.
Chris Lattnerd7349192010-03-19 21:37:09 +00003163 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
3164 Pattern->getTree(0)->getNumTypes());
3165 i != e; ++i) {
Chris Lattner6c6ba362010-03-18 23:15:10 +00003166 IterateInference = Pattern->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00003167 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00003168 IterateInference |= Result->getTree(0)->
Chris Lattnerd7349192010-03-19 21:37:09 +00003169 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattner6c6ba362010-03-18 23:15:10 +00003170 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003171
Chris Lattner2cacec52010-03-15 06:00:16 +00003172 // If our iteration has converged and the input pattern's types are fully
3173 // resolved but the result pattern is not fully resolved, we may have a
3174 // situation where we have two instructions in the result pattern and
3175 // the instructions require a common register class, but don't care about
3176 // what actual MVT is used. This is actually a bug in our modelling:
3177 // output patterns should have register classes, not MVTs.
3178 //
3179 // In any case, to handle this, we just go through and disambiguate some
3180 // arbitrary types to the result pattern's nodes.
3181 if (!IterateInference && InferredAllPatternTypes &&
3182 !InferredAllResultTypes)
3183 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
3184 *Result);
Chris Lattner6cefb772008-01-05 22:25:12 +00003185 } while (IterateInference);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003186
Chris Lattner6cefb772008-01-05 22:25:12 +00003187 // Verify that we inferred enough types that we can do something with the
3188 // pattern and result. If these fire the user has to add type casts.
3189 if (!InferredAllPatternTypes)
3190 Pattern->error("Could not infer all types in pattern!");
Chris Lattner2cacec52010-03-15 06:00:16 +00003191 if (!InferredAllResultTypes) {
3192 Pattern->dump();
Chris Lattner6cefb772008-01-05 22:25:12 +00003193 Result->error("Could not infer all types in pattern result!");
Chris Lattner2cacec52010-03-15 06:00:16 +00003194 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003195
Chris Lattner6cefb772008-01-05 22:25:12 +00003196 // Validate that the input pattern is correct.
3197 std::map<std::string, TreePatternNode*> InstInputs;
3198 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00003199 std::vector<Record*> InstImpResults;
3200 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3201 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3202 InstInputs, InstResults,
Chris Lattneracfb70f2010-04-20 06:30:25 +00003203 InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00003204
3205 // Promote the xform function to be an explicit node if set.
3206 TreePatternNode *DstPattern = Result->getOnlyTree();
3207 std::vector<TreePatternNode*> ResultNodeOperands;
3208 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3209 TreePatternNode *OpNode = DstPattern->getChild(ii);
3210 if (Record *Xform = OpNode->getTransformFn()) {
3211 OpNode->setTransformFn(0);
3212 std::vector<TreePatternNode*> Children;
3213 Children.push_back(OpNode);
Chris Lattnerd7349192010-03-19 21:37:09 +00003214 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00003215 }
3216 ResultNodeOperands.push_back(OpNode);
3217 }
3218 DstPattern = Result->getOnlyTree();
3219 if (!DstPattern->isLeaf())
3220 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerd7349192010-03-19 21:37:09 +00003221 ResultNodeOperands,
3222 DstPattern->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003223
Chris Lattnerd7349192010-03-19 21:37:09 +00003224 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
3225 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003226
Chris Lattner6cefb772008-01-05 22:25:12 +00003227 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
3228 Temp.InferAllTypes();
3229
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003230
Chris Lattner25b6f912010-02-23 06:16:51 +00003231 AddPatternToMatch(Pattern,
Jim Grosbach997759a2010-12-07 23:05:49 +00003232 PatternToMatch(CurPattern,
3233 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerd7349192010-03-19 21:37:09 +00003234 Pattern->getTree(0),
3235 Temp.getOnlyTree(), InstImpResults,
3236 CurPattern->getValueAsInt("AddedComplexity"),
3237 CurPattern->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003238 }
3239}
3240
3241/// CombineChildVariants - Given a bunch of permutations of each child of the
3242/// 'operator' node, put them together in all possible ways.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003243static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00003244 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3245 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003246 CodeGenDAGPatterns &CDP,
3247 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003248 // Make sure that each operand has at least one variant to choose from.
3249 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3250 if (ChildVariants[i].empty())
3251 return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003252
Chris Lattner6cefb772008-01-05 22:25:12 +00003253 // The end result is an all-pairs construction of the resultant pattern.
3254 std::vector<unsigned> Idxs;
3255 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00003256 bool NotDone;
3257 do {
3258#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00003259 DEBUG(if (!Idxs.empty()) {
3260 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3261 for (unsigned i = 0; i < Idxs.size(); ++i) {
3262 errs() << Idxs[i] << " ";
3263 }
3264 errs() << "]\n";
3265 });
Scott Michel327d0652008-03-05 17:49:05 +00003266#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00003267 // Create the variant and add it to the output list.
3268 std::vector<TreePatternNode*> NewChildren;
3269 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3270 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerd7349192010-03-19 21:37:09 +00003271 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3272 Orig->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003273
Chris Lattner6cefb772008-01-05 22:25:12 +00003274 // Copy over properties.
3275 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00003276 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00003277 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerd7349192010-03-19 21:37:09 +00003278 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3279 R->setType(i, Orig->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003280
Scott Michel327d0652008-03-05 17:49:05 +00003281 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00003282 std::string ErrString;
3283 if (!R->canPatternMatch(ErrString, CDP)) {
3284 delete R;
3285 } else {
3286 bool AlreadyExists = false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003287
Chris Lattner6cefb772008-01-05 22:25:12 +00003288 // Scan to see if this pattern has already been emitted. We can get
3289 // duplication due to things like commuting:
3290 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3291 // which are the same pattern. Ignore the dups.
3292 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003293 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003294 AlreadyExists = true;
3295 break;
3296 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003297
Chris Lattner6cefb772008-01-05 22:25:12 +00003298 if (AlreadyExists)
3299 delete R;
3300 else
3301 OutVariants.push_back(R);
3302 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003303
Scott Michel327d0652008-03-05 17:49:05 +00003304 // Increment indices to the next permutation by incrementing the
3305 // indicies from last index backward, e.g., generate the sequence
3306 // [0, 0], [0, 1], [1, 0], [1, 1].
3307 int IdxsIdx;
3308 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3309 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3310 Idxs[IdxsIdx] = 0;
3311 else
Chris Lattner6cefb772008-01-05 22:25:12 +00003312 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00003313 }
Scott Michel327d0652008-03-05 17:49:05 +00003314 NotDone = (IdxsIdx >= 0);
3315 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00003316}
3317
3318/// CombineChildVariants - A helper function for binary operators.
3319///
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003320static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner6cefb772008-01-05 22:25:12 +00003321 const std::vector<TreePatternNode*> &LHS,
3322 const std::vector<TreePatternNode*> &RHS,
3323 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003324 CodeGenDAGPatterns &CDP,
3325 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003326 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3327 ChildVariants.push_back(LHS);
3328 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00003329 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003330}
Chris Lattner6cefb772008-01-05 22:25:12 +00003331
3332
3333static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3334 std::vector<TreePatternNode *> &Children) {
3335 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3336 Record *Operator = N->getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003337
Chris Lattner6cefb772008-01-05 22:25:12 +00003338 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00003339 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00003340 N->getTransformFn()) {
3341 Children.push_back(N);
3342 return;
3343 }
3344
3345 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3346 Children.push_back(N->getChild(0));
3347 else
3348 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3349
3350 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3351 Children.push_back(N->getChild(1));
3352 else
3353 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3354}
3355
3356/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3357/// the (potentially recursive) pattern by using algebraic laws.
3358///
3359static void GenerateVariantsOf(TreePatternNode *N,
3360 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00003361 CodeGenDAGPatterns &CDP,
3362 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003363 // We cannot permute leaves.
3364 if (N->isLeaf()) {
3365 OutVariants.push_back(N);
3366 return;
3367 }
3368
3369 // Look up interesting info about the node.
3370 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3371
Jim Grosbachda4231f2009-03-26 16:17:51 +00003372 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00003373 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003374 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00003375 std::vector<TreePatternNode*> MaximalChildren;
3376 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3377
3378 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3379 // permutations.
3380 if (MaximalChildren.size() == 3) {
3381 // Find the variants of all of our maximal children.
3382 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003383 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3384 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3385 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003386
Chris Lattner6cefb772008-01-05 22:25:12 +00003387 // There are only two ways we can permute the tree:
3388 // (A op B) op C and A op (B op C)
3389 // Within these forms, we can also permute A/B/C.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003390
Chris Lattner6cefb772008-01-05 22:25:12 +00003391 // Generate legal pair permutations of A/B/C.
3392 std::vector<TreePatternNode*> ABVariants;
3393 std::vector<TreePatternNode*> BAVariants;
3394 std::vector<TreePatternNode*> ACVariants;
3395 std::vector<TreePatternNode*> CAVariants;
3396 std::vector<TreePatternNode*> BCVariants;
3397 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00003398 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3399 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3400 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3401 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3402 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3403 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003404
3405 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00003406 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3407 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3408 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3409 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3410 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3411 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003412
3413 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00003414 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3415 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3416 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3417 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3418 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3419 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003420 return;
3421 }
3422 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003423
Chris Lattner6cefb772008-01-05 22:25:12 +00003424 // Compute permutations of all children.
3425 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3426 ChildVariants.resize(N->getNumChildren());
3427 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00003428 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003429
3430 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00003431 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003432
3433 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003434 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3435 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3436 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3437 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003438 // Don't count children which are actually register references.
3439 unsigned NC = 0;
3440 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3441 TreePatternNode *Child = N->getChild(i);
3442 if (Child->isLeaf())
Sean Silva6cfc8062012-10-10 20:24:43 +00003443 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003444 Record *RR = DI->getDef();
3445 if (RR->isSubClassOf("Register"))
3446 continue;
3447 }
3448 NC++;
3449 }
3450 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00003451 if (isCommIntrinsic) {
3452 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3453 // operands are the commutative operands, and there might be more operands
3454 // after those.
3455 assert(NC >= 3 &&
3456 "Commutative intrinsic should have at least 3 childrean!");
3457 std::vector<std::vector<TreePatternNode*> > Variants;
3458 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3459 Variants.push_back(ChildVariants[2]);
3460 Variants.push_back(ChildVariants[1]);
3461 for (unsigned i = 3; i != NC; ++i)
3462 Variants.push_back(ChildVariants[i]);
3463 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3464 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00003465 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00003466 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003467 }
3468}
3469
3470
3471// GenerateVariants - Generate variants. For example, commutative patterns can
3472// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00003473void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00003474 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003475
Chris Lattner6cefb772008-01-05 22:25:12 +00003476 // Loop over all of the patterns we've collected, checking to see if we can
3477 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00003478 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00003479 // the .td file having to contain tons of variants of instructions.
3480 //
3481 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3482 // intentionally do not reconsider these. Any variants of added patterns have
3483 // already been added.
3484 //
3485 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00003486 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00003487 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00003488 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00003489 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00003490 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00003491 DEBUG(errs() << "\n");
Jim Grosbachbb168242010-10-08 18:13:57 +00003492 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3493 DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00003494
3495 assert(!Variants.empty() && "Must create at least original variant!");
3496 Variants.erase(Variants.begin()); // Remove the original pattern.
3497
3498 if (Variants.empty()) // No variants for this pattern.
3499 continue;
3500
Chris Lattner569f1212009-08-23 04:44:11 +00003501 DEBUG(errs() << "FOUND VARIANTS OF: ";
3502 PatternsToMatch[i].getSrcPattern()->dump();
3503 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003504
3505 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3506 TreePatternNode *Variant = Variants[v];
3507
Chris Lattner569f1212009-08-23 04:44:11 +00003508 DEBUG(errs() << " VAR#" << v << ": ";
3509 Variant->dump();
3510 errs() << "\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003511
Chris Lattner6cefb772008-01-05 22:25:12 +00003512 // Scan to see if an instruction or explicit pattern already matches this.
3513 bool AlreadyExists = false;
3514 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00003515 // Skip if the top level predicates do not match.
3516 if (PatternsToMatch[i].getPredicates() !=
3517 PatternsToMatch[p].getPredicates())
3518 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00003519 // Check to see if this variant already exists.
Jim Grosbachbb168242010-10-08 18:13:57 +00003520 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3521 DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00003522 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003523 AlreadyExists = true;
3524 break;
3525 }
3526 }
3527 // If we already have it, ignore the variant.
3528 if (AlreadyExists) continue;
3529
3530 // Otherwise, add it to the list of patterns we have.
3531 PatternsToMatch.
Jim Grosbach997759a2010-12-07 23:05:49 +00003532 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3533 PatternsToMatch[i].getPredicates(),
Chris Lattner6cefb772008-01-05 22:25:12 +00003534 Variant, PatternsToMatch[i].getDstPattern(),
3535 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00003536 PatternsToMatch[i].getAddedComplexity(),
3537 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00003538 }
3539
Chris Lattner569f1212009-08-23 04:44:11 +00003540 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00003541 }
3542}