blob: 633b5b349b82c1f01e806b1974a811a467eacc20 [file] [log] [blame]
Chris Lattnerab3242f2008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner8cab0212008-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 Lattnerab3242f2008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner8cab0212008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner78ac0742008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000016#include "llvm/ADT/STLExtras.h"
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000017#include "llvm/ADT/SmallSet.h"
Craig Topper3522ab32015-11-28 08:23:02 +000018#include "llvm/ADT/SmallString.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000019#include "llvm/ADT/StringExtras.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000020#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000021#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000022#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000023#include "llvm/TableGen/Error.h"
24#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000025#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000026#include <cstdio>
27#include <set>
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000028#include <sstream>
Chris Lattner8cab0212008-01-05 22:25:12 +000029using namespace llvm;
30
Chandler Carruthe96dd892014-04-21 22:55:11 +000031#define DEBUG_TYPE "dag-patterns"
32
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000033static inline bool isIntegerOrPtr(MVT VT) {
34 return VT.isInteger() || VT == MVT::iPTR;
Duncan Sands13237ac2008-06-06 12:08:01 +000035}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000036static inline bool isFloatingPoint(MVT VT) {
37 return VT.isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000038}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000039static inline bool isVector(MVT VT) {
40 return VT.isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000041}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000042static inline bool isScalar(MVT VT) {
43 return !VT.isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000044}
Duncan Sands13237ac2008-06-06 12:08:01 +000045
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000046template <typename Predicate>
47static bool berase_if(MachineValueTypeSet &S, Predicate P) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000048 bool Erased = false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000049 // It is ok to iterate over MachineValueTypeSet and remove elements from it
50 // at the same time.
51 for (MVT T : S) {
52 if (!P(T))
53 continue;
54 Erased = true;
55 S.erase(T);
Chris Lattnercabe0372010-03-15 06:00:16 +000056 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000057 return Erased;
Chris Lattner8cab0212008-01-05 22:25:12 +000058}
59
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000060// --- TypeSetByHwMode
Chris Lattnercabe0372010-03-15 06:00:16 +000061
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000062// This is a parameterized type-set class. For each mode there is a list
63// of types that are currently possible for a given tree node. Type
64// inference will apply to each mode separately.
Jim Grosbach65586fe2010-12-21 16:16:00 +000065
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000066TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
67 for (const ValueTypeByHwMode &VVT : VTList)
68 insert(VVT);
Chris Lattner8cab0212008-01-05 22:25:12 +000069}
70
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000071bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
72 for (const auto &I : *this) {
73 if (I.second.size() > 1)
74 return false;
75 if (!AllowEmpty && I.second.empty())
76 return false;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000077 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000078 return true;
79}
Chris Lattnercabe0372010-03-15 06:00:16 +000080
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000081ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
82 assert(isValueTypeByHwMode(true) &&
83 "The type set has multiple types for at least one HW mode");
84 ValueTypeByHwMode VVT;
85 for (const auto &I : *this) {
86 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
87 VVT.getOrCreateTypeForMode(I.first, T);
Chris Lattnercabe0372010-03-15 06:00:16 +000088 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000089 return VVT;
Bob Wilson2cd5da82009-08-11 01:14:02 +000090}
Chris Lattnercabe0372010-03-15 06:00:16 +000091
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000092bool TypeSetByHwMode::isPossible() const {
93 for (const auto &I : *this)
94 if (!I.second.empty())
95 return true;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000096 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +000097}
98
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000099bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
100 bool Changed = false;
101 std::set<unsigned> Modes;
102 for (const auto &P : VVT) {
103 unsigned M = P.first;
104 Modes.insert(M);
105 // Make sure there exists a set for each specific mode from VVT.
106 Changed |= getOrCreate(M).insert(P.second).second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000107 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000108
109 // If VVT has a default mode, add the corresponding type to all
110 // modes in "this" that do not exist in VVT.
111 if (Modes.count(DefaultMode)) {
112 MVT DT = VVT.getType(DefaultMode);
113 for (auto &I : *this)
114 if (!Modes.count(I.first))
115 Changed |= I.second.insert(DT).second;
116 }
117
118 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000119}
120
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000121// Constrain the type set to be the intersection with VTS.
122bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
123 bool Changed = false;
124 if (hasDefault()) {
125 for (const auto &I : VTS) {
126 unsigned M = I.first;
127 if (M == DefaultMode || hasMode(M))
128 continue;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000129 Map.insert({M, Map.at(DefaultMode)});
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000130 Changed = true;
131 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000132 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000133
134 for (auto &I : *this) {
135 unsigned M = I.first;
136 SetType &S = I.second;
137 if (VTS.hasMode(M) || VTS.hasDefault()) {
138 Changed |= intersect(I.second, VTS.get(M));
139 } else if (!S.empty()) {
140 S.clear();
141 Changed = true;
142 }
143 }
144 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000145}
146
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000147template <typename Predicate>
148bool TypeSetByHwMode::constrain(Predicate P) {
149 bool Changed = false;
150 for (auto &I : *this)
Benjamin Kramere57308e2017-09-17 11:19:53 +0000151 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000152 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000153}
154
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000155template <typename Predicate>
156bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
157 assert(empty());
158 for (const auto &I : VTS) {
159 SetType &S = getOrCreate(I.first);
160 for (auto J : I.second)
161 if (P(J))
162 S.insert(J);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000163 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000164 return !empty();
Chris Lattnercabe0372010-03-15 06:00:16 +0000165}
166
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000167std::string TypeSetByHwMode::getAsString() const {
168 std::stringstream str;
169 std::vector<unsigned> Modes;
Chris Lattnercabe0372010-03-15 06:00:16 +0000170
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000171 for (const auto &I : *this)
172 Modes.push_back(I.first);
173 if (Modes.empty())
174 return "{}";
175 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000176
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000177 str << '{';
178 for (unsigned M : Modes) {
179 const SetType &S = get(M);
180 str << ' ' << getModeName(M) << ':' << getAsString(S);
181 }
182 str << " }";
183 return str.str();
184}
185
186std::string TypeSetByHwMode::getAsString(const SetType &S) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000187 std::vector<MVT> Types;
188 for (MVT T : S)
189 Types.push_back(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000190 array_pod_sort(Types.begin(), Types.end());
191
192 std::stringstream str;
193 str << '[';
194 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
195 str << ValueTypeByHwMode::getMVTName(Types[i]);
196 if (i != e-1)
197 str << ' ';
198 }
199 str << ']';
200 return str.str();
201}
202
203bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
204 bool HaveDefault = hasDefault();
205 if (HaveDefault != VTS.hasDefault())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000206 return false;
207
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000208 if (isSimple()) {
209 if (VTS.isSimple())
210 return *begin() == *VTS.begin();
211 return false;
212 }
213
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000214 std::set<unsigned> Modes;
215 for (auto &I : *this)
216 Modes.insert(I.first);
217 for (const auto &I : VTS)
218 Modes.insert(I.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000219
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000220 if (HaveDefault) {
221 // Both sets have default mode.
222 for (unsigned M : Modes) {
223 if (get(M) != VTS.get(M))
David Majnemerc7004902016-08-12 04:32:37 +0000224 return false;
Craig Topper5712d462015-11-24 08:20:47 +0000225 }
Scott Michel94420742008-03-05 17:49:05 +0000226 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000227 // Neither set has default mode.
228 for (unsigned M : Modes) {
229 // If there is no default mode, an empty set is equivalent to not having
230 // the corresponding mode.
231 bool NoModeThis = !hasMode(M) || get(M).empty();
232 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
233 if (NoModeThis != NoModeVTS)
234 return false;
235 if (!NoModeThis)
236 if (get(M) != VTS.get(M))
237 return false;
238 }
Scott Michel94420742008-03-05 17:49:05 +0000239 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000240
241 return true;
Scott Michel94420742008-03-05 17:49:05 +0000242}
243
Krzysztof Parzyszek426bf362017-09-12 15:31:26 +0000244LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000245void TypeSetByHwMode::dump() const {
246 dbgs() << getAsString() << '\n';
247}
248
249bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
250 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
251 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
252
253 if (OutP == InP)
254 return berase_if(Out, Int);
255
256 // Compute the intersection of scalars separately to account for only
257 // one set containing iPTR.
258 // The itersection of iPTR with a set of integer scalar types that does not
259 // include iPTR will result in the most specific scalar type:
260 // - iPTR is more specific than any set with two elements or more
261 // - iPTR is less specific than any single integer scalar type.
262 // For example
263 // { iPTR } * { i32 } -> { i32 }
264 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000265 // and
266 // { iPTR i32 } * { i32 } -> { i32 }
267 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
268 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000269
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000270 // Compute the difference between the two sets in such a way that the
271 // iPTR is in the set that is being subtracted. This is to see if there
272 // are any extra scalars in the set without iPTR that are not in the
273 // set containing iPTR. Then the iPTR could be considered a "wildcard"
274 // matching these scalars. If there is only one such scalar, it would
275 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000276 SetType Diff;
277 if (InP) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000278 Diff = Out;
279 berase_if(Diff, [&In](MVT T) { return In.count(T); });
280 // Pre-remove these elements and rely only on InP/OutP to determine
281 // whether a change has been made.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000282 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000283 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000284 Diff = In;
285 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000286 Out.erase(MVT::iPTR);
287 }
288
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000289 // The actual intersection.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000290 bool Changed = berase_if(Out, Int);
291 unsigned NumD = Diff.size();
292 if (NumD == 0)
293 return Changed;
294
295 if (NumD == 1) {
296 Out.insert(*Diff.begin());
297 // This is a change only if Out was the one with iPTR (which is now
298 // being replaced).
299 Changed |= OutP;
300 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000301 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000302 Out.insert(MVT::iPTR);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000303 Changed |= !OutP;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000304 }
305 return Changed;
306}
307
308void TypeSetByHwMode::validate() const {
309#ifndef NDEBUG
310 if (empty())
311 return;
312 bool AllEmpty = true;
313 for (const auto &I : *this)
314 AllEmpty &= I.second.empty();
315 assert(!AllEmpty &&
316 "type set is empty for each HW mode: type contradiction?");
317#endif
318}
319
320// --- TypeInfer
321
322bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
323 const TypeSetByHwMode &In) {
324 ValidateOnExit _1(Out);
325 In.validate();
326 if (In.empty() || Out == In || TP.hasError())
327 return false;
328 if (Out.empty()) {
329 Out = In;
330 return true;
331 }
332
333 bool Changed = Out.constrain(In);
334 if (Changed && Out.empty())
335 TP.error("Type contradiction");
336
337 return Changed;
338}
339
340bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
341 ValidateOnExit _1(Out);
342 if (TP.hasError())
343 return false;
344 assert(!Out.empty() && "cannot pick from an empty set");
345
346 bool Changed = false;
347 for (auto &I : Out) {
348 TypeSetByHwMode::SetType &S = I.second;
349 if (S.size() <= 1)
350 continue;
351 MVT T = *S.begin(); // Pick the first element.
352 S.clear();
353 S.insert(T);
354 Changed = true;
355 }
356 return Changed;
357}
358
359bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
360 ValidateOnExit _1(Out);
361 if (TP.hasError())
362 return false;
363 if (!Out.empty())
364 return Out.constrain(isIntegerOrPtr);
365
366 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
367}
368
369bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
370 ValidateOnExit _1(Out);
371 if (TP.hasError())
372 return false;
373 if (!Out.empty())
374 return Out.constrain(isFloatingPoint);
375
376 return Out.assign_if(getLegalTypes(), isFloatingPoint);
377}
378
379bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
380 ValidateOnExit _1(Out);
381 if (TP.hasError())
382 return false;
383 if (!Out.empty())
384 return Out.constrain(isScalar);
385
386 return Out.assign_if(getLegalTypes(), isScalar);
387}
388
389bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
390 ValidateOnExit _1(Out);
391 if (TP.hasError())
392 return false;
393 if (!Out.empty())
394 return Out.constrain(isVector);
395
396 return Out.assign_if(getLegalTypes(), isVector);
397}
398
399bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
400 ValidateOnExit _1(Out);
401 if (TP.hasError() || !Out.empty())
402 return false;
403
404 Out = getLegalTypes();
405 return true;
406}
407
408template <typename Iter, typename Pred, typename Less>
409static Iter min_if(Iter B, Iter E, Pred P, Less L) {
410 if (B == E)
411 return E;
412 Iter Min = E;
413 for (Iter I = B; I != E; ++I) {
414 if (!P(*I))
415 continue;
416 if (Min == E || L(*I, *Min))
417 Min = I;
418 }
419 return Min;
420}
421
422template <typename Iter, typename Pred, typename Less>
423static Iter max_if(Iter B, Iter E, Pred P, Less L) {
424 if (B == E)
425 return E;
426 Iter Max = E;
427 for (Iter I = B; I != E; ++I) {
428 if (!P(*I))
429 continue;
430 if (Max == E || L(*Max, *I))
431 Max = I;
432 }
433 return Max;
434}
435
436/// Make sure that for each type in Small, there exists a larger type in Big.
437bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
438 TypeSetByHwMode &Big) {
439 ValidateOnExit _1(Small), _2(Big);
440 if (TP.hasError())
441 return false;
442 bool Changed = false;
443
444 if (Small.empty())
445 Changed |= EnforceAny(Small);
446 if (Big.empty())
447 Changed |= EnforceAny(Big);
448
449 assert(Small.hasDefault() && Big.hasDefault());
450
451 std::vector<unsigned> Modes = union_modes(Small, Big);
452
453 // 1. Only allow integer or floating point types and make sure that
454 // both sides are both integer or both floating point.
455 // 2. Make sure that either both sides have vector types, or neither
456 // of them does.
457 for (unsigned M : Modes) {
458 TypeSetByHwMode::SetType &S = Small.get(M);
459 TypeSetByHwMode::SetType &B = Big.get(M);
460
461 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000462 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000463 Changed |= berase_if(S, NotInt) |
464 berase_if(B, NotInt);
465 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000466 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000467 Changed |= berase_if(S, NotFP) |
468 berase_if(B, NotFP);
469 } else if (S.empty() || B.empty()) {
470 Changed = !S.empty() || !B.empty();
471 S.clear();
472 B.clear();
473 } else {
474 TP.error("Incompatible types");
475 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000476 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000477
478 if (none_of(S, isVector) || none_of(B, isVector)) {
479 Changed |= berase_if(S, isVector) |
480 berase_if(B, isVector);
481 }
482 }
483
484 auto LT = [](MVT A, MVT B) -> bool {
485 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
486 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
487 A.getSizeInBits() < B.getSizeInBits());
488 };
489 auto LE = [](MVT A, MVT B) -> bool {
490 // This function is used when removing elements: when a vector is compared
491 // to a non-vector, it should return false (to avoid removal).
492 if (A.isVector() != B.isVector())
493 return false;
494
495 // Note on the < comparison below:
496 // X86 has patterns like
497 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
498 // where the truncated vector is given a type v16i8, while the source
499 // vector has type v4i32. They both have the same size in bits.
500 // The minimal type in the result is obviously v16i8, and when we remove
501 // all types from the source that are smaller-or-equal than v8i16, the
502 // only source type would also be removed (since it's equal in size).
503 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
504 A.getSizeInBits() < B.getSizeInBits();
505 };
506
507 for (unsigned M : Modes) {
508 TypeSetByHwMode::SetType &S = Small.get(M);
509 TypeSetByHwMode::SetType &B = Big.get(M);
510 // MinS = min scalar in Small, remove all scalars from Big that are
511 // smaller-or-equal than MinS.
512 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
513 if (MinS != S.end()) {
514 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
515 if (B.empty()) {
516 TP.error("Type contradiction in " +
517 Twine(__func__) + ":" + Twine(__LINE__));
518 return Changed;
519 }
520 }
521 // MaxS = max scalar in Big, remove all scalars from Small that are
522 // larger than MaxS.
523 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
524 if (MaxS != B.end()) {
525 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
526 if (B.empty()) {
527 TP.error("Type contradiction in " +
528 Twine(__func__) + ":" + Twine(__LINE__));
529 return Changed;
530 }
531 }
532
533 // MinV = min vector in Small, remove all vectors from Big that are
534 // smaller-or-equal than MinV.
535 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
536 if (MinV != S.end()) {
537 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
538 if (B.empty()) {
539 TP.error("Type contradiction in " +
540 Twine(__func__) + ":" + Twine(__LINE__));
541 return Changed;
542 }
543 }
544 // MaxV = max vector in Big, remove all vectors from Small that are
545 // larger than MaxV.
546 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
547 if (MaxV != B.end()) {
548 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
549 if (B.empty()) {
550 TP.error("Type contradiction in " +
551 Twine(__func__) + ":" + Twine(__LINE__));
552 return Changed;
553 }
554 }
555 }
556
557 return Changed;
558}
559
560/// 1. Ensure that for each type T in Vec, T is a vector type, and that
561/// for each type U in Elem, U is a scalar type.
562/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
563/// type T in Vec, such that U is the element type of T.
564bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
565 TypeSetByHwMode &Elem) {
566 ValidateOnExit _1(Vec), _2(Elem);
567 if (TP.hasError())
568 return false;
569 bool Changed = false;
570
571 if (Vec.empty())
572 Changed |= EnforceVector(Vec);
573 if (Elem.empty())
574 Changed |= EnforceScalar(Elem);
575
576 for (unsigned M : union_modes(Vec, Elem)) {
577 TypeSetByHwMode::SetType &V = Vec.get(M);
578 TypeSetByHwMode::SetType &E = Elem.get(M);
579
580 Changed |= berase_if(V, isScalar); // Scalar = !vector
581 Changed |= berase_if(E, isVector); // Vector = !scalar
582 assert(!V.empty() && !E.empty());
583
584 SmallSet<MVT,4> VT, ST;
585 // Collect element types from the "vector" set.
586 for (MVT T : V)
587 VT.insert(T.getVectorElementType());
588 // Collect scalar types from the "element" set.
589 for (MVT T : E)
590 ST.insert(T);
591
592 // Remove from V all (vector) types whose element type is not in S.
593 Changed |= berase_if(V, [&ST](MVT T) -> bool {
594 return !ST.count(T.getVectorElementType());
595 });
596 // Remove from E all (scalar) types, for which there is no corresponding
597 // type in V.
598 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
599
600 if (V.empty() || E.empty()) {
601 TP.error("Type contradiction in " +
602 Twine(__func__) + ":" + Twine(__LINE__));
603 return Changed;
604 }
605 }
606
607 return Changed;
608}
609
610bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
611 const ValueTypeByHwMode &VVT) {
612 TypeSetByHwMode Tmp(VVT);
613 ValidateOnExit _1(Vec), _2(Tmp);
614 return EnforceVectorEltTypeIs(Vec, Tmp);
615}
616
617/// Ensure that for each type T in Sub, T is a vector type, and there
618/// exists a type U in Vec such that U is a vector type with the same
619/// element type as T and at least as many elements as T.
620bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
621 TypeSetByHwMode &Sub) {
622 ValidateOnExit _1(Vec), _2(Sub);
623 if (TP.hasError())
624 return false;
625
626 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
627 auto IsSubVec = [](MVT B, MVT P) -> bool {
628 if (!B.isVector() || !P.isVector())
629 return false;
630 if (B.getVectorElementType() != P.getVectorElementType())
631 return false;
632 return B.getVectorNumElements() < P.getVectorNumElements();
633 };
634
635 /// Return true if S has no element (vector type) that T is a sub-vector of,
636 /// i.e. has the same element type as T and more elements.
637 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
638 for (const auto &I : S)
639 if (IsSubVec(T, I))
640 return false;
641 return true;
642 };
643
644 /// Return true if S has no element (vector type) that T is a super-vector
645 /// of, i.e. has the same element type as T and fewer elements.
646 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
647 for (const auto &I : S)
648 if (IsSubVec(I, T))
649 return false;
650 return true;
651 };
652
653 bool Changed = false;
654
655 if (Vec.empty())
656 Changed |= EnforceVector(Vec);
657 if (Sub.empty())
658 Changed |= EnforceVector(Sub);
659
660 for (unsigned M : union_modes(Vec, Sub)) {
661 TypeSetByHwMode::SetType &S = Sub.get(M);
662 TypeSetByHwMode::SetType &V = Vec.get(M);
663
664 Changed |= berase_if(S, isScalar);
665 if (S.empty()) {
666 TP.error("Type contradiction in " +
667 Twine(__func__) + ":" + Twine(__LINE__));
668 return Changed;
669 }
670
671 // Erase all types from S that are not sub-vectors of a type in V.
672 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
673 if (S.empty()) {
674 TP.error("Type contradiction in " +
675 Twine(__func__) + ":" + Twine(__LINE__));
676 return Changed;
677 }
678
679 // Erase all types from V that are not super-vectors of a type in S.
680 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
681 if (V.empty()) {
682 TP.error("Type contradiction in " +
683 Twine(__func__) + ":" + Twine(__LINE__));
684 return Changed;
685 }
686 }
687
688 return Changed;
689}
690
691/// 1. Ensure that V has a scalar type iff W has a scalar type.
692/// 2. Ensure that for each vector type T in V, there exists a vector
693/// type U in W, such that T and U have the same number of elements.
694/// 3. Ensure that for each vector type U in W, there exists a vector
695/// type T in V, such that T and U have the same number of elements
696/// (reverse of 2).
697bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
698 ValidateOnExit _1(V), _2(W);
699 if (TP.hasError())
700 return false;
701
702 bool Changed = false;
703 if (V.empty())
704 Changed |= EnforceAny(V);
705 if (W.empty())
706 Changed |= EnforceAny(W);
707
708 // An actual vector type cannot have 0 elements, so we can treat scalars
709 // as zero-length vectors. This way both vectors and scalars can be
710 // processed identically.
711 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
712 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
713 };
714
715 for (unsigned M : union_modes(V, W)) {
716 TypeSetByHwMode::SetType &VS = V.get(M);
717 TypeSetByHwMode::SetType &WS = W.get(M);
718
719 SmallSet<unsigned,2> VN, WN;
720 for (MVT T : VS)
721 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
722 for (MVT T : WS)
723 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
724
725 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
726 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
727 }
728 return Changed;
729}
730
731/// 1. Ensure that for each type T in A, there exists a type U in B,
732/// such that T and U have equal size in bits.
733/// 2. Ensure that for each type U in B, there exists a type T in A
734/// such that T and U have equal size in bits (reverse of 1).
735bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
736 ValidateOnExit _1(A), _2(B);
737 if (TP.hasError())
738 return false;
739 bool Changed = false;
740 if (A.empty())
741 Changed |= EnforceAny(A);
742 if (B.empty())
743 Changed |= EnforceAny(B);
744
745 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
746 return !Sizes.count(T.getSizeInBits());
747 };
748
749 for (unsigned M : union_modes(A, B)) {
750 TypeSetByHwMode::SetType &AS = A.get(M);
751 TypeSetByHwMode::SetType &BS = B.get(M);
752 SmallSet<unsigned,2> AN, BN;
753
754 for (MVT T : AS)
755 AN.insert(T.getSizeInBits());
756 for (MVT T : BS)
757 BN.insert(T.getSizeInBits());
758
759 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
760 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
761 }
762
763 return Changed;
764}
765
766void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
767 ValidateOnExit _1(VTS);
768 TypeSetByHwMode Legal = getLegalTypes();
769 bool HaveLegalDef = Legal.hasDefault();
770
771 for (auto &I : VTS) {
772 unsigned M = I.first;
773 if (!Legal.hasMode(M) && !HaveLegalDef) {
774 TP.error("Invalid mode " + Twine(M));
775 return;
776 }
777 expandOverloads(I.second, Legal.get(M));
Scott Michel94420742008-03-05 17:49:05 +0000778 }
779}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000780
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000781void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
782 const TypeSetByHwMode::SetType &Legal) {
783 std::set<MVT> Ovs;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000784 for (MVT T : Out) {
785 if (!T.isOverloaded())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000786 continue;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000787 Ovs.insert(T);
788 // MachineValueTypeSet allows iteration and erasing.
789 Out.erase(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000790 }
791
792 for (MVT Ov : Ovs) {
793 switch (Ov.SimpleTy) {
794 case MVT::iPTRAny:
795 Out.insert(MVT::iPTR);
796 return;
797 case MVT::iAny:
798 for (MVT T : MVT::integer_valuetypes())
799 if (Legal.count(T))
800 Out.insert(T);
801 for (MVT T : MVT::integer_vector_valuetypes())
802 if (Legal.count(T))
803 Out.insert(T);
804 return;
805 case MVT::fAny:
806 for (MVT T : MVT::fp_valuetypes())
807 if (Legal.count(T))
808 Out.insert(T);
809 for (MVT T : MVT::fp_vector_valuetypes())
810 if (Legal.count(T))
811 Out.insert(T);
812 return;
813 case MVT::vAny:
814 for (MVT T : MVT::vector_valuetypes())
815 if (Legal.count(T))
816 Out.insert(T);
817 return;
818 case MVT::Any:
819 for (MVT T : MVT::all_valuetypes())
820 if (Legal.count(T))
821 Out.insert(T);
822 return;
823 default:
824 break;
825 }
826 }
827}
828
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000829TypeSetByHwMode TypeInfer::getLegalTypes() {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000830 if (!LegalTypesCached) {
831 // Stuff all types from all modes into the default mode.
832 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
833 for (const auto &I : LTS)
834 LegalCache.insert(I.second);
835 LegalTypesCached = true;
836 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000837 TypeSetByHwMode VTS;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000838 VTS.getOrCreate(DefaultMode) = LegalCache;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000839 return VTS;
840}
Chris Lattner514e2922011-04-17 21:38:24 +0000841
842//===----------------------------------------------------------------------===//
843// TreePredicateFn Implementation
844//===----------------------------------------------------------------------===//
845
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000846/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
847TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
848 assert((getPredCode().empty() || getImmCode().empty()) &&
849 ".td file corrupt: can't have a node predicate *and* an imm predicate");
850}
851
Chris Lattner514e2922011-04-17 21:38:24 +0000852std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000853 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000854}
855
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000856std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000857 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000858}
859
Chris Lattner514e2922011-04-17 21:38:24 +0000860
861/// isAlwaysTrue - Return true if this is a noop predicate.
862bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000863 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000864}
865
866/// Return the name to use in the generated code to reference this, this is
867/// "Predicate_foo" if from a pattern fragment "foo".
868std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +0000869 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +0000870}
871
872/// getCodeToRunOnSDNode - Return the code for the function body that
873/// evaluates this predicate. The argument is expected to be in "Node",
874/// not N. This handles casting and conversion to a concrete node type as
875/// appropriate.
876std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000877 // Handle immediate predicates first.
878 std::string ImmCode = getImmCode();
879 if (!ImmCode.empty()) {
880 std::string Result =
881 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000882 return Result + ImmCode;
883 }
884
885 // Handle arbitrary node predicates.
886 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000887 std::string ClassName;
888 if (PatFragRec->getOnlyTree()->isLeaf())
889 ClassName = "SDNode";
890 else {
891 Record *Op = PatFragRec->getOnlyTree()->getOperator();
892 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
893 }
894 std::string Result;
895 if (ClassName == "SDNode")
896 Result = " SDNode *N = Node;\n";
897 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000898 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000899
900 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000901}
902
Chris Lattner8cab0212008-01-05 22:25:12 +0000903//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000904// PatternToMatch implementation
905//
906
Chris Lattner05925fe2010-03-29 01:40:38 +0000907/// getPatternSize - Return the 'size' of this pattern. We want to match large
908/// patterns before small ones. This is used to determine the size of a
909/// pattern.
910static unsigned getPatternSize(const TreePatternNode *P,
911 const CodeGenDAGPatterns &CGP) {
912 unsigned Size = 3; // The node itself.
913 // If the root node is a ConstantSDNode, increases its size.
914 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000915 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000916 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000917
Chris Lattner05925fe2010-03-29 01:40:38 +0000918 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000919 if (AM) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000920 Size += AM->getComplexity();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000921
Tim Northoverc807a172014-05-20 11:52:46 +0000922 // We don't want to count any children twice, so return early.
923 return Size;
924 }
925
Chris Lattner05925fe2010-03-29 01:40:38 +0000926 // If this node has some predicate function that must match, it adds to the
927 // complexity of this node.
928 if (!P->getPredicateFns().empty())
929 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000930
Chris Lattner05925fe2010-03-29 01:40:38 +0000931 // Count children in the count if they are also nodes.
932 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
933 TreePatternNode *Child = P->getChild(i);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000934 if (!Child->isLeaf() && Child->getNumTypes()) {
935 const TypeSetByHwMode &T0 = Child->getType(0);
936 // At this point, all variable type sets should be simple, i.e. only
937 // have a default mode.
938 if (T0.getMachineValueType() != MVT::Other) {
939 Size += getPatternSize(Child, CGP);
940 continue;
941 }
942 }
943 if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000944 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000945 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
946 else if (Child->getComplexPatternInfo(CGP))
947 Size += getPatternSize(Child, CGP);
948 else if (!Child->getPredicateFns().empty())
949 ++Size;
950 }
951 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000952
Chris Lattner05925fe2010-03-29 01:40:38 +0000953 return Size;
954}
955
956/// Compute the complexity metric for the input pattern. This roughly
957/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000958int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000959getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
960 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
961}
962
Dan Gohman49e19e92008-08-22 00:20:26 +0000963/// getPredicateCheck - Return a single string containing all of this
964/// pattern's predicates concatenated with "&&" operators.
965///
966std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000967 SmallVector<const Predicate*,4> PredList;
968 for (const Predicate &P : Predicates)
969 PredList.push_back(&P);
970 std::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +0000971
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000972 std::string Check;
973 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
974 if (i != 0)
975 Check += " && ";
976 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +0000977 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000978 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +0000979}
980
981//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000982// SDTypeConstraint implementation
983//
984
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000985SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000986 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000987
Chris Lattner8cab0212008-01-05 22:25:12 +0000988 if (R->isSubClassOf("SDTCisVT")) {
989 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000990 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
991 for (const auto &P : VVT)
992 if (P.second == MVT::isVoid)
993 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +0000994 } else if (R->isSubClassOf("SDTCisPtrTy")) {
995 ConstraintType = SDTCisPtrTy;
996 } else if (R->isSubClassOf("SDTCisInt")) {
997 ConstraintType = SDTCisInt;
998 } else if (R->isSubClassOf("SDTCisFP")) {
999 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001000 } else if (R->isSubClassOf("SDTCisVec")) {
1001 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001002 } else if (R->isSubClassOf("SDTCisSameAs")) {
1003 ConstraintType = SDTCisSameAs;
1004 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1005 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1006 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001007 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001008 R->getValueAsInt("OtherOperandNum");
1009 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1010 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001011 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001012 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001013 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1014 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001015 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001016 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1017 ConstraintType = SDTCisSubVecOfVec;
1018 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1019 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001020 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1021 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001022 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1023 for (const auto &P : VVT) {
1024 MVT T = P.second;
1025 if (T.isVector())
1026 PrintFatalError(R->getLoc(),
1027 "Cannot use vector type as SDTCVecEltisVT");
1028 if (!T.isInteger() && !T.isFloatingPoint())
1029 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1030 "as SDTCVecEltisVT");
1031 }
Craig Topper0be34582015-03-05 07:11:34 +00001032 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1033 ConstraintType = SDTCisSameNumEltsAs;
1034 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1035 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001036 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1037 ConstraintType = SDTCisSameSizeAs;
1038 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1039 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001040 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001041 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001042 }
1043}
1044
1045/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001046/// N, and the result number in ResNo.
1047static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1048 const SDNodeInfo &NodeInfo,
1049 unsigned &ResNo) {
1050 unsigned NumResults = NodeInfo.getNumResults();
1051 if (OpNo < NumResults) {
1052 ResNo = OpNo;
1053 return N;
1054 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001055
Chris Lattner2db7aba2010-03-19 21:56:21 +00001056 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001057
Chris Lattner2db7aba2010-03-19 21:56:21 +00001058 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001059 std::string S;
1060 raw_string_ostream OS(S);
1061 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001062 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +00001063 N->print(OS);
1064 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001065 }
1066
Chris Lattner2db7aba2010-03-19 21:56:21 +00001067 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001068}
1069
1070/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1071/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001072/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001073bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1074 const SDNodeInfo &NodeInfo,
1075 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001076 if (TP.hasError())
1077 return false;
1078
Chris Lattner2db7aba2010-03-19 21:56:21 +00001079 unsigned ResNo = 0; // The result number being referenced.
1080 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001081 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001082
Chris Lattner8cab0212008-01-05 22:25:12 +00001083 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001084 case SDTCisVT:
1085 // Operand must be a particular type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001086 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001087 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001088 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001089 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001090 case SDTCisInt:
1091 // Require it to be one of the legal integer VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001092 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001093 case SDTCisFP:
1094 // Require it to be one of the legal fp VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001095 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001096 case SDTCisVec:
1097 // Require it to be one of the legal vector VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001098 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001099 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001100 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001101 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001102 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001103 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1104 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001105 }
1106 case SDTCisVTSmallerThanOp: {
1107 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1108 // have an integer type that is smaller than the VT.
1109 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001110 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001111 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001112 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001113 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001114 return false;
1115 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001116 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1117 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1118 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1119 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001120
Chris Lattner2db7aba2010-03-19 21:56:21 +00001121 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001122 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001123 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1124 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001125
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001126 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001127 }
1128 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001129 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001130 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001131 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1132 BResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001133 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1134 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001135 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001136 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001137 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001138 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001139 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1140 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001141 // Filter vector types out of VecOperand that don't have the right element
1142 // type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001143 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1144 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001145 }
David Greene127fd1d2011-01-24 20:53:18 +00001146 case SDTCisSubVecOfVec: {
1147 unsigned VResNo = 0;
1148 TreePatternNode *BigVecOperand =
1149 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1150 VResNo);
1151
1152 // Filter vector types out of BigVecOperand that don't have the
1153 // right subvector type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001154 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1155 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001156 }
Craig Topper0be34582015-03-05 07:11:34 +00001157 case SDTCVecEltisVT: {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001158 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001159 }
1160 case SDTCisSameNumEltsAs: {
1161 unsigned OResNo = 0;
1162 TreePatternNode *OtherNode =
1163 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1164 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001165 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1166 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001167 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001168 case SDTCisSameSizeAs: {
1169 unsigned OResNo = 0;
1170 TreePatternNode *OtherNode =
1171 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1172 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001173 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1174 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001175 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001176 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001177 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001178}
1179
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001180// Update the node type to match an instruction operand or result as specified
1181// in the ins or outs lists on the instruction definition. Return true if the
1182// type was actually changed.
1183bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1184 Record *Operand,
1185 TreePattern &TP) {
1186 // The 'unknown' operand indicates that types should be inferred from the
1187 // context.
1188 if (Operand->isSubClassOf("unknown_class"))
1189 return false;
1190
1191 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001192 if (Operand->isSubClassOf("Operand")) {
1193 Record *R = Operand->getValueAsDef("Type");
1194 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1195 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1196 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001197
1198 // PointerLikeRegClass has a type that is determined at runtime.
1199 if (Operand->isSubClassOf("PointerLikeRegClass"))
1200 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1201
1202 // Both RegisterClass and RegisterOperand operands derive their types from a
1203 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001204 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001205 if (Operand->isSubClassOf("RegisterClass"))
1206 RC = Operand;
1207 else if (Operand->isSubClassOf("RegisterOperand"))
1208 RC = Operand->getValueAsDef("RegClass");
1209
1210 assert(RC && "Unknown operand type");
1211 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1212 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1213}
1214
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001215bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1216 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1217 if (!TP.getInfer().isConcrete(Types[i], true))
1218 return true;
1219 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1220 if (getChild(i)->ContainsUnresolvedType(TP))
1221 return true;
1222 return false;
1223}
1224
1225bool TreePatternNode::hasProperTypeByHwMode() const {
1226 for (const TypeSetByHwMode &S : Types)
1227 if (!S.isDefaultOnly())
1228 return true;
1229 for (TreePatternNode *C : Children)
1230 if (C->hasProperTypeByHwMode())
1231 return true;
1232 return false;
1233}
1234
1235bool TreePatternNode::hasPossibleType() const {
1236 for (const TypeSetByHwMode &S : Types)
1237 if (!S.isPossible())
1238 return false;
1239 for (TreePatternNode *C : Children)
1240 if (!C->hasPossibleType())
1241 return false;
1242 return true;
1243}
1244
1245bool TreePatternNode::setDefaultMode(unsigned Mode) {
1246 for (TypeSetByHwMode &S : Types) {
1247 S.makeSimple(Mode);
1248 // Check if the selected mode had a type conflict.
1249 if (S.get(DefaultMode).empty())
1250 return false;
1251 }
1252 for (TreePatternNode *C : Children)
1253 if (!C->setDefaultMode(Mode))
1254 return false;
1255 return true;
1256}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001257
Chris Lattner8cab0212008-01-05 22:25:12 +00001258//===----------------------------------------------------------------------===//
1259// SDNodeInfo implementation
1260//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001261SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001262 EnumName = R->getValueAsString("Opcode");
1263 SDClassName = R->getValueAsString("SDClass");
1264 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1265 NumResults = TypeProfile->getValueAsInt("NumResults");
1266 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001267
Chris Lattner8cab0212008-01-05 22:25:12 +00001268 // Parse the properties.
1269 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001270 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1271 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001272 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001273 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001274 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001275 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001276 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001277 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001278 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001279 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001280 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001281 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001282 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001283 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001284 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001285 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001286 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001287 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001288 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001289 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001290 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001291 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001292 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001293 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001294 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001295 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001296 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001297 }
1298 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001299
1300
Chris Lattner8cab0212008-01-05 22:25:12 +00001301 // Parse the type constraints.
1302 std::vector<Record*> ConstraintList =
1303 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001304 for (Record *R : ConstraintList)
1305 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001306}
1307
Chris Lattner99e53b32010-02-28 00:22:30 +00001308/// getKnownType - If the type constraints on this node imply a fixed type
1309/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001310/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001311MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001312 unsigned NumResults = getNumResults();
1313 assert(NumResults <= 1 &&
1314 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001315 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001316
Craig Topper306cb122015-11-22 20:46:24 +00001317 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001318 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001319 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001320 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001321
Craig Topper306cb122015-11-22 20:46:24 +00001322 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001323 default: break;
1324 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001325 if (Constraint.VVT.isSimple())
1326 return Constraint.VVT.getSimple().SimpleTy;
1327 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001328 case SDTypeConstraint::SDTCisPtrTy:
1329 return MVT::iPTR;
1330 }
1331 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001332 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001333}
1334
Chris Lattner8cab0212008-01-05 22:25:12 +00001335//===----------------------------------------------------------------------===//
1336// TreePatternNode implementation
1337//
1338
1339TreePatternNode::~TreePatternNode() {
1340#if 0 // FIXME: implement refcounted tree nodes!
1341 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1342 delete getChild(i);
1343#endif
1344}
1345
Chris Lattnerf1447252010-03-19 21:37:09 +00001346static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1347 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001348 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001349 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001350
Chris Lattner2109cb42010-03-22 20:56:36 +00001351 if (Operator->isSubClassOf("Intrinsic"))
1352 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001353
Chris Lattnerf1447252010-03-19 21:37:09 +00001354 if (Operator->isSubClassOf("SDNode"))
1355 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001356
Chris Lattnerf1447252010-03-19 21:37:09 +00001357 if (Operator->isSubClassOf("PatFrag")) {
1358 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1359 // the forward reference case where one pattern fragment references another
1360 // before it is processed.
1361 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1362 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001363
Chris Lattnerf1447252010-03-19 21:37:09 +00001364 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001365 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001366 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001367 if (Tree)
1368 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1369 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001370 assert(Op && "Invalid Fragment");
1371 return GetNumNodeResults(Op, CDP);
1372 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001373
Chris Lattnerf1447252010-03-19 21:37:09 +00001374 if (Operator->isSubClassOf("Instruction")) {
1375 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001376
Craig Topper3a8eb892015-03-20 05:09:06 +00001377 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1378
1379 // Subtract any defaulted outputs.
1380 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1381 Record *OperandNode = InstInfo.Operands[i].Rec;
1382
1383 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1384 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1385 --NumDefsToAdd;
1386 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001387
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001388 // Add on one implicit def if it has a resolvable type.
1389 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1390 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001391 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001392 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001393
Chris Lattnerf1447252010-03-19 21:37:09 +00001394 if (Operator->isSubClassOf("SDNodeXForm"))
1395 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001396
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001397 if (Operator->isSubClassOf("ValueType"))
1398 return 1; // A type-cast of one result.
1399
Tim Northoverc807a172014-05-20 11:52:46 +00001400 if (Operator->isSubClassOf("ComplexPattern"))
1401 return 1;
1402
Matthias Braun8c209aa2017-01-28 02:02:38 +00001403 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001404 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001405}
1406
1407void TreePatternNode::print(raw_ostream &OS) const {
1408 if (isLeaf())
1409 OS << *getLeafValue();
1410 else
1411 OS << '(' << getOperator()->getName();
1412
1413 for (unsigned i = 0, e = Types.size(); i != e; ++i)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001414 OS << ':' << getExtType(i).getAsString();
Chris Lattner8cab0212008-01-05 22:25:12 +00001415
1416 if (!isLeaf()) {
1417 if (getNumChildren() != 0) {
1418 OS << " ";
1419 getChild(0)->print(OS);
1420 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1421 OS << ", ";
1422 getChild(i)->print(OS);
1423 }
1424 }
1425 OS << ")";
1426 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001427
Craig Topper306cb122015-11-22 20:46:24 +00001428 for (const TreePredicateFn &Pred : PredicateFns)
1429 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001430 if (TransformFn)
1431 OS << "<<X:" << TransformFn->getName() << ">>";
1432 if (!getName().empty())
1433 OS << ":$" << getName();
1434
1435}
1436void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001437 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001438}
1439
Scott Michel94420742008-03-05 17:49:05 +00001440/// isIsomorphicTo - Return true if this node is recursively
1441/// isomorphic to the specified node. For this comparison, the node's
1442/// entire state is considered. The assigned name is ignored, since
1443/// nodes with differing names are considered isomorphic. However, if
1444/// the assigned name is present in the dependent variable set, then
1445/// the assigned name is considered significant and the node is
1446/// isomorphic if the names match.
1447bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1448 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001449 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001450 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001451 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001452 getTransformFn() != N->getTransformFn())
1453 return false;
1454
1455 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001456 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1457 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001458 return ((DI->getDef() == NDI->getDef())
1459 && (DepVars.find(getName()) == DepVars.end()
1460 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001461 }
1462 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001463 return getLeafValue() == N->getLeafValue();
1464 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001465
Chris Lattner8cab0212008-01-05 22:25:12 +00001466 if (N->getOperator() != getOperator() ||
1467 N->getNumChildren() != getNumChildren()) return false;
1468 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001469 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001470 return false;
1471 return true;
1472}
1473
1474/// clone - Make a copy of this tree and all of its children.
1475///
1476TreePatternNode *TreePatternNode::clone() const {
1477 TreePatternNode *New;
1478 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001479 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001480 } else {
1481 std::vector<TreePatternNode*> CChildren;
1482 CChildren.reserve(Children.size());
1483 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1484 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001485 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001486 }
1487 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001488 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001489 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001490 New->setTransformFn(getTransformFn());
1491 return New;
1492}
1493
Chris Lattner53c39ba2010-02-14 22:22:58 +00001494/// RemoveAllTypes - Recursively strip all the types of this tree.
1495void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001496 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001497 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001498 if (isLeaf()) return;
1499 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1500 getChild(i)->RemoveAllTypes();
1501}
1502
1503
Chris Lattner8cab0212008-01-05 22:25:12 +00001504/// SubstituteFormalArguments - Replace the formal arguments in this tree
1505/// with actual values specified by ArgMap.
1506void TreePatternNode::
1507SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1508 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001509
Chris Lattner8cab0212008-01-05 22:25:12 +00001510 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1511 TreePatternNode *Child = getChild(i);
1512 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001513 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001514 // Note that, when substituting into an output pattern, Val might be an
1515 // UnsetInit.
1516 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1517 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001518 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001519 TreePatternNode *NewChild = ArgMap[Child->getName()];
1520 assert(NewChild && "Couldn't find formal argument!");
1521 assert((Child->getPredicateFns().empty() ||
1522 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1523 "Non-empty child predicate clobbered!");
1524 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001525 }
1526 } else {
1527 getChild(i)->SubstituteFormalArguments(ArgMap);
1528 }
1529 }
1530}
1531
1532
1533/// InlinePatternFragments - If this pattern refers to any pattern
1534/// fragments, inline them into place, giving us a pattern without any
1535/// PatFrag references.
1536TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001537 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001538 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001539
1540 if (isLeaf())
1541 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001542 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001543
Chris Lattner8cab0212008-01-05 22:25:12 +00001544 if (!Op->isSubClassOf("PatFrag")) {
1545 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001546 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1547 TreePatternNode *Child = getChild(i);
1548 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1549
1550 assert((Child->getPredicateFns().empty() ||
1551 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1552 "Non-empty child predicate clobbered!");
1553
1554 setChild(i, NewChild);
1555 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001556 return this;
1557 }
1558
1559 // Otherwise, we found a reference to a fragment. First, look up its
1560 // TreePattern record.
1561 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001562
Chris Lattner8cab0212008-01-05 22:25:12 +00001563 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001564 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001565 TP.error("'" + Op->getName() + "' fragment requires " +
1566 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001567 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001568 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001569
1570 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1571
Chris Lattner514e2922011-04-17 21:38:24 +00001572 TreePredicateFn PredFn(Frag);
1573 if (!PredFn.isAlwaysTrue())
1574 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001575
Chris Lattner8cab0212008-01-05 22:25:12 +00001576 // Resolve formal arguments to their actual value.
1577 if (Frag->getNumArgs()) {
1578 // Compute the map of formal to actual arguments.
1579 std::map<std::string, TreePatternNode*> ArgMap;
1580 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1581 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001582
Chris Lattner8cab0212008-01-05 22:25:12 +00001583 FragTree->SubstituteFormalArguments(ArgMap);
1584 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001585
Chris Lattner8cab0212008-01-05 22:25:12 +00001586 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001587 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1588 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001589
1590 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001591 for (const TreePredicateFn &Pred : getPredicateFns())
1592 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001593
Chris Lattner8cab0212008-01-05 22:25:12 +00001594 // Get a new copy of this fragment to stitch into here.
1595 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001596
Chris Lattner2e253b42008-06-30 03:02:03 +00001597 // The fragment we inlined could have recursive inlining that is needed. See
1598 // if there are any pattern fragments in it and inline them as needed.
1599 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001600}
1601
1602/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001603/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001604/// references from the register file information, for example.
1605///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001606/// When Unnamed is set, return the type of a DAG operand with no name, such as
1607/// the F8RC register class argument in:
1608///
1609/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1610///
1611/// When Unnamed is false, return the type of a named DAG operand such as the
1612/// GPR:$src operand above.
1613///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001614static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1615 bool NotRegisters,
1616 bool Unnamed,
1617 TreePattern &TP) {
1618 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1619
Owen Andersona84be6c2011-06-27 21:06:21 +00001620 // Check to see if this is a register operand.
1621 if (R->isSubClassOf("RegisterOperand")) {
1622 assert(ResNo == 0 && "Regoperand ref only has one result!");
1623 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001624 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00001625 Record *RegClass = R->getValueAsDef("RegClass");
1626 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001627 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00001628 }
1629
Chris Lattnercabe0372010-03-15 06:00:16 +00001630 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001631 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001632 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001633 // An unnamed register class represents itself as an i32 immediate, for
1634 // example on a COPY_TO_REGCLASS instruction.
1635 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001636 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001637
1638 // In a named operand, the register class provides the possible set of
1639 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001640 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001641 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00001642 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001643 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001644 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001645
Chris Lattner6070ee22010-03-23 23:50:31 +00001646 if (R->isSubClassOf("PatFrag")) {
1647 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001648 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001649 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001650 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001651
Chris Lattner6070ee22010-03-23 23:50:31 +00001652 if (R->isSubClassOf("Register")) {
1653 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001654 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001655 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001656 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001657 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001658 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001659
1660 if (R->isSubClassOf("SubRegIndex")) {
1661 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001662 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001663 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001664
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001665 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001666 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001667 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1668 //
1669 // (sext_inreg GPR:$src, i16)
1670 // ~~~
1671 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001672 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001673 // With a name, the ValueType simply provides the type of the named
1674 // variable.
1675 //
1676 // (sext_inreg i32:$src, i16)
1677 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001678 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001679 return TypeSetByHwMode(); // Unknown.
1680 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1681 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001682 }
1683
1684 if (R->isSubClassOf("CondCode")) {
1685 assert(ResNo == 0 && "This node only has one result!");
1686 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001687 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00001688 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001689
Chris Lattner6070ee22010-03-23 23:50:31 +00001690 if (R->isSubClassOf("ComplexPattern")) {
1691 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001692 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001693 return TypeSetByHwMode(); // Unknown.
1694 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00001695 }
1696 if (R->isSubClassOf("PointerLikeRegClass")) {
1697 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001698 TypeSetByHwMode VTS(MVT::iPTR);
1699 TP.getInfer().expandOverloads(VTS);
1700 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00001701 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001702
Chris Lattner6070ee22010-03-23 23:50:31 +00001703 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1704 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001705 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001706 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001707 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001708
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001709 if (R->isSubClassOf("Operand")) {
1710 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1711 Record *T = R->getValueAsDef("Type");
1712 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
1713 }
Tim Northoverc807a172014-05-20 11:52:46 +00001714
Chris Lattner8cab0212008-01-05 22:25:12 +00001715 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001716 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00001717}
1718
Chris Lattner89c65662008-01-06 05:36:50 +00001719
1720/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1721/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1722const CodeGenIntrinsic *TreePatternNode::
1723getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1724 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1725 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1726 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001727 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001728
Sean Silva88eb8dd2012-10-10 20:24:47 +00001729 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001730 return &CDP.getIntrinsicInfo(IID);
1731}
1732
Chris Lattner53c39ba2010-02-14 22:22:58 +00001733/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1734/// return the ComplexPattern information, otherwise return null.
1735const ComplexPattern *
1736TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001737 Record *Rec;
1738 if (isLeaf()) {
1739 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1740 if (!DI)
1741 return nullptr;
1742 Rec = DI->getDef();
1743 } else
1744 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001745
Tim Northoverc807a172014-05-20 11:52:46 +00001746 if (!Rec->isSubClassOf("ComplexPattern"))
1747 return nullptr;
1748 return &CGP.getComplexPattern(Rec);
1749}
1750
1751unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1752 // A ComplexPattern specifically declares how many results it fills in.
1753 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1754 return CP->getNumOperands();
1755
1756 // If MIOperandInfo is specified, that gives the count.
1757 if (isLeaf()) {
1758 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1759 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1760 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1761 if (MIOps->getNumArgs())
1762 return MIOps->getNumArgs();
1763 }
1764 }
1765
1766 // Otherwise there is just one result.
1767 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001768}
1769
1770/// NodeHasProperty - Return true if this node has the specified property.
1771bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001772 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001773 if (isLeaf()) {
1774 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1775 return CP->hasProperty(Property);
1776 return false;
1777 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001778
Chris Lattner53c39ba2010-02-14 22:22:58 +00001779 Record *Operator = getOperator();
1780 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001781
Chris Lattner53c39ba2010-02-14 22:22:58 +00001782 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1783}
1784
1785
1786
1787
1788/// TreeHasProperty - Return true if any node in this tree has the specified
1789/// property.
1790bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001791 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001792 if (NodeHasProperty(Property, CGP))
1793 return true;
1794 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1795 if (getChild(i)->TreeHasProperty(Property, CGP))
1796 return true;
1797 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001798}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001799
Evan Cheng49bad4c2008-06-16 20:29:38 +00001800/// isCommutativeIntrinsic - Return true if the node corresponds to a
1801/// commutative intrinsic.
1802bool
1803TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1804 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1805 return Int->isCommutative;
1806 return false;
1807}
1808
Matt Arsenaulteb492162014-11-02 23:46:51 +00001809static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1810 if (!N->isLeaf())
1811 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001812
Matt Arsenaulteb492162014-11-02 23:46:51 +00001813 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1814 if (DI && DI->getDef()->isSubClassOf(Class))
1815 return true;
1816
1817 return false;
1818}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001819
1820static void emitTooManyOperandsError(TreePattern &TP,
1821 StringRef InstName,
1822 unsigned Expected,
1823 unsigned Actual) {
1824 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1825 " operands but expected only " + Twine(Expected) + "!");
1826}
1827
1828static void emitTooFewOperandsError(TreePattern &TP,
1829 StringRef InstName,
1830 unsigned Actual) {
1831 TP.error("Instruction '" + InstName +
1832 "' expects more than the provided " + Twine(Actual) + " operands!");
1833}
1834
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001835/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001836/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001837/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001838bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001839 if (TP.hasError())
1840 return false;
1841
Chris Lattnerab3242f2008-01-06 01:10:31 +00001842 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001843 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001844 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001845 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001846 bool MadeChange = false;
1847 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1848 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001849 NotRegisters,
1850 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001851 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001852 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001853
Sean Silvafb509ed2012-10-10 20:24:43 +00001854 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001855 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001856
Chris Lattnerf1447252010-03-19 21:37:09 +00001857 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001858 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001859
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001860 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00001861 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001862
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001863 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
1864 for (auto &P : VVT) {
1865 MVT::SimpleValueType VT = P.second.SimpleTy;
1866 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1867 continue;
1868 unsigned Size = MVT(VT).getSizeInBits();
1869 // Make sure that the value is representable for this type.
1870 if (Size >= 32)
1871 continue;
1872 // Check that the value doesn't use more bits than we have. It must
1873 // either be a sign- or zero-extended equivalent of the original.
1874 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1875 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
1876 SignBitAndAbove == 1)
1877 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001878
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001879 TP.error("Integer value '" + itostr(II->getValue()) +
1880 "' is out of range for type '" + getEnumName(VT) + "'!");
1881 break;
1882 }
1883 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001884 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001885
Chris Lattner8cab0212008-01-05 22:25:12 +00001886 return false;
1887 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001888
Chris Lattner8cab0212008-01-05 22:25:12 +00001889 // special handling for set, which isn't really an SDNode.
1890 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001891 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1892 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001893 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001894
Chris Lattnerf1447252010-03-19 21:37:09 +00001895 TreePatternNode *SetVal = getChild(NC-1);
1896 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1897
Elena Demikhovsky09954792015-03-01 08:23:41 +00001898 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001899 TreePatternNode *Child = getChild(i);
1900 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001901
Chris Lattner8cab0212008-01-05 22:25:12 +00001902 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001903 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1904 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001905 }
1906 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001907 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001908
Chris Lattner5c2182e2010-03-27 02:53:27 +00001909 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001910 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1911
Chris Lattner8cab0212008-01-05 22:25:12 +00001912 bool MadeChange = false;
1913 for (unsigned i = 0; i < getNumChildren(); ++i)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001914 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001915 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001916 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001917
Chris Lattneree820ac2010-02-23 05:51:07 +00001918 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001919 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001920
Chris Lattner8cab0212008-01-05 22:25:12 +00001921 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001922 unsigned NumRetVTs = Int->IS.RetVTs.size();
1923 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001924
Bill Wendling91821472008-11-13 09:08:33 +00001925 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001926 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001927
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001928 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001929 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001930 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001931 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001932 return false;
1933 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001934
1935 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001936 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001937
Chris Lattnerf1447252010-03-19 21:37:09 +00001938 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1939 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001940
Chris Lattnerf1447252010-03-19 21:37:09 +00001941 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1942 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1943 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001944 }
1945 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001946 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001947
Chris Lattneree820ac2010-02-23 05:51:07 +00001948 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001949 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001950
Chris Lattner135091b2010-03-28 08:48:47 +00001951 // Check that the number of operands is sane. Negative operands -> varargs.
1952 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001953 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001954 TP.error(getOperator()->getName() + " node requires exactly " +
1955 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001956 return false;
1957 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001958
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001959 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001960 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1961 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001962 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001963 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001964 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001965
Chris Lattneree820ac2010-02-23 05:51:07 +00001966 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001967 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001968 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001969 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001970
Chris Lattnerd44966f2010-03-27 19:15:02 +00001971 bool MadeChange = false;
1972
1973 // Apply the result types to the node, these come from the things in the
1974 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001975 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1976 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001977 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1978 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001979
Chris Lattnerd44966f2010-03-27 19:15:02 +00001980 // If the instruction has implicit defs, we apply the first one as a result.
1981 // FIXME: This sucks, it should apply all implicit defs.
1982 if (!InstInfo.ImplicitDefs.empty()) {
1983 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001984
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001985 // FIXME: Generalize to multiple possible types and multiple possible
1986 // ImplicitDefs.
1987 MVT::SimpleValueType VT =
1988 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001989
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001990 if (VT != MVT::Other)
1991 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001992 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001993
Chris Lattnercabe0372010-03-15 06:00:16 +00001994 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1995 // be the same.
1996 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001997 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1998 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1999 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002000 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2001 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2002 // variadic.
2003
2004 unsigned NChild = getNumChildren();
2005 if (NChild < 3) {
2006 TP.error("REG_SEQUENCE requires at least 3 operands!");
2007 return false;
2008 }
2009
2010 if (NChild % 2 == 0) {
2011 TP.error("REG_SEQUENCE requires an odd number of operands!");
2012 return false;
2013 }
2014
2015 if (!isOperandClass(getChild(0), "RegisterClass")) {
2016 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2017 return false;
2018 }
2019
2020 for (unsigned I = 1; I < NChild; I += 2) {
2021 TreePatternNode *SubIdxChild = getChild(I + 1);
2022 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2023 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2024 itostr(I + 1) + "!");
2025 return false;
2026 }
2027 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002028 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002029
2030 unsigned ChildNo = 0;
2031 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2032 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002033
Chris Lattner8cab0212008-01-05 22:25:12 +00002034 // If the instruction expects a predicate or optional def operand, we
2035 // codegen this by setting the operand to it's default value if it has a
2036 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002037 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002038 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2039 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002040
Chris Lattner8cab0212008-01-05 22:25:12 +00002041 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002042 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002043 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002044 return false;
2045 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002046
Chris Lattner8cab0212008-01-05 22:25:12 +00002047 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002048 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002049
2050 // If the operand has sub-operands, they may be provided by distinct
2051 // child patterns, so attempt to match each sub-operand separately.
2052 if (OperandNode->isSubClassOf("Operand")) {
2053 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2054 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2055 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002056 // a single ComplexPattern-related Operand.
2057
2058 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002059 // Match first sub-operand against the child we already have.
2060 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2061 MadeChange |=
2062 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2063
2064 // And the remaining sub-operands against subsequent children.
2065 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2066 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002067 emitTooFewOperandsError(TP, getOperator()->getName(),
2068 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002069 return false;
2070 }
2071 Child = getChild(ChildNo++);
2072
2073 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2074 MadeChange |=
2075 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2076 }
2077 continue;
2078 }
2079 }
2080 }
2081
2082 // If we didn't match by pieces above, attempt to match the whole
2083 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002084 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002085 }
Christopher Lamba7312392008-03-11 09:33:47 +00002086
Matt Arsenaulteb492162014-11-02 23:46:51 +00002087 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002088 emitTooManyOperandsError(TP, getOperator()->getName(),
2089 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002090 return false;
2091 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002092
Ulrich Weigande618abd2013-03-19 19:51:09 +00002093 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2094 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002095 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002096 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002097
Tim Northoverc807a172014-05-20 11:52:46 +00002098 if (getOperator()->isSubClassOf("ComplexPattern")) {
2099 bool MadeChange = false;
2100
2101 for (unsigned i = 0; i < getNumChildren(); ++i)
2102 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2103
2104 return MadeChange;
2105 }
2106
Chris Lattneree820ac2010-02-23 05:51:07 +00002107 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002108
Chris Lattneree820ac2010-02-23 05:51:07 +00002109 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002110 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002111 TP.error("Node transform '" + getOperator()->getName() +
2112 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002113 return false;
2114 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002115
Chris Lattnercabe0372010-03-15 06:00:16 +00002116 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002117 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002118}
2119
2120/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2121/// RHS of a commutative operation, not the on LHS.
2122static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2123 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2124 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002125 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002126 return true;
2127 return false;
2128}
2129
2130
2131/// canPatternMatch - If it is impossible for this pattern to match on this
2132/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002133/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002134/// that can never possibly work), and to prevent the pattern permuter from
2135/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002136bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002137 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002138 if (isLeaf()) return true;
2139
2140 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2141 if (!getChild(i)->canPatternMatch(Reason, CDP))
2142 return false;
2143
2144 // If this is an intrinsic, handle cases that would make it not match. For
2145 // example, if an operand is required to be an immediate.
2146 if (getOperator()->isSubClassOf("Intrinsic")) {
2147 // TODO:
2148 return true;
2149 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002150
Tim Northoverc807a172014-05-20 11:52:46 +00002151 if (getOperator()->isSubClassOf("ComplexPattern"))
2152 return true;
2153
Chris Lattner8cab0212008-01-05 22:25:12 +00002154 // If this node is a commutative operator, check that the LHS isn't an
2155 // immediate.
2156 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002157 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2158 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002159 // Scan all of the operands of the node and make sure that only the last one
2160 // is a constant node, unless the RHS also is.
2161 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002162 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002163 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002164 if (OnlyOnRHSOfCommutative(getChild(i))) {
2165 Reason="Immediate value must be on the RHS of commutative operators!";
2166 return false;
2167 }
2168 }
2169 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002170
Chris Lattner8cab0212008-01-05 22:25:12 +00002171 return true;
2172}
2173
2174//===----------------------------------------------------------------------===//
2175// TreePattern implementation
2176//
2177
David Greeneaf8ee2c2011-07-29 22:43:06 +00002178TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002179 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002180 isInputPattern(isInput), HasError(false),
2181 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002182 for (Init *I : RawPat->getValues())
2183 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002184}
2185
David Greeneaf8ee2c2011-07-29 22:43:06 +00002186TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002187 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002188 isInputPattern(isInput), HasError(false),
2189 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002190 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002191}
2192
David Blaikiecf195302014-11-17 22:55:41 +00002193TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002194 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002195 isInputPattern(isInput), HasError(false),
2196 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002197 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002198}
2199
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002200void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002201 if (HasError)
2202 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002203 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002204 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2205 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002206}
2207
Chris Lattnercabe0372010-03-15 06:00:16 +00002208void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002209 for (TreePatternNode *Tree : Trees)
2210 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002211}
2212
2213void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2214 if (!N->getName().empty())
2215 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002216
Chris Lattnercabe0372010-03-15 06:00:16 +00002217 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2218 ComputeNamedNodes(N->getChild(i));
2219}
2220
David Blaikiecf195302014-11-17 22:55:41 +00002221
2222TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002223 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002224 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002225
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002226 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002227 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002228 /// (foo GPR, imm) -> (foo GPR, (imm))
2229 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002230 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002231 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002232 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002233 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002234
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002235 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002236 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002237 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002238 if (OpName.empty())
2239 error("'node' argument requires a name to match with operand list");
2240 Args.push_back(OpName);
2241 }
2242
2243 Res->setName(OpName);
2244 return Res;
2245 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002246
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002247 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002248 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002249 if (OpName.empty())
2250 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002251 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002252 Args.push_back(OpName);
2253 Res->setName(OpName);
2254 return Res;
2255 }
2256
Sean Silvafb509ed2012-10-10 20:24:43 +00002257 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002258 if (!OpName.empty())
2259 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002260 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002261 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002262
Sean Silvafb509ed2012-10-10 20:24:43 +00002263 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002264 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002265 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002266 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002267 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002268 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002269 }
2270
Sean Silvafb509ed2012-10-10 20:24:43 +00002271 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002272 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002273 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002274 error("Pattern has unexpected init kind!");
2275 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002276 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002277 if (!OpDef) error("Pattern has unexpected operator type!");
2278 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002279
Chris Lattner8cab0212008-01-05 22:25:12 +00002280 if (Operator->isSubClassOf("ValueType")) {
2281 // If the operator is a ValueType, then this must be "type cast" of a leaf
2282 // node.
2283 if (Dag->getNumArgs() != 1)
2284 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002285
Matthias Braunbb053162016-12-05 06:00:46 +00002286 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2287 Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002288
Chris Lattner8cab0212008-01-05 22:25:12 +00002289 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002290 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002291 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2292 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002293
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002294 if (!OpName.empty())
2295 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002296 return New;
2297 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002298
Chris Lattner8cab0212008-01-05 22:25:12 +00002299 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002300 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002301 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002302 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002303 !Operator->isSubClassOf("SDNodeXForm") &&
2304 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002305 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002306 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002307 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002308 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002309
Chris Lattner8cab0212008-01-05 22:25:12 +00002310 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002311 if (isInputPattern) {
2312 if (Operator->isSubClassOf("Instruction") ||
2313 Operator->isSubClassOf("SDNodeXForm"))
2314 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2315 } else {
2316 if (Operator->isSubClassOf("Intrinsic"))
2317 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002318
Chris Lattner2e9eae12010-03-28 06:57:56 +00002319 if (Operator->isSubClassOf("SDNode") &&
2320 Operator->getName() != "imm" &&
2321 Operator->getName() != "fpimm" &&
2322 Operator->getName() != "tglobaltlsaddr" &&
2323 Operator->getName() != "tconstpool" &&
2324 Operator->getName() != "tjumptable" &&
2325 Operator->getName() != "tframeindex" &&
2326 Operator->getName() != "texternalsym" &&
2327 Operator->getName() != "tblockaddress" &&
2328 Operator->getName() != "tglobaladdr" &&
2329 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002330 Operator->getName() != "vt" &&
2331 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002332 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2333 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002334
Chris Lattner8cab0212008-01-05 22:25:12 +00002335 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002336
2337 // Parse all the operands.
2338 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002339 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002340
Chris Lattner8cab0212008-01-05 22:25:12 +00002341 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002342 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002343 // convert the intrinsic name to a number.
2344 if (Operator->isSubClassOf("Intrinsic")) {
2345 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2346 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2347
2348 // If this intrinsic returns void, it must have side-effects and thus a
2349 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002350 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002351 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002352 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002353 // Has side-effects, requires chain.
2354 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002355 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002356 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002357
David Greenee32ebf22011-07-29 19:07:07 +00002358 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002359 Children.insert(Children.begin(), IIDNode);
2360 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002361
Tim Northoverc807a172014-05-20 11:52:46 +00002362 if (Operator->isSubClassOf("ComplexPattern")) {
2363 for (unsigned i = 0; i < Children.size(); ++i) {
2364 TreePatternNode *Child = Children[i];
2365
2366 if (Child->getName().empty())
2367 error("All arguments to a ComplexPattern must be named");
2368
2369 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2370 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2371 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2372 auto OperandId = std::make_pair(Operator, i);
2373 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2374 if (PrevOp != ComplexPatternOperands.end()) {
2375 if (PrevOp->getValue() != OperandId)
2376 error("All ComplexPattern operands must appear consistently: "
2377 "in the same order in just one ComplexPattern instance.");
2378 } else
2379 ComplexPatternOperands[Child->getName()] = OperandId;
2380 }
2381 }
2382
Chris Lattnerf1447252010-03-19 21:37:09 +00002383 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002384 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002385 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002386
Matthias Braun7cf3b112016-12-05 06:00:41 +00002387 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002388 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002389 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002390 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002391 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002392}
2393
Chris Lattnera787c9e2010-03-28 08:38:32 +00002394/// SimplifyTree - See if we can simplify this tree to eliminate something that
2395/// will never match in favor of something obvious that will. This is here
2396/// strictly as a convenience to target authors because it allows them to write
2397/// more type generic things and have useless type casts fold away.
2398///
2399/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002400static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002401 if (N->isLeaf())
2402 return false;
2403
2404 // If we have a bitconvert with a resolved type and if the source and
2405 // destination types are the same, then the bitconvert is useless, remove it.
2406 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002407 N->getExtType(0).isValueTypeByHwMode(false) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002408 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2409 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002410 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002411 SimplifyTree(N);
2412 return true;
2413 }
2414
2415 // Walk all children.
2416 bool MadeChange = false;
2417 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002418 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002419 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002420 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002421 }
2422 return MadeChange;
2423}
2424
2425
2426
Chris Lattner8cab0212008-01-05 22:25:12 +00002427/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002428/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002429/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002430bool TreePattern::
2431InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2432 if (NamedNodes.empty())
2433 ComputeNamedNodes();
2434
Chris Lattner8cab0212008-01-05 22:25:12 +00002435 bool MadeChange = true;
2436 while (MadeChange) {
2437 MadeChange = false;
Craig Topper3f7864e2017-08-30 02:05:03 +00002438 for (TreePatternNode *&Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002439 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2440 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002441 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002442
2443 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002444 for (auto &Entry : NamedNodes) {
2445 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002446
Chris Lattnercabe0372010-03-15 06:00:16 +00002447 // If we have input named node types, propagate their types to the named
2448 // values here.
2449 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002450 if (!InNamedTypes->count(Entry.getKey())) {
2451 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002452 "' in output pattern but not input pattern");
2453 return true;
2454 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002455
2456 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002457 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002458
2459 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002460 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002461 // If this node is a register class, and it is the root of the pattern
2462 // then we're mapping something onto an input register. We allow
2463 // changing the type of the input register in this case. This allows
2464 // us to match things like:
2465 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002466 if (Node == Trees[0] && Node->isLeaf()) {
2467 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002468 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2469 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002470 continue;
2471 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002472
Craig Topper306cb122015-11-22 20:46:24 +00002473 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002474 InNodes[0]->getNumTypes() == 1 &&
2475 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002476 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2477 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002478 }
2479 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002480
Chris Lattnercabe0372010-03-15 06:00:16 +00002481 // If there are multiple nodes with the same name, they must all have the
2482 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002483 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002484 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002485 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002486 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002487 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002488
Chris Lattnerf1447252010-03-19 21:37:09 +00002489 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2490 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002491 }
2492 }
2493 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002494 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002495
Chris Lattner8cab0212008-01-05 22:25:12 +00002496 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002497 for (const TreePatternNode *Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002498 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002499 return !HasUnresolvedTypes;
2500}
2501
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002502void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002503 OS << getRecord()->getName();
2504 if (!Args.empty()) {
2505 OS << "(" << Args[0];
2506 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2507 OS << ", " << Args[i];
2508 OS << ")";
2509 }
2510 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002511
Chris Lattner8cab0212008-01-05 22:25:12 +00002512 if (Trees.size() > 1)
2513 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002514 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002515 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002516 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002517 OS << "\n";
2518 }
2519
2520 if (Trees.size() > 1)
2521 OS << "]\n";
2522}
2523
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002524void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002525
2526//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002527// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002528//
2529
Jim Grosbach65586fe2010-12-21 16:16:00 +00002530CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002531 Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002532
Justin Bogner92a8c612016-07-15 16:31:37 +00002533 Intrinsics = CodeGenIntrinsicTable(Records, false);
2534 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002535 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002536 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002537 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002538 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002539 ParseDefaultOperands();
2540 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002541 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002542 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002543
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002544 // Break patterns with parameterized types into a series of patterns,
2545 // where each one has a fixed type and is predicated on the conditions
2546 // of the associated HW mode.
2547 ExpandHwModeBasedTypes();
2548
Chris Lattner8cab0212008-01-05 22:25:12 +00002549 // Generate variants. For example, commutative patterns can match
2550 // multiple ways. Add them to PatternsToMatch as well.
2551 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002552
2553 // Infer instruction flags. For example, we can detect loads,
2554 // stores, and side effects in many cases by examining an
2555 // instruction's pattern.
2556 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002557
2558 // Verify that instruction flags match the patterns.
2559 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002560}
2561
Chris Lattnerab3242f2008-01-06 01:10:31 +00002562Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002563 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002564 if (!N || !N->isSubClassOf("SDNode"))
2565 PrintFatalError("Error getting SDNode '" + Name + "'!");
2566
Chris Lattner8cab0212008-01-05 22:25:12 +00002567 return N;
2568}
2569
2570// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002571void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002572 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002573 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2574
Chris Lattner8cab0212008-01-05 22:25:12 +00002575 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002576 Record *R = Nodes.back();
2577 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002578 Nodes.pop_back();
2579 }
2580
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002581 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002582 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2583 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2584 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2585}
2586
2587/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2588/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002589void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002590 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2591 while (!Xforms.empty()) {
2592 Record *XFormNode = Xforms.back();
2593 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002594 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002595 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002596
2597 Xforms.pop_back();
2598 }
2599}
2600
Chris Lattnerab3242f2008-01-06 01:10:31 +00002601void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002602 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2603 while (!AMs.empty()) {
2604 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2605 AMs.pop_back();
2606 }
2607}
2608
2609
2610/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2611/// file, building up the PatternFragments map. After we've collected them all,
2612/// inline fragments together as necessary, so that there are no references left
2613/// inside a pattern fragment to a pattern fragment.
2614///
Hal Finkel2756dc12014-02-28 00:26:56 +00002615void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002616 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002617
Chris Lattnere7170df2008-01-05 22:43:57 +00002618 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002619 for (Record *Frag : Fragments) {
2620 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002621 continue;
2622
Craig Topper306cb122015-11-22 20:46:24 +00002623 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002624 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002625 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2626 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002627 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002628
Chris Lattnere7170df2008-01-05 22:43:57 +00002629 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002630 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002631 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002632
Chris Lattnere7170df2008-01-05 22:43:57 +00002633 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002634 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002635
Chris Lattner8cab0212008-01-05 22:25:12 +00002636 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002637 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002638 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002639 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002640 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002641 if (!OpsOp ||
2642 (OpsOp->getDef()->getName() != "ops" &&
2643 OpsOp->getDef()->getName() != "outs" &&
2644 OpsOp->getDef()->getName() != "ins"))
2645 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002646
2647 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002648 Args.clear();
2649 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002650 if (!isa<DefInit>(OpsList->getArg(j)) ||
2651 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002652 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00002653 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00002654 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00002655 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2656 if (!OperandsSet.count(ArgNameStr))
2657 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00002658 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00002659 OperandsSet.erase(ArgNameStr);
2660 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00002661 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002662
Chris Lattnere7170df2008-01-05 22:43:57 +00002663 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002664 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002665 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002666
Chris Lattnere7170df2008-01-05 22:43:57 +00002667 // If there is a code init for this fragment, keep track of the fact that
2668 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002669 TreePredicateFn PredFn(P);
2670 if (!PredFn.isAlwaysTrue())
2671 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002672
Chris Lattner8cab0212008-01-05 22:25:12 +00002673 // If there is a node transformation corresponding to this, keep track of
2674 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002675 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002676 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2677 P->getOnlyTree()->setTransformFn(Transform);
2678 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002679
Chris Lattner8cab0212008-01-05 22:25:12 +00002680 // Now that we've parsed all of the tree fragments, do a closure on them so
2681 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002682 for (Record *Frag : Fragments) {
2683 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002684 continue;
2685
Craig Topper306cb122015-11-22 20:46:24 +00002686 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002687 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002688
Chris Lattner8cab0212008-01-05 22:25:12 +00002689 // Infer as many types as possible. Don't worry about it if we don't infer
2690 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002691 ThePat.InferAllTypes();
2692 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002693
Chris Lattner8cab0212008-01-05 22:25:12 +00002694 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002695 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002696 }
2697}
2698
Chris Lattnerab3242f2008-01-06 01:10:31 +00002699void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002700 std::vector<Record*> DefaultOps;
2701 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002702
2703 // Find some SDNode.
2704 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002705 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002706
Tom Stellardb7246a72012-09-06 14:15:52 +00002707 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2708 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002709
Tom Stellardb7246a72012-09-06 14:15:52 +00002710 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2711 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00002712 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00002713 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2714 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2715 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00002716 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002717
Tom Stellardb7246a72012-09-06 14:15:52 +00002718 // Create a TreePattern to parse this.
2719 TreePattern P(DefaultOps[i], DI, false, *this);
2720 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002721
Tom Stellardb7246a72012-09-06 14:15:52 +00002722 // Copy the operands over into a DAGDefaultOperand.
2723 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002724
Tom Stellardb7246a72012-09-06 14:15:52 +00002725 TreePatternNode *T = P.getTree(0);
2726 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2727 TreePatternNode *TPN = T->getChild(op);
2728 while (TPN->ApplyTypeConstraints(P, false))
2729 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002730
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002731 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002732 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2733 DefaultOps[i]->getName() +
2734 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002735 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002736 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002737 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002738
2739 // Insert it into the DefaultOperands map so we can find it later.
2740 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002741 }
2742}
2743
2744/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2745/// instruction input. Return true if this is a real use.
2746static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002747 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002748 // No name -> not interesting.
2749 if (Pat->getName().empty()) {
2750 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002751 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002752 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2753 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002754 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002755 }
2756 return false;
2757 }
2758
2759 Record *Rec;
2760 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002761 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002762 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2763 Rec = DI->getDef();
2764 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002765 Rec = Pat->getOperator();
2766 }
2767
2768 // SRCVALUE nodes are ignored.
2769 if (Rec->getName() == "srcvalue")
2770 return false;
2771
2772 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2773 if (!Slot) {
2774 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002775 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002776 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002777 Record *SlotRec;
2778 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002779 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002780 } else {
2781 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2782 SlotRec = Slot->getOperator();
2783 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002784
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002785 // Ensure that the inputs agree if we've already seen this input.
2786 if (Rec != SlotRec)
2787 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002788 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002789 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002790 return true;
2791}
2792
2793/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2794/// part of "I", the instruction), computing the set of inputs and outputs of
2795/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002796void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002797FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2798 std::map<std::string, TreePatternNode*> &InstInputs,
2799 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002800 std::vector<Record*> &InstImpResults) {
2801 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002802 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002803 if (!isUse && Pat->getTransformFn())
2804 I->error("Cannot specify a transform function for a non-input value!");
2805 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002806 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002807
Chris Lattnerf2d70992010-02-17 06:53:36 +00002808 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002809 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2810 TreePatternNode *Dest = Pat->getChild(i);
2811 if (!Dest->isLeaf())
2812 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002813
Sean Silvafb509ed2012-10-10 20:24:43 +00002814 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002815 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2816 I->error("implicitly defined value should be a register!");
2817 InstImpResults.push_back(Val->getDef());
2818 }
2819 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002820 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002821
Chris Lattnerf2d70992010-02-17 06:53:36 +00002822 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002823 // If this is not a set, verify that the children nodes are not void typed,
2824 // and recurse.
2825 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002826 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002827 I->error("Cannot have void nodes inside of patterns!");
2828 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002829 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002830 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002831
Chris Lattner8cab0212008-01-05 22:25:12 +00002832 // If this is a non-leaf node with no children, treat it basically as if
2833 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002834 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002835
Chris Lattner8cab0212008-01-05 22:25:12 +00002836 if (!isUse && Pat->getTransformFn())
2837 I->error("Cannot specify a transform function for a non-input value!");
2838 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002839 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002840
Chris Lattner8cab0212008-01-05 22:25:12 +00002841 // Otherwise, this is a set, validate and collect instruction results.
2842 if (Pat->getNumChildren() == 0)
2843 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002844
Chris Lattner8cab0212008-01-05 22:25:12 +00002845 if (Pat->getTransformFn())
2846 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002847
Chris Lattner8cab0212008-01-05 22:25:12 +00002848 // Check the set destinations.
2849 unsigned NumDests = Pat->getNumChildren()-1;
2850 for (unsigned i = 0; i != NumDests; ++i) {
2851 TreePatternNode *Dest = Pat->getChild(i);
2852 if (!Dest->isLeaf())
2853 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002854
Sean Silvafb509ed2012-10-10 20:24:43 +00002855 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002856 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002857 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002858 continue;
2859 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002860
2861 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002862 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002863 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002864 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002865 if (Dest->getName().empty())
2866 I->error("set destination must have a name!");
2867 if (InstResults.count(Dest->getName()))
2868 I->error("cannot set '" + Dest->getName() +"' multiple times");
2869 InstResults[Dest->getName()] = Dest;
2870 } else if (Val->getDef()->isSubClassOf("Register")) {
2871 InstImpResults.push_back(Val->getDef());
2872 } else {
2873 I->error("set destination should be a register!");
2874 }
2875 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002876
Chris Lattner8cab0212008-01-05 22:25:12 +00002877 // Verify and collect info from the computation.
2878 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002879 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002880}
2881
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002882//===----------------------------------------------------------------------===//
2883// Instruction Analysis
2884//===----------------------------------------------------------------------===//
2885
2886class InstAnalyzer {
2887 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002888public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002889 bool hasSideEffects;
2890 bool mayStore;
2891 bool mayLoad;
2892 bool isBitcast;
2893 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002894
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002895 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2896 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2897 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002898
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002899 void Analyze(const TreePattern *Pat) {
2900 // Assume only the first tree is the pattern. The others are clobber nodes.
2901 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002902 }
2903
Craig Topper2a053a92017-06-20 16:34:37 +00002904 void Analyze(const PatternToMatch &Pat) {
2905 AnalyzeNode(Pat.getSrcPattern());
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002906 }
2907
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002908private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002909 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002910 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002911 return false;
2912
2913 if (N->getNumChildren() != 2)
2914 return false;
2915
2916 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002917 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002918 return false;
2919
2920 const TreePatternNode *N1 = N->getChild(1);
2921 if (N1->isLeaf())
2922 return false;
2923 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2924 return false;
2925
2926 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2927 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2928 return false;
2929 return OpInfo.getEnumName() == "ISD::BITCAST";
2930 }
2931
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002932public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002933 void AnalyzeNode(const TreePatternNode *N) {
2934 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002935 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002936 Record *LeafRec = DI->getDef();
2937 // Handle ComplexPattern leaves.
2938 if (LeafRec->isSubClassOf("ComplexPattern")) {
2939 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2940 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2941 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002942 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002943 }
2944 }
2945 return;
2946 }
2947
2948 // Analyze children.
2949 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2950 AnalyzeNode(N->getChild(i));
2951
2952 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002953 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002954 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002955 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002956 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002957
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002958 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002959 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2960 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2961 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2962 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002963
2964 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2965 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002966 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002967 mayLoad = true;// These may load memory.
2968
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002969 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002970 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2971
Matt Arsenault868af922017-04-28 21:01:46 +00002972 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
2973 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002974 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002975 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002976 }
2977 }
2978
2979};
2980
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002981static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002982 const InstAnalyzer &PatInfo,
2983 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002984 bool Error = false;
2985
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002986 // Remember where InstInfo got its flags.
2987 if (InstInfo.hasUndefFlags())
2988 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002989
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002990 // Check explicitly set flags for consistency.
2991 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2992 !InstInfo.hasSideEffects_Unset) {
2993 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2994 // the pattern has no side effects. That could be useful for div/rem
2995 // instructions that may trap.
2996 if (!InstInfo.hasSideEffects) {
2997 Error = true;
2998 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2999 Twine(InstInfo.hasSideEffects));
3000 }
3001 }
3002
3003 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3004 Error = true;
3005 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3006 Twine(InstInfo.mayStore));
3007 }
3008
3009 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3010 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003011 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003012 if (!InstInfo.mayLoad) {
3013 Error = true;
3014 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3015 Twine(InstInfo.mayLoad));
3016 }
3017 }
3018
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003019 // Transfer inferred flags.
3020 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3021 InstInfo.mayStore |= PatInfo.mayStore;
3022 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003023
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003024 // These flags are silently added without any verification.
3025 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003026
3027 // Don't infer isVariadic. This flag means something different on SDNodes and
3028 // instructions. For example, a CALL SDNode is variadic because it has the
3029 // call arguments as operands, but a CALL instruction is not variadic - it
3030 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003031
3032 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003033}
3034
Jim Grosbach514410b2012-07-17 00:47:06 +00003035/// hasNullFragReference - Return true if the DAG has any reference to the
3036/// null_frag operator.
3037static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003038 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003039 if (!OpDef) return false;
3040 Record *Operator = OpDef->getDef();
3041
3042 // If this is the null fragment, return true.
3043 if (Operator->getName() == "null_frag") return true;
3044 // If any of the arguments reference the null fragment, return true.
3045 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003046 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003047 if (Arg && hasNullFragReference(Arg))
3048 return true;
3049 }
3050
3051 return false;
3052}
3053
3054/// hasNullFragReference - Return true if any DAG in the list references
3055/// the null_frag operator.
3056static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003057 for (Init *I : LI->getValues()) {
3058 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003059 assert(DI && "non-dag in an instruction Pattern list?!");
3060 if (hasNullFragReference(DI))
3061 return true;
3062 }
3063 return false;
3064}
3065
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003066/// Get all the instructions in a tree.
3067static void
3068getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3069 if (Tree->isLeaf())
3070 return;
3071 if (Tree->getOperator()->isSubClassOf("Instruction"))
3072 Instrs.push_back(Tree->getOperator());
3073 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3074 getInstructionsInTree(Tree->getChild(i), Instrs);
3075}
3076
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003077/// Check the class of a pattern leaf node against the instruction operand it
3078/// represents.
3079static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3080 Record *Leaf) {
3081 if (OI.Rec == Leaf)
3082 return true;
3083
3084 // Allow direct value types to be used in instruction set patterns.
3085 // The type will be checked later.
3086 if (Leaf->isSubClassOf("ValueType"))
3087 return true;
3088
3089 // Patterns can also be ComplexPattern instances.
3090 if (Leaf->isSubClassOf("ComplexPattern"))
3091 return true;
3092
3093 return false;
3094}
3095
Ahmed Bougacha14107512013-10-28 18:07:21 +00003096const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
3097 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003098
Craig Topper0d1fb902015-03-10 03:25:04 +00003099 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003100
Craig Topper0d1fb902015-03-10 03:25:04 +00003101 // Parse the instruction.
3102 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
3103 // Inline pattern fragments into it.
3104 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003105
Craig Topper0d1fb902015-03-10 03:25:04 +00003106 // Infer as many types as possible. If we cannot infer all of them, we can
3107 // never do anything with this instruction pattern: report it to the user.
3108 if (!I->InferAllTypes())
3109 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003110
Craig Topper0d1fb902015-03-10 03:25:04 +00003111 // InstInputs - Keep track of all of the inputs of the instruction, along
3112 // with the record they are declared as.
3113 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003114
Craig Topper0d1fb902015-03-10 03:25:04 +00003115 // InstResults - Keep track of all the virtual registers that are 'set'
3116 // in the instruction, including what reg class they are.
3117 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003118
Craig Topper0d1fb902015-03-10 03:25:04 +00003119 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003120
Craig Topper0d1fb902015-03-10 03:25:04 +00003121 // Verify that the top-level forms in the instruction are of void type, and
3122 // fill in the InstResults map.
3123 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
3124 TreePatternNode *Pat = I->getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003125 if (Pat->getNumTypes() != 0) {
3126 std::string Types;
3127 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3128 if (k > 0)
3129 Types += ", ";
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003130 Types += Pat->getExtType(k).getAsString();
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003131 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003132 I->error("Top-level forms in instruction pattern should have"
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003133 " void types, has types " + Types);
3134 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003135
Craig Topper0d1fb902015-03-10 03:25:04 +00003136 // Find inputs and outputs, and verify the structure of the uses/defs.
3137 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3138 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003139 }
3140
Craig Topper0d1fb902015-03-10 03:25:04 +00003141 // Now that we have inputs and outputs of the pattern, inspect the operands
3142 // list for the instruction. This determines the order that operands are
3143 // added to the machine instruction the node corresponds to.
3144 unsigned NumResults = InstResults.size();
3145
3146 // Parse the operands list from the (ops) list, validating it.
3147 assert(I->getArgList().empty() && "Args list should still be empty here!");
3148
3149 // Check that all of the results occur first in the list.
3150 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00003151 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003152 for (unsigned i = 0; i != NumResults; ++i) {
3153 if (i == CGI.Operands.size())
3154 I->error("'" + InstResults.begin()->first +
3155 "' set but does not appear in operand list!");
3156 const std::string &OpName = CGI.Operands[i].Name;
3157
3158 // Check that it exists in InstResults.
3159 TreePatternNode *RNode = InstResults[OpName];
3160 if (!RNode)
3161 I->error("Operand $" + OpName + " does not exist in operand list!");
3162
Craig Topper3a8eb892015-03-20 05:09:06 +00003163 ResNodes.push_back(RNode);
3164
Craig Topper0d1fb902015-03-10 03:25:04 +00003165 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3166 if (!R)
3167 I->error("Operand $" + OpName + " should be a set destination: all "
3168 "outputs must occur before inputs in operand list!");
3169
3170 if (!checkOperandClass(CGI.Operands[i], R))
3171 I->error("Operand $" + OpName + " class mismatch!");
3172
3173 // Remember the return type.
3174 Results.push_back(CGI.Operands[i].Rec);
3175
3176 // Okay, this one checks out.
3177 InstResults.erase(OpName);
3178 }
3179
3180 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3181 // the copy while we're checking the inputs.
3182 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3183
3184 std::vector<TreePatternNode*> ResultNodeOperands;
3185 std::vector<Record*> Operands;
3186 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3187 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3188 const std::string &OpName = Op.Name;
3189 if (OpName.empty())
3190 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3191
3192 if (!InstInputsCheck.count(OpName)) {
3193 // If this is an operand with a DefaultOps set filled in, we can ignore
3194 // this. When we codegen it, we will do so as always executed.
3195 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3196 // Does it have a non-empty DefaultOps field? If so, ignore this
3197 // operand.
3198 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3199 continue;
3200 }
3201 I->error("Operand $" + OpName +
3202 " does not appear in the instruction pattern");
3203 }
3204 TreePatternNode *InVal = InstInputsCheck[OpName];
3205 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3206
3207 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3208 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3209 if (!checkOperandClass(Op, InRec))
3210 I->error("Operand $" + OpName + "'s register class disagrees"
3211 " between the operand and pattern");
3212 }
3213 Operands.push_back(Op.Rec);
3214
3215 // Construct the result for the dest-pattern operand list.
3216 TreePatternNode *OpNode = InVal->clone();
3217
3218 // No predicate is useful on the result.
3219 OpNode->clearPredicateFns();
3220
3221 // Promote the xform function to be an explicit node if set.
3222 if (Record *Xform = OpNode->getTransformFn()) {
3223 OpNode->setTransformFn(nullptr);
3224 std::vector<TreePatternNode*> Children;
3225 Children.push_back(OpNode);
3226 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3227 }
3228
3229 ResultNodeOperands.push_back(OpNode);
3230 }
3231
3232 if (!InstInputsCheck.empty())
3233 I->error("Input operand $" + InstInputsCheck.begin()->first +
3234 " occurs in pattern but not in operands list!");
3235
3236 TreePatternNode *ResultPattern =
3237 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3238 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003239 // Copy fully inferred output node types to instruction result pattern.
3240 for (unsigned i = 0; i != NumResults; ++i) {
3241 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3242 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3243 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003244
3245 // Create and insert the instruction.
3246 // FIXME: InstImpResults should not be part of DAGInstruction.
3247 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3248 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3249
3250 // Use a temporary tree pattern to infer all types and make sure that the
3251 // constructed result is correct. This depends on the instruction already
3252 // being inserted into the DAGInsts map.
3253 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3254 Temp.InferAllTypes(&I->getNamedNodesMap());
3255
3256 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3257 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3258
3259 return TheInsertedInst;
3260}
3261
Ahmed Bougacha14107512013-10-28 18:07:21 +00003262/// ParseInstructions - Parse all of the instructions, inlining and resolving
3263/// any fragments involved. This populates the Instructions list with fully
3264/// resolved instructions.
3265void CodeGenDAGPatterns::ParseInstructions() {
3266 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3267
Craig Topper306cb122015-11-22 20:46:24 +00003268 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003269 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003270
Craig Topper306cb122015-11-22 20:46:24 +00003271 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3272 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003273
3274 // If there is no pattern, only collect minimal information about the
3275 // instruction for its operand list. We have to assume that there is one
3276 // result, as we have no detailed info. A pattern which references the
3277 // null_frag operator is as-if no pattern were specified. Normally this
3278 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3279 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003280 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003281 std::vector<Record*> Results;
3282 std::vector<Record*> Operands;
3283
Craig Topper306cb122015-11-22 20:46:24 +00003284 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003285
3286 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003287 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3288 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003289
Craig Topper3a8eb892015-03-20 05:09:06 +00003290 // The rest are inputs.
3291 for (unsigned j = InstInfo.Operands.NumDefs,
3292 e = InstInfo.Operands.size(); j < e; ++j)
3293 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003294 }
3295
3296 // Create and insert the instruction.
3297 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003298 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003299 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003300 continue; // no pattern.
3301 }
3302
Craig Topper306cb122015-11-22 20:46:24 +00003303 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003304 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3305
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003306 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003307 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003308 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003309
Chris Lattner8cab0212008-01-05 22:25:12 +00003310 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003311 for (auto &Entry : Instructions) {
3312 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003313 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003314 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003315
3316 // FIXME: Assume only the first tree is the pattern. The others are clobber
3317 // nodes.
3318 TreePatternNode *Pattern = I->getTree(0);
3319 TreePatternNode *SrcPattern;
3320 if (Pattern->getOperator()->getName() == "set") {
3321 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3322 } else{
3323 // Not a set (store or something?)
3324 SrcPattern = Pattern;
3325 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003326
Craig Topper306cb122015-11-22 20:46:24 +00003327 Record *Instr = Entry.first;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003328 ListInit *Preds = Instr->getValueAsListInit("Predicates");
3329 int Complexity = Instr->getValueAsInt("AddedComplexity");
3330 AddPatternToMatch(
3331 I,
3332 PatternToMatch(Instr, makePredList(Preds), SrcPattern,
3333 TheInst.getResultPattern(), TheInst.getImpResults(),
3334 Complexity, Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003335 }
3336}
3337
Chris Lattnera7722b62010-02-23 06:55:24 +00003338
3339typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3340
Jim Grosbach65586fe2010-12-21 16:16:00 +00003341static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003342 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003343 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003344 if (!P->getName().empty()) {
3345 NameRecord &Rec = Names[P->getName()];
3346 // If this is the first instance of the name, remember the node.
3347 if (Rec.second++ == 0)
3348 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003349 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003350 PatternTop->error("repetition of value: $" + P->getName() +
3351 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003352 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003353
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003354 if (!P->isLeaf()) {
3355 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003356 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003357 }
3358}
3359
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003360std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3361 std::vector<Predicate> Preds;
3362 for (Init *I : L->getValues()) {
3363 if (DefInit *Pred = dyn_cast<DefInit>(I))
3364 Preds.push_back(Pred->getDef());
3365 else
3366 llvm_unreachable("Non-def on the list");
3367 }
3368
3369 // Sort so that different orders get canonicalized to the same string.
3370 std::sort(Preds.begin(), Preds.end());
3371 return Preds;
3372}
3373
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003374void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003375 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003376 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003377 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003378 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3379 PrintWarning(Pattern->getRecord()->getLoc(),
3380 Twine("Pattern can never match: ") + Reason);
3381 return;
3382 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003383
Chris Lattner1e634e32010-03-01 22:29:19 +00003384 // If the source pattern's root is a complex pattern, that complex pattern
3385 // must specify the nodes it can potentially match.
3386 if (const ComplexPattern *CP =
3387 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3388 if (CP->getRootNodes().empty())
3389 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3390 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003391
3392
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003393 // Find all of the named values in the input and output, ensure they have the
3394 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003395 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003396 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3397 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003398
3399 // Scan all of the named values in the destination pattern, rejecting them if
3400 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003401 for (const auto &Entry : DstNames) {
3402 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003403 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003404 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003405 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003406
Chris Lattnera7722b62010-02-23 06:55:24 +00003407 // Scan all of the named values in the source pattern, rejecting them if the
3408 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003409 for (const auto &Entry : SrcNames)
3410 if (DstNames[Entry.first].first == nullptr &&
3411 SrcNames[Entry.first].second == 1)
3412 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003413
Craig Topper18e6b572017-06-25 17:33:49 +00003414 PatternsToMatch.push_back(std::move(PTM));
Chris Lattner0c0baa92010-02-23 06:16:51 +00003415}
3416
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003417void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003418 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003419 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003420
3421 // First try to infer flags from the primary instruction pattern, if any.
3422 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003423 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003424 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3425 CodeGenInstruction &InstInfo =
3426 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003427
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003428 // Get the primary instruction pattern.
3429 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3430 if (!Pattern) {
3431 if (InstInfo.hasUndefFlags())
3432 Revisit.push_back(&InstInfo);
3433 continue;
3434 }
3435 InstAnalyzer PatInfo(*this);
3436 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003437 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003438 }
3439
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003440 // Second, look for single-instruction patterns defined outside the
3441 // instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003442 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003443 // We can only infer from single-instruction patterns, otherwise we won't
3444 // know which instruction should get the flags.
3445 SmallVector<Record*, 8> PatInstrs;
3446 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3447 if (PatInstrs.size() != 1)
3448 continue;
3449
3450 // Get the single instruction.
3451 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3452
3453 // Only infer properties from the first pattern. We'll verify the others.
3454 if (InstInfo.InferredFrom)
3455 continue;
3456
3457 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003458 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003459 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3460 }
3461
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003462 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003463 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003464
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003465 // Revisit instructions with undefined flags and no pattern.
3466 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003467 for (CodeGenInstruction *InstInfo : Revisit) {
3468 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003469 continue;
3470 // The mayLoad and mayStore flags default to false.
3471 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003472 if (InstInfo->hasSideEffects_Unset)
3473 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003474 }
3475 return;
3476 }
3477
3478 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003479 for (CodeGenInstruction *InstInfo : Revisit) {
3480 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003481 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003482 if (InstInfo->hasSideEffects_Unset)
3483 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003484 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003485 if (InstInfo->mayStore_Unset)
3486 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003487 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003488 if (InstInfo->mayLoad_Unset)
3489 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003490 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003491 }
3492}
3493
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003494
3495/// Verify instruction flags against pattern node properties.
3496void CodeGenDAGPatterns::VerifyInstructionFlags() {
3497 unsigned Errors = 0;
3498 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3499 const PatternToMatch &PTM = *I;
3500 SmallVector<Record*, 8> Instrs;
3501 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3502 if (Instrs.empty())
3503 continue;
3504
3505 // Count the number of instructions with each flag set.
3506 unsigned NumSideEffects = 0;
3507 unsigned NumStores = 0;
3508 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003509 for (const Record *Instr : Instrs) {
3510 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003511 NumSideEffects += InstInfo.hasSideEffects;
3512 NumStores += InstInfo.mayStore;
3513 NumLoads += InstInfo.mayLoad;
3514 }
3515
3516 // Analyze the source pattern.
3517 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003518 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003519
3520 // Collect error messages.
3521 SmallVector<std::string, 4> Msgs;
3522
3523 // Check for missing flags in the output.
3524 // Permit extra flags for now at least.
3525 if (PatInfo.hasSideEffects && !NumSideEffects)
3526 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3527
3528 // Don't verify store flags on instructions with side effects. At least for
3529 // intrinsics, side effects implies mayStore.
3530 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3531 Msgs.push_back("pattern may store, but mayStore isn't set");
3532
3533 // Similarly, mayStore implies mayLoad on intrinsics.
3534 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3535 Msgs.push_back("pattern may load, but mayLoad isn't set");
3536
3537 // Print error messages.
3538 if (Msgs.empty())
3539 continue;
3540 ++Errors;
3541
Craig Topper306cb122015-11-22 20:46:24 +00003542 for (const std::string &Msg : Msgs)
3543 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003544 (Instrs.size() == 1 ?
3545 "instruction" : "output instructions"));
3546 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003547 for (const Record *Instr : Instrs) {
3548 if (Instr != PTM.getSrcRecord())
3549 PrintError(Instr->getLoc(), "defined here");
3550 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003551 if (InstInfo.InferredFrom &&
3552 InstInfo.InferredFrom != InstInfo.TheDef &&
3553 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003554 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003555 }
3556 }
3557 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003558 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003559}
3560
Chris Lattnercabe0372010-03-15 06:00:16 +00003561/// Given a pattern result with an unresolved type, see if we can find one
3562/// instruction with an unresolved result type. Force this result type to an
3563/// arbitrary element if it's possible types to converge results.
3564static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3565 if (N->isLeaf())
3566 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003567
Chris Lattnercabe0372010-03-15 06:00:16 +00003568 // Analyze children.
3569 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3570 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3571 return true;
3572
3573 if (!N->getOperator()->isSubClassOf("Instruction"))
3574 return false;
3575
3576 // If this type is already concrete or completely unknown we can't do
3577 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003578 TypeInfer &TI = TP.getInfer();
Chris Lattnerf1447252010-03-19 21:37:09 +00003579 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003580 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003581 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003582
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003583 // Otherwise, force its type to an arbitrary choice.
3584 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003585 return true;
3586 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003587
Chris Lattnerf1447252010-03-19 21:37:09 +00003588 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003589}
3590
Chris Lattnerab3242f2008-01-06 01:10:31 +00003591void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003592 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3593
Craig Topper306cb122015-11-22 20:46:24 +00003594 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003595 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003596
3597 // If the pattern references the null_frag, there's nothing to do.
3598 if (hasNullFragReference(Tree))
3599 continue;
3600
Chris Lattner5c2182e2010-03-27 02:53:27 +00003601 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003602
3603 // Inline pattern fragments into it.
3604 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003605
David Greeneaf8ee2c2011-07-29 22:43:06 +00003606 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003607 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003608
Chris Lattner8cab0212008-01-05 22:25:12 +00003609 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003610 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003611
Chris Lattner8cab0212008-01-05 22:25:12 +00003612 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003613 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003614
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003615 if (Result.getNumTrees() != 1)
3616 Result.error("Cannot handle instructions producing instructions "
3617 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003618
Chris Lattner8cab0212008-01-05 22:25:12 +00003619 bool IterateInference;
3620 bool InferredAllPatternTypes, InferredAllResultTypes;
3621 do {
3622 // Infer as many types as possible. If we cannot infer all of them, we
3623 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003624 InferredAllPatternTypes =
3625 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003626
Chris Lattner8cab0212008-01-05 22:25:12 +00003627 // Infer as many types as possible. If we cannot infer all of them, we
3628 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003629 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003630 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003631
Chris Lattnerfdc20712010-03-18 23:15:10 +00003632 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003633
Chris Lattner8cab0212008-01-05 22:25:12 +00003634 // Apply the type of the result to the source pattern. This helps us
3635 // resolve cases where the input type is known to be a pointer type (which
3636 // is considered resolved), but the result knows it needs to be 32- or
3637 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003638 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003639 Pattern->getTree(0)->getNumTypes());
3640 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003641 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3642 i, Result.getTree(0)->getExtType(i), Result);
3643 IterateInference |= Result.getTree(0)->UpdateNodeType(
3644 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003645 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003646
Chris Lattnercabe0372010-03-15 06:00:16 +00003647 // If our iteration has converged and the input pattern's types are fully
3648 // resolved but the result pattern is not fully resolved, we may have a
3649 // situation where we have two instructions in the result pattern and
3650 // the instructions require a common register class, but don't care about
3651 // what actual MVT is used. This is actually a bug in our modelling:
3652 // output patterns should have register classes, not MVTs.
3653 //
3654 // In any case, to handle this, we just go through and disambiguate some
3655 // arbitrary types to the result pattern's nodes.
3656 if (!IterateInference && InferredAllPatternTypes &&
3657 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003658 IterateInference =
3659 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003660 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003661
Chris Lattner8cab0212008-01-05 22:25:12 +00003662 // Verify that we inferred enough types that we can do something with the
3663 // pattern and result. If these fire the user has to add type casts.
3664 if (!InferredAllPatternTypes)
3665 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003666 if (!InferredAllResultTypes) {
3667 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003668 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003669 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003670
Chris Lattner8cab0212008-01-05 22:25:12 +00003671 // Validate that the input pattern is correct.
3672 std::map<std::string, TreePatternNode*> InstInputs;
3673 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003674 std::vector<Record*> InstImpResults;
3675 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3676 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3677 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003678 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003679
3680 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003681 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003682 std::vector<TreePatternNode*> ResultNodeOperands;
3683 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3684 TreePatternNode *OpNode = DstPattern->getChild(ii);
3685 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003686 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003687 std::vector<TreePatternNode*> Children;
3688 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003689 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003690 }
3691 ResultNodeOperands.push_back(OpNode);
3692 }
David Blaikiecf195302014-11-17 22:55:41 +00003693 DstPattern = Result.getOnlyTree();
3694 if (!DstPattern->isLeaf())
3695 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3696 ResultNodeOperands,
3697 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003698
David Blaikiecf195302014-11-17 22:55:41 +00003699 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3700 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3701
3702 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003703 Temp.InferAllTypes();
3704
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003705 // A pattern may end up with an "impossible" type, i.e. a situation
3706 // where all types have been eliminated for some node in this pattern.
3707 // This could occur for intrinsics that only make sense for a specific
3708 // value type, and use a specific register class. If, for some mode,
3709 // that register class does not accept that type, the type inference
3710 // will lead to a contradiction, which is not an error however, but
3711 // a sign that this pattern will simply never match.
3712 if (Pattern->getTree(0)->hasPossibleType() &&
3713 Temp.getOnlyTree()->hasPossibleType()) {
3714 ListInit *Preds = CurPattern->getValueAsListInit("Predicates");
3715 int Complexity = CurPattern->getValueAsInt("AddedComplexity");
3716 AddPatternToMatch(
3717 Pattern,
3718 PatternToMatch(
3719 CurPattern, makePredList(Preds), Pattern->getTree(0),
3720 Temp.getOnlyTree(), std::move(InstImpResults), Complexity,
3721 CurPattern->getID()));
3722 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003723 }
3724}
3725
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003726static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
3727 for (const TypeSetByHwMode &VTS : N->getExtTypes())
3728 for (const auto &I : VTS)
3729 Modes.insert(I.first);
3730
3731 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3732 collectModes(Modes, N->getChild(i));
3733}
3734
3735void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
3736 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3737 std::map<unsigned,std::vector<Predicate>> ModeChecks;
3738 std::vector<PatternToMatch> Copy = PatternsToMatch;
3739 PatternsToMatch.clear();
3740
3741 auto AppendPattern = [this,&ModeChecks](PatternToMatch &P, unsigned Mode) {
3742 TreePatternNode *NewSrc = P.SrcPattern->clone();
3743 TreePatternNode *NewDst = P.DstPattern->clone();
3744 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
3745 delete NewSrc;
3746 delete NewDst;
3747 return;
3748 }
3749
3750 std::vector<Predicate> Preds = P.Predicates;
3751 const std::vector<Predicate> &MC = ModeChecks[Mode];
3752 Preds.insert(Preds.end(), MC.begin(), MC.end());
3753 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, NewSrc, NewDst,
3754 P.getDstRegs(), P.getAddedComplexity(),
3755 Record::getNewUID(), Mode);
3756 };
3757
3758 for (PatternToMatch &P : Copy) {
3759 TreePatternNode *SrcP = nullptr, *DstP = nullptr;
3760 if (P.SrcPattern->hasProperTypeByHwMode())
3761 SrcP = P.SrcPattern;
3762 if (P.DstPattern->hasProperTypeByHwMode())
3763 DstP = P.DstPattern;
3764 if (!SrcP && !DstP) {
3765 PatternsToMatch.push_back(P);
3766 continue;
3767 }
3768
3769 std::set<unsigned> Modes;
3770 if (SrcP)
3771 collectModes(Modes, SrcP);
3772 if (DstP)
3773 collectModes(Modes, DstP);
3774
3775 // The predicate for the default mode needs to be constructed for each
3776 // pattern separately.
3777 // Since not all modes must be present in each pattern, if a mode m is
3778 // absent, then there is no point in constructing a check for m. If such
3779 // a check was created, it would be equivalent to checking the default
3780 // mode, except not all modes' predicates would be a part of the checking
3781 // code. The subsequently generated check for the default mode would then
3782 // have the exact same patterns, but a different predicate code. To avoid
3783 // duplicated patterns with different predicate checks, construct the
3784 // default check as a negation of all predicates that are actually present
3785 // in the source/destination patterns.
3786 std::vector<Predicate> DefaultPred;
3787
3788 for (unsigned M : Modes) {
3789 if (M == DefaultMode)
3790 continue;
3791 if (ModeChecks.find(M) != ModeChecks.end())
3792 continue;
3793
3794 // Fill the map entry for this mode.
3795 const HwMode &HM = CGH.getMode(M);
3796 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
3797
3798 // Add negations of the HM's predicates to the default predicate.
3799 DefaultPred.emplace_back(Predicate(HM.Features, false));
3800 }
3801
3802 for (unsigned M : Modes) {
3803 if (M == DefaultMode)
3804 continue;
3805 AppendPattern(P, M);
3806 }
3807
3808 bool HasDefault = Modes.count(DefaultMode);
3809 if (HasDefault)
3810 AppendPattern(P, DefaultMode);
3811 }
3812}
3813
3814/// Dependent variable map for CodeGenDAGPattern variant generation
3815typedef std::map<std::string, int> DepVarMap;
3816
3817static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
3818 if (N->isLeaf()) {
3819 if (isa<DefInit>(N->getLeafValue()))
3820 DepMap[N->getName()]++;
3821 } else {
3822 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
3823 FindDepVarsOf(N->getChild(i), DepMap);
3824 }
3825}
3826
3827/// Find dependent variables within child patterns
3828static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
3829 DepVarMap depcounts;
3830 FindDepVarsOf(N, depcounts);
3831 for (const std::pair<std::string, int> &Pair : depcounts) {
3832 if (Pair.second > 1)
3833 DepVars.insert(Pair.first);
3834 }
3835}
3836
3837#ifndef NDEBUG
3838/// Dump the dependent variable set:
3839static void DumpDepVars(MultipleUseVarSet &DepVars) {
3840 if (DepVars.empty()) {
3841 DEBUG(errs() << "<empty set>");
3842 } else {
3843 DEBUG(errs() << "[ ");
3844 for (const std::string &DepVar : DepVars) {
3845 DEBUG(errs() << DepVar << " ");
3846 }
3847 DEBUG(errs() << "]");
3848 }
3849}
3850#endif
3851
3852
Chris Lattner8cab0212008-01-05 22:25:12 +00003853/// CombineChildVariants - Given a bunch of permutations of each child of the
3854/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003855static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003856 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3857 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003858 CodeGenDAGPatterns &CDP,
3859 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003860 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003861 for (const auto &Variants : ChildVariants)
3862 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003863 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003864
Chris Lattner8cab0212008-01-05 22:25:12 +00003865 // The end result is an all-pairs construction of the resultant pattern.
3866 std::vector<unsigned> Idxs;
3867 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003868 bool NotDone;
3869 do {
3870#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003871 DEBUG(if (!Idxs.empty()) {
3872 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003873 for (unsigned Idx : Idxs) {
3874 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003875 }
3876 errs() << "]\n";
3877 });
Scott Michel94420742008-03-05 17:49:05 +00003878#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003879 // Create the variant and add it to the output list.
3880 std::vector<TreePatternNode*> NewChildren;
3881 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3882 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003883 auto R = llvm::make_unique<TreePatternNode>(
3884 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003885
Chris Lattner8cab0212008-01-05 22:25:12 +00003886 // Copy over properties.
3887 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003888 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003889 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003890 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3891 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003892
Scott Michel94420742008-03-05 17:49:05 +00003893 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003894 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003895 // Scan to see if this pattern has already been emitted. We can get
3896 // duplication due to things like commuting:
3897 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3898 // which are the same pattern. Ignore the dups.
3899 if (R->canPatternMatch(ErrString, CDP) &&
David Majnemer0a16c222016-08-11 21:15:00 +00003900 none_of(OutVariants, [&](TreePatternNode *Variant) {
3901 return R->isIsomorphicTo(Variant, DepVars);
3902 }))
David Blaikiefda69dd2015-11-22 20:11:21 +00003903 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003904
Scott Michel94420742008-03-05 17:49:05 +00003905 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003906 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003907 // [0, 0], [0, 1], [1, 0], [1, 1].
3908 int IdxsIdx;
3909 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3910 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3911 Idxs[IdxsIdx] = 0;
3912 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003913 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003914 }
Scott Michel94420742008-03-05 17:49:05 +00003915 NotDone = (IdxsIdx >= 0);
3916 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003917}
3918
3919/// CombineChildVariants - A helper function for binary operators.
3920///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003921static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003922 const std::vector<TreePatternNode*> &LHS,
3923 const std::vector<TreePatternNode*> &RHS,
3924 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003925 CodeGenDAGPatterns &CDP,
3926 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003927 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3928 ChildVariants.push_back(LHS);
3929 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003930 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003931}
Chris Lattner8cab0212008-01-05 22:25:12 +00003932
3933
3934static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3935 std::vector<TreePatternNode *> &Children) {
3936 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3937 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003938
Chris Lattner8cab0212008-01-05 22:25:12 +00003939 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003940 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003941 N->getTransformFn()) {
3942 Children.push_back(N);
3943 return;
3944 }
3945
3946 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3947 Children.push_back(N->getChild(0));
3948 else
3949 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3950
3951 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3952 Children.push_back(N->getChild(1));
3953 else
3954 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3955}
3956
3957/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3958/// the (potentially recursive) pattern by using algebraic laws.
3959///
3960static void GenerateVariantsOf(TreePatternNode *N,
3961 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003962 CodeGenDAGPatterns &CDP,
3963 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003964 // We cannot permute leaves or ComplexPattern uses.
3965 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003966 OutVariants.push_back(N);
3967 return;
3968 }
3969
3970 // Look up interesting info about the node.
3971 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3972
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003973 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003974 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003975 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003976 std::vector<TreePatternNode*> MaximalChildren;
3977 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3978
3979 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3980 // permutations.
3981 if (MaximalChildren.size() == 3) {
3982 // Find the variants of all of our maximal children.
3983 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003984 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3985 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3986 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003987
Chris Lattner8cab0212008-01-05 22:25:12 +00003988 // There are only two ways we can permute the tree:
3989 // (A op B) op C and A op (B op C)
3990 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003991
Chris Lattner8cab0212008-01-05 22:25:12 +00003992 // Generate legal pair permutations of A/B/C.
3993 std::vector<TreePatternNode*> ABVariants;
3994 std::vector<TreePatternNode*> BAVariants;
3995 std::vector<TreePatternNode*> ACVariants;
3996 std::vector<TreePatternNode*> CAVariants;
3997 std::vector<TreePatternNode*> BCVariants;
3998 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003999 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4000 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4001 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4002 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4003 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4004 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004005
4006 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00004007 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4008 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4009 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4010 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4011 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4012 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004013
4014 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00004015 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4016 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4017 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4018 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4019 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4020 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004021 return;
4022 }
4023 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004024
Chris Lattner8cab0212008-01-05 22:25:12 +00004025 // Compute permutations of all children.
4026 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4027 ChildVariants.resize(N->getNumChildren());
4028 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00004029 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004030
4031 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00004032 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004033
4034 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004035 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4036 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004037 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004038 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004039 // Don't count children which are actually register references.
4040 unsigned NC = 0;
4041 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4042 TreePatternNode *Child = N->getChild(i);
4043 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00004044 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004045 Record *RR = DI->getDef();
4046 if (RR->isSubClassOf("Register"))
4047 continue;
4048 }
4049 NC++;
4050 }
4051 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004052 if (isCommIntrinsic) {
4053 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4054 // operands are the commutative operands, and there might be more operands
4055 // after those.
4056 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004057 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00004058 std::vector<std::vector<TreePatternNode*> > Variants;
4059 Variants.push_back(ChildVariants[0]); // Intrinsic id.
4060 Variants.push_back(ChildVariants[2]);
4061 Variants.push_back(ChildVariants[1]);
4062 for (unsigned i = 3; i != NC; ++i)
4063 Variants.push_back(ChildVariants[i]);
4064 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004065 } else if (NC == N->getNumChildren()) {
4066 std::vector<std::vector<TreePatternNode*> > Variants;
4067 Variants.push_back(ChildVariants[1]);
4068 Variants.push_back(ChildVariants[0]);
4069 for (unsigned i = 2; i != NC; ++i)
4070 Variants.push_back(ChildVariants[i]);
4071 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4072 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004073 }
4074}
4075
4076
4077// GenerateVariants - Generate variants. For example, commutative patterns can
4078// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004079void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00004080 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004081
Chris Lattner8cab0212008-01-05 22:25:12 +00004082 // Loop over all of the patterns we've collected, checking to see if we can
4083 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004084 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004085 // the .td file having to contain tons of variants of instructions.
4086 //
4087 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4088 // intentionally do not reconsider these. Any variants of added patterns have
4089 // already been added.
4090 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00004091 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00004092 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00004093 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004094 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00004095 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00004096 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00004097 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00004098 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00004099 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004100
4101 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00004102 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004103 continue;
4104
Chris Lattner34822f62009-08-23 04:44:11 +00004105 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00004106 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00004107 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004108
4109 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4110 TreePatternNode *Variant = Variants[v];
4111
Chris Lattner34822f62009-08-23 04:44:11 +00004112 DEBUG(errs() << " VAR#" << v << ": ";
4113 Variant->dump();
4114 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004115
Chris Lattner8cab0212008-01-05 22:25:12 +00004116 // Scan to see if an instruction or explicit pattern already matches this.
4117 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004118 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004119 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004120 if (PatternsToMatch[i].getPredicates() !=
4121 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00004122 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004123 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004124 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4125 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00004126 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004127 AlreadyExists = true;
4128 break;
4129 }
4130 }
4131 // If we already have it, ignore the variant.
4132 if (AlreadyExists) continue;
4133
4134 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004135 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004136 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4137 Variant, PatternsToMatch[i].getDstPattern(),
4138 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004139 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00004140 }
4141
Chris Lattner34822f62009-08-23 04:44:11 +00004142 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004143 }
4144}