blob: 86238b6c8479dafd4dad7989bb485efce157fb98 [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 Parzyszek779d98e2017-09-14 16:56:21 +000046template <typename T, typename Predicate>
47static bool berase_if(std::set<T> &S, Predicate P) {
48 bool Erased = false;
49 for (auto I = S.begin(); I != S.end(); ) {
50 if (P(*I)) {
51 Erased = true;
52 I = S.erase(I);
53 } else
54 ++I;
Chris Lattnercabe0372010-03-15 06:00:16 +000055 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000056 return Erased;
Chris Lattner8cab0212008-01-05 22:25:12 +000057}
58
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000059// --- TypeSetByHwMode
Chris Lattnercabe0372010-03-15 06:00:16 +000060
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000061// This is a parameterized type-set class. For each mode there is a list
62// of types that are currently possible for a given tree node. Type
63// inference will apply to each mode separately.
Jim Grosbach65586fe2010-12-21 16:16:00 +000064
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000065TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
66 for (const ValueTypeByHwMode &VVT : VTList)
67 insert(VVT);
Chris Lattner8cab0212008-01-05 22:25:12 +000068}
69
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000070bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
71 for (const auto &I : *this) {
72 if (I.second.size() > 1)
73 return false;
74 if (!AllowEmpty && I.second.empty())
75 return false;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000076 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000077 return true;
78}
Chris Lattnercabe0372010-03-15 06:00:16 +000079
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000080ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
81 assert(isValueTypeByHwMode(true) &&
82 "The type set has multiple types for at least one HW mode");
83 ValueTypeByHwMode VVT;
84 for (const auto &I : *this) {
85 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
86 VVT.getOrCreateTypeForMode(I.first, T);
Chris Lattnercabe0372010-03-15 06:00:16 +000087 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000088 return VVT;
Bob Wilson2cd5da82009-08-11 01:14:02 +000089}
Chris Lattnercabe0372010-03-15 06:00:16 +000090
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000091bool TypeSetByHwMode::isPossible() const {
92 for (const auto &I : *this)
93 if (!I.second.empty())
94 return true;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000095 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +000096}
97
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000098bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
99 bool Changed = false;
100 std::set<unsigned> Modes;
101 for (const auto &P : VVT) {
102 unsigned M = P.first;
103 Modes.insert(M);
104 // Make sure there exists a set for each specific mode from VVT.
105 Changed |= getOrCreate(M).insert(P.second).second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000106 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000107
108 // If VVT has a default mode, add the corresponding type to all
109 // modes in "this" that do not exist in VVT.
110 if (Modes.count(DefaultMode)) {
111 MVT DT = VVT.getType(DefaultMode);
112 for (auto &I : *this)
113 if (!Modes.count(I.first))
114 Changed |= I.second.insert(DT).second;
115 }
116
117 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000118}
119
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000120// Constrain the type set to be the intersection with VTS.
121bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
122 bool Changed = false;
123 if (hasDefault()) {
124 for (const auto &I : VTS) {
125 unsigned M = I.first;
126 if (M == DefaultMode || hasMode(M))
127 continue;
128 Map[M] = Map[DefaultMode];
129 Changed = true;
130 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000131 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000132
133 for (auto &I : *this) {
134 unsigned M = I.first;
135 SetType &S = I.second;
136 if (VTS.hasMode(M) || VTS.hasDefault()) {
137 Changed |= intersect(I.second, VTS.get(M));
138 } else if (!S.empty()) {
139 S.clear();
140 Changed = true;
141 }
142 }
143 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000144}
145
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000146template <typename Predicate>
147bool TypeSetByHwMode::constrain(Predicate P) {
148 bool Changed = false;
149 for (auto &I : *this)
Benjamin Kramere57308e2017-09-17 11:19:53 +0000150 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000151 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000152}
153
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000154template <typename Predicate>
155bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
156 assert(empty());
157 for (const auto &I : VTS) {
158 SetType &S = getOrCreate(I.first);
159 for (auto J : I.second)
160 if (P(J))
161 S.insert(J);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000162 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000163 return !empty();
Chris Lattnercabe0372010-03-15 06:00:16 +0000164}
165
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000166std::string TypeSetByHwMode::getAsString() const {
167 std::stringstream str;
168 std::vector<unsigned> Modes;
Chris Lattnercabe0372010-03-15 06:00:16 +0000169
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000170 for (const auto &I : *this)
171 Modes.push_back(I.first);
172 if (Modes.empty())
173 return "{}";
174 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000175
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000176 str << '{';
177 for (unsigned M : Modes) {
178 const SetType &S = get(M);
179 str << ' ' << getModeName(M) << ':' << getAsString(S);
180 }
181 str << " }";
182 return str.str();
183}
184
185std::string TypeSetByHwMode::getAsString(const SetType &S) {
186 std::vector<MVT> Types(S.begin(), S.end());
187 array_pod_sort(Types.begin(), Types.end());
188
189 std::stringstream str;
190 str << '[';
191 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
192 str << ValueTypeByHwMode::getMVTName(Types[i]);
193 if (i != e-1)
194 str << ' ';
195 }
196 str << ']';
197 return str.str();
198}
199
200bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
201 bool HaveDefault = hasDefault();
202 if (HaveDefault != VTS.hasDefault())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000203 return false;
204
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000205 std::set<unsigned> Modes;
206 for (auto &I : *this)
207 Modes.insert(I.first);
208 for (const auto &I : VTS)
209 Modes.insert(I.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000210
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000211 if (HaveDefault) {
212 // Both sets have default mode.
213 for (unsigned M : Modes) {
214 if (get(M) != VTS.get(M))
David Majnemerc7004902016-08-12 04:32:37 +0000215 return false;
Craig Topper5712d462015-11-24 08:20:47 +0000216 }
Scott Michel94420742008-03-05 17:49:05 +0000217 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000218 // Neither set has default mode.
219 for (unsigned M : Modes) {
220 // If there is no default mode, an empty set is equivalent to not having
221 // the corresponding mode.
222 bool NoModeThis = !hasMode(M) || get(M).empty();
223 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
224 if (NoModeThis != NoModeVTS)
225 return false;
226 if (!NoModeThis)
227 if (get(M) != VTS.get(M))
228 return false;
229 }
Scott Michel94420742008-03-05 17:49:05 +0000230 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000231
232 return true;
Scott Michel94420742008-03-05 17:49:05 +0000233}
234
Krzysztof Parzyszek426bf362017-09-12 15:31:26 +0000235LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000236void TypeSetByHwMode::dump() const {
237 dbgs() << getAsString() << '\n';
238}
239
240bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
241 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
242 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
243
244 if (OutP == InP)
245 return berase_if(Out, Int);
246
247 // Compute the intersection of scalars separately to account for only
248 // one set containing iPTR.
249 // The itersection of iPTR with a set of integer scalar types that does not
250 // include iPTR will result in the most specific scalar type:
251 // - iPTR is more specific than any set with two elements or more
252 // - iPTR is less specific than any single integer scalar type.
253 // For example
254 // { iPTR } * { i32 } -> { i32 }
255 // { iPTR } * { i32 i64 } -> { iPTR }
256
257 SetType Diff;
258 if (InP) {
259 std::copy_if(Out.begin(), Out.end(), std::inserter(Diff, Diff.end()),
260 [&In](MVT T) { return !In.count(T); });
261 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000262 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000263 std::copy_if(In.begin(), In.end(), std::inserter(Diff, Diff.end()),
264 [&Out](MVT T) { return !Out.count(T); });
265 Out.erase(MVT::iPTR);
266 }
267
268 bool Changed = berase_if(Out, Int);
269 unsigned NumD = Diff.size();
270 if (NumD == 0)
271 return Changed;
272
273 if (NumD == 1) {
274 Out.insert(*Diff.begin());
275 // This is a change only if Out was the one with iPTR (which is now
276 // being replaced).
277 Changed |= OutP;
278 } else {
279 Out.insert(MVT::iPTR);
280 Changed |= InP;
281 }
282 return Changed;
283}
284
285void TypeSetByHwMode::validate() const {
286#ifndef NDEBUG
287 if (empty())
288 return;
289 bool AllEmpty = true;
290 for (const auto &I : *this)
291 AllEmpty &= I.second.empty();
292 assert(!AllEmpty &&
293 "type set is empty for each HW mode: type contradiction?");
294#endif
295}
296
297// --- TypeInfer
298
299bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
300 const TypeSetByHwMode &In) {
301 ValidateOnExit _1(Out);
302 In.validate();
303 if (In.empty() || Out == In || TP.hasError())
304 return false;
305 if (Out.empty()) {
306 Out = In;
307 return true;
308 }
309
310 bool Changed = Out.constrain(In);
311 if (Changed && Out.empty())
312 TP.error("Type contradiction");
313
314 return Changed;
315}
316
317bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
318 ValidateOnExit _1(Out);
319 if (TP.hasError())
320 return false;
321 assert(!Out.empty() && "cannot pick from an empty set");
322
323 bool Changed = false;
324 for (auto &I : Out) {
325 TypeSetByHwMode::SetType &S = I.second;
326 if (S.size() <= 1)
327 continue;
328 MVT T = *S.begin(); // Pick the first element.
329 S.clear();
330 S.insert(T);
331 Changed = true;
332 }
333 return Changed;
334}
335
336bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
337 ValidateOnExit _1(Out);
338 if (TP.hasError())
339 return false;
340 if (!Out.empty())
341 return Out.constrain(isIntegerOrPtr);
342
343 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
344}
345
346bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
347 ValidateOnExit _1(Out);
348 if (TP.hasError())
349 return false;
350 if (!Out.empty())
351 return Out.constrain(isFloatingPoint);
352
353 return Out.assign_if(getLegalTypes(), isFloatingPoint);
354}
355
356bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
357 ValidateOnExit _1(Out);
358 if (TP.hasError())
359 return false;
360 if (!Out.empty())
361 return Out.constrain(isScalar);
362
363 return Out.assign_if(getLegalTypes(), isScalar);
364}
365
366bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
367 ValidateOnExit _1(Out);
368 if (TP.hasError())
369 return false;
370 if (!Out.empty())
371 return Out.constrain(isVector);
372
373 return Out.assign_if(getLegalTypes(), isVector);
374}
375
376bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
377 ValidateOnExit _1(Out);
378 if (TP.hasError() || !Out.empty())
379 return false;
380
381 Out = getLegalTypes();
382 return true;
383}
384
385template <typename Iter, typename Pred, typename Less>
386static Iter min_if(Iter B, Iter E, Pred P, Less L) {
387 if (B == E)
388 return E;
389 Iter Min = E;
390 for (Iter I = B; I != E; ++I) {
391 if (!P(*I))
392 continue;
393 if (Min == E || L(*I, *Min))
394 Min = I;
395 }
396 return Min;
397}
398
399template <typename Iter, typename Pred, typename Less>
400static Iter max_if(Iter B, Iter E, Pred P, Less L) {
401 if (B == E)
402 return E;
403 Iter Max = E;
404 for (Iter I = B; I != E; ++I) {
405 if (!P(*I))
406 continue;
407 if (Max == E || L(*Max, *I))
408 Max = I;
409 }
410 return Max;
411}
412
413/// Make sure that for each type in Small, there exists a larger type in Big.
414bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
415 TypeSetByHwMode &Big) {
416 ValidateOnExit _1(Small), _2(Big);
417 if (TP.hasError())
418 return false;
419 bool Changed = false;
420
421 if (Small.empty())
422 Changed |= EnforceAny(Small);
423 if (Big.empty())
424 Changed |= EnforceAny(Big);
425
426 assert(Small.hasDefault() && Big.hasDefault());
427
428 std::vector<unsigned> Modes = union_modes(Small, Big);
429
430 // 1. Only allow integer or floating point types and make sure that
431 // both sides are both integer or both floating point.
432 // 2. Make sure that either both sides have vector types, or neither
433 // of them does.
434 for (unsigned M : Modes) {
435 TypeSetByHwMode::SetType &S = Small.get(M);
436 TypeSetByHwMode::SetType &B = Big.get(M);
437
438 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000439 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000440 Changed |= berase_if(S, NotInt) |
441 berase_if(B, NotInt);
442 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000443 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000444 Changed |= berase_if(S, NotFP) |
445 berase_if(B, NotFP);
446 } else if (S.empty() || B.empty()) {
447 Changed = !S.empty() || !B.empty();
448 S.clear();
449 B.clear();
450 } else {
451 TP.error("Incompatible types");
452 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000453 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000454
455 if (none_of(S, isVector) || none_of(B, isVector)) {
456 Changed |= berase_if(S, isVector) |
457 berase_if(B, isVector);
458 }
459 }
460
461 auto LT = [](MVT A, MVT B) -> bool {
462 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
463 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
464 A.getSizeInBits() < B.getSizeInBits());
465 };
466 auto LE = [](MVT A, MVT B) -> bool {
467 // This function is used when removing elements: when a vector is compared
468 // to a non-vector, it should return false (to avoid removal).
469 if (A.isVector() != B.isVector())
470 return false;
471
472 // Note on the < comparison below:
473 // X86 has patterns like
474 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
475 // where the truncated vector is given a type v16i8, while the source
476 // vector has type v4i32. They both have the same size in bits.
477 // The minimal type in the result is obviously v16i8, and when we remove
478 // all types from the source that are smaller-or-equal than v8i16, the
479 // only source type would also be removed (since it's equal in size).
480 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
481 A.getSizeInBits() < B.getSizeInBits();
482 };
483
484 for (unsigned M : Modes) {
485 TypeSetByHwMode::SetType &S = Small.get(M);
486 TypeSetByHwMode::SetType &B = Big.get(M);
487 // MinS = min scalar in Small, remove all scalars from Big that are
488 // smaller-or-equal than MinS.
489 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
490 if (MinS != S.end()) {
491 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
492 if (B.empty()) {
493 TP.error("Type contradiction in " +
494 Twine(__func__) + ":" + Twine(__LINE__));
495 return Changed;
496 }
497 }
498 // MaxS = max scalar in Big, remove all scalars from Small that are
499 // larger than MaxS.
500 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
501 if (MaxS != B.end()) {
502 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
503 if (B.empty()) {
504 TP.error("Type contradiction in " +
505 Twine(__func__) + ":" + Twine(__LINE__));
506 return Changed;
507 }
508 }
509
510 // MinV = min vector in Small, remove all vectors from Big that are
511 // smaller-or-equal than MinV.
512 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
513 if (MinV != S.end()) {
514 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
515 if (B.empty()) {
516 TP.error("Type contradiction in " +
517 Twine(__func__) + ":" + Twine(__LINE__));
518 return Changed;
519 }
520 }
521 // MaxV = max vector in Big, remove all vectors from Small that are
522 // larger than MaxV.
523 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
524 if (MaxV != B.end()) {
525 Changed |= berase_if(S, std::bind(LE, *MaxV, 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
534 return Changed;
535}
536
537/// 1. Ensure that for each type T in Vec, T is a vector type, and that
538/// for each type U in Elem, U is a scalar type.
539/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
540/// type T in Vec, such that U is the element type of T.
541bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
542 TypeSetByHwMode &Elem) {
543 ValidateOnExit _1(Vec), _2(Elem);
544 if (TP.hasError())
545 return false;
546 bool Changed = false;
547
548 if (Vec.empty())
549 Changed |= EnforceVector(Vec);
550 if (Elem.empty())
551 Changed |= EnforceScalar(Elem);
552
553 for (unsigned M : union_modes(Vec, Elem)) {
554 TypeSetByHwMode::SetType &V = Vec.get(M);
555 TypeSetByHwMode::SetType &E = Elem.get(M);
556
557 Changed |= berase_if(V, isScalar); // Scalar = !vector
558 Changed |= berase_if(E, isVector); // Vector = !scalar
559 assert(!V.empty() && !E.empty());
560
561 SmallSet<MVT,4> VT, ST;
562 // Collect element types from the "vector" set.
563 for (MVT T : V)
564 VT.insert(T.getVectorElementType());
565 // Collect scalar types from the "element" set.
566 for (MVT T : E)
567 ST.insert(T);
568
569 // Remove from V all (vector) types whose element type is not in S.
570 Changed |= berase_if(V, [&ST](MVT T) -> bool {
571 return !ST.count(T.getVectorElementType());
572 });
573 // Remove from E all (scalar) types, for which there is no corresponding
574 // type in V.
575 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
576
577 if (V.empty() || E.empty()) {
578 TP.error("Type contradiction in " +
579 Twine(__func__) + ":" + Twine(__LINE__));
580 return Changed;
581 }
582 }
583
584 return Changed;
585}
586
587bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
588 const ValueTypeByHwMode &VVT) {
589 TypeSetByHwMode Tmp(VVT);
590 ValidateOnExit _1(Vec), _2(Tmp);
591 return EnforceVectorEltTypeIs(Vec, Tmp);
592}
593
594/// Ensure that for each type T in Sub, T is a vector type, and there
595/// exists a type U in Vec such that U is a vector type with the same
596/// element type as T and at least as many elements as T.
597bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
598 TypeSetByHwMode &Sub) {
599 ValidateOnExit _1(Vec), _2(Sub);
600 if (TP.hasError())
601 return false;
602
603 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
604 auto IsSubVec = [](MVT B, MVT P) -> bool {
605 if (!B.isVector() || !P.isVector())
606 return false;
607 if (B.getVectorElementType() != P.getVectorElementType())
608 return false;
609 return B.getVectorNumElements() < P.getVectorNumElements();
610 };
611
612 /// Return true if S has no element (vector type) that T is a sub-vector of,
613 /// i.e. has the same element type as T and more elements.
614 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
615 for (const auto &I : S)
616 if (IsSubVec(T, I))
617 return false;
618 return true;
619 };
620
621 /// Return true if S has no element (vector type) that T is a super-vector
622 /// of, i.e. has the same element type as T and fewer elements.
623 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
624 for (const auto &I : S)
625 if (IsSubVec(I, T))
626 return false;
627 return true;
628 };
629
630 bool Changed = false;
631
632 if (Vec.empty())
633 Changed |= EnforceVector(Vec);
634 if (Sub.empty())
635 Changed |= EnforceVector(Sub);
636
637 for (unsigned M : union_modes(Vec, Sub)) {
638 TypeSetByHwMode::SetType &S = Sub.get(M);
639 TypeSetByHwMode::SetType &V = Vec.get(M);
640
641 Changed |= berase_if(S, isScalar);
642 if (S.empty()) {
643 TP.error("Type contradiction in " +
644 Twine(__func__) + ":" + Twine(__LINE__));
645 return Changed;
646 }
647
648 // Erase all types from S that are not sub-vectors of a type in V.
649 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
650 if (S.empty()) {
651 TP.error("Type contradiction in " +
652 Twine(__func__) + ":" + Twine(__LINE__));
653 return Changed;
654 }
655
656 // Erase all types from V that are not super-vectors of a type in S.
657 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
658 if (V.empty()) {
659 TP.error("Type contradiction in " +
660 Twine(__func__) + ":" + Twine(__LINE__));
661 return Changed;
662 }
663 }
664
665 return Changed;
666}
667
668/// 1. Ensure that V has a scalar type iff W has a scalar type.
669/// 2. Ensure that for each vector type T in V, there exists a vector
670/// type U in W, such that T and U have the same number of elements.
671/// 3. Ensure that for each vector type U in W, there exists a vector
672/// type T in V, such that T and U have the same number of elements
673/// (reverse of 2).
674bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
675 ValidateOnExit _1(V), _2(W);
676 if (TP.hasError())
677 return false;
678
679 bool Changed = false;
680 if (V.empty())
681 Changed |= EnforceAny(V);
682 if (W.empty())
683 Changed |= EnforceAny(W);
684
685 // An actual vector type cannot have 0 elements, so we can treat scalars
686 // as zero-length vectors. This way both vectors and scalars can be
687 // processed identically.
688 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
689 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
690 };
691
692 for (unsigned M : union_modes(V, W)) {
693 TypeSetByHwMode::SetType &VS = V.get(M);
694 TypeSetByHwMode::SetType &WS = W.get(M);
695
696 SmallSet<unsigned,2> VN, WN;
697 for (MVT T : VS)
698 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
699 for (MVT T : WS)
700 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
701
702 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
703 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
704 }
705 return Changed;
706}
707
708/// 1. Ensure that for each type T in A, there exists a type U in B,
709/// such that T and U have equal size in bits.
710/// 2. Ensure that for each type U in B, there exists a type T in A
711/// such that T and U have equal size in bits (reverse of 1).
712bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
713 ValidateOnExit _1(A), _2(B);
714 if (TP.hasError())
715 return false;
716 bool Changed = false;
717 if (A.empty())
718 Changed |= EnforceAny(A);
719 if (B.empty())
720 Changed |= EnforceAny(B);
721
722 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
723 return !Sizes.count(T.getSizeInBits());
724 };
725
726 for (unsigned M : union_modes(A, B)) {
727 TypeSetByHwMode::SetType &AS = A.get(M);
728 TypeSetByHwMode::SetType &BS = B.get(M);
729 SmallSet<unsigned,2> AN, BN;
730
731 for (MVT T : AS)
732 AN.insert(T.getSizeInBits());
733 for (MVT T : BS)
734 BN.insert(T.getSizeInBits());
735
736 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
737 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
738 }
739
740 return Changed;
741}
742
743void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
744 ValidateOnExit _1(VTS);
745 TypeSetByHwMode Legal = getLegalTypes();
746 bool HaveLegalDef = Legal.hasDefault();
747
748 for (auto &I : VTS) {
749 unsigned M = I.first;
750 if (!Legal.hasMode(M) && !HaveLegalDef) {
751 TP.error("Invalid mode " + Twine(M));
752 return;
753 }
754 expandOverloads(I.second, Legal.get(M));
Scott Michel94420742008-03-05 17:49:05 +0000755 }
756}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000757
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000758void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
759 const TypeSetByHwMode::SetType &Legal) {
760 std::set<MVT> Ovs;
761 for (auto I = Out.begin(); I != Out.end(); ) {
762 if (I->isOverloaded()) {
763 Ovs.insert(*I);
764 I = Out.erase(I);
765 continue;
766 }
767 ++I;
768 }
769
770 for (MVT Ov : Ovs) {
771 switch (Ov.SimpleTy) {
772 case MVT::iPTRAny:
773 Out.insert(MVT::iPTR);
774 return;
775 case MVT::iAny:
776 for (MVT T : MVT::integer_valuetypes())
777 if (Legal.count(T))
778 Out.insert(T);
779 for (MVT T : MVT::integer_vector_valuetypes())
780 if (Legal.count(T))
781 Out.insert(T);
782 return;
783 case MVT::fAny:
784 for (MVT T : MVT::fp_valuetypes())
785 if (Legal.count(T))
786 Out.insert(T);
787 for (MVT T : MVT::fp_vector_valuetypes())
788 if (Legal.count(T))
789 Out.insert(T);
790 return;
791 case MVT::vAny:
792 for (MVT T : MVT::vector_valuetypes())
793 if (Legal.count(T))
794 Out.insert(T);
795 return;
796 case MVT::Any:
797 for (MVT T : MVT::all_valuetypes())
798 if (Legal.count(T))
799 Out.insert(T);
800 return;
801 default:
802 break;
803 }
804 }
805}
806
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000807TypeSetByHwMode TypeInfer::getLegalTypes() {
808 TypeSetByHwMode VTS;
809 TypeSetByHwMode::SetType &DS = VTS.getOrCreate(DefaultMode);
810 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
811
Krzysztof Parzyszek89291f22017-09-15 18:58:07 +0000812 // Stuff all types from all modes into the default mode.
813 for (const auto &I : LTS)
814 DS.insert(I.second.begin(), I.second.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000815 return VTS;
816}
Chris Lattner514e2922011-04-17 21:38:24 +0000817
818//===----------------------------------------------------------------------===//
819// TreePredicateFn Implementation
820//===----------------------------------------------------------------------===//
821
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000822/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
823TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
824 assert((getPredCode().empty() || getImmCode().empty()) &&
825 ".td file corrupt: can't have a node predicate *and* an imm predicate");
826}
827
Chris Lattner514e2922011-04-17 21:38:24 +0000828std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000829 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000830}
831
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000832std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000833 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000834}
835
Chris Lattner514e2922011-04-17 21:38:24 +0000836
837/// isAlwaysTrue - Return true if this is a noop predicate.
838bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000839 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000840}
841
842/// Return the name to use in the generated code to reference this, this is
843/// "Predicate_foo" if from a pattern fragment "foo".
844std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +0000845 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +0000846}
847
848/// getCodeToRunOnSDNode - Return the code for the function body that
849/// evaluates this predicate. The argument is expected to be in "Node",
850/// not N. This handles casting and conversion to a concrete node type as
851/// appropriate.
852std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000853 // Handle immediate predicates first.
854 std::string ImmCode = getImmCode();
855 if (!ImmCode.empty()) {
856 std::string Result =
857 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000858 return Result + ImmCode;
859 }
860
861 // Handle arbitrary node predicates.
862 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000863 std::string ClassName;
864 if (PatFragRec->getOnlyTree()->isLeaf())
865 ClassName = "SDNode";
866 else {
867 Record *Op = PatFragRec->getOnlyTree()->getOperator();
868 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
869 }
870 std::string Result;
871 if (ClassName == "SDNode")
872 Result = " SDNode *N = Node;\n";
873 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000874 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000875
876 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000877}
878
Chris Lattner8cab0212008-01-05 22:25:12 +0000879//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000880// PatternToMatch implementation
881//
882
Chris Lattner05925fe2010-03-29 01:40:38 +0000883/// getPatternSize - Return the 'size' of this pattern. We want to match large
884/// patterns before small ones. This is used to determine the size of a
885/// pattern.
886static unsigned getPatternSize(const TreePatternNode *P,
887 const CodeGenDAGPatterns &CGP) {
888 unsigned Size = 3; // The node itself.
889 // If the root node is a ConstantSDNode, increases its size.
890 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000891 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000892 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000893
Chris Lattner05925fe2010-03-29 01:40:38 +0000894 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000895 if (AM) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000896 Size += AM->getComplexity();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000897
Tim Northoverc807a172014-05-20 11:52:46 +0000898 // We don't want to count any children twice, so return early.
899 return Size;
900 }
901
Chris Lattner05925fe2010-03-29 01:40:38 +0000902 // If this node has some predicate function that must match, it adds to the
903 // complexity of this node.
904 if (!P->getPredicateFns().empty())
905 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000906
Chris Lattner05925fe2010-03-29 01:40:38 +0000907 // Count children in the count if they are also nodes.
908 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
909 TreePatternNode *Child = P->getChild(i);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000910 if (!Child->isLeaf() && Child->getNumTypes()) {
911 const TypeSetByHwMode &T0 = Child->getType(0);
912 // At this point, all variable type sets should be simple, i.e. only
913 // have a default mode.
914 if (T0.getMachineValueType() != MVT::Other) {
915 Size += getPatternSize(Child, CGP);
916 continue;
917 }
918 }
919 if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000920 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000921 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
922 else if (Child->getComplexPatternInfo(CGP))
923 Size += getPatternSize(Child, CGP);
924 else if (!Child->getPredicateFns().empty())
925 ++Size;
926 }
927 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000928
Chris Lattner05925fe2010-03-29 01:40:38 +0000929 return Size;
930}
931
932/// Compute the complexity metric for the input pattern. This roughly
933/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000934int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000935getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
936 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
937}
938
Dan Gohman49e19e92008-08-22 00:20:26 +0000939/// getPredicateCheck - Return a single string containing all of this
940/// pattern's predicates concatenated with "&&" operators.
941///
942std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000943 SmallVector<const Predicate*,4> PredList;
944 for (const Predicate &P : Predicates)
945 PredList.push_back(&P);
946 std::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +0000947
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000948 std::string Check;
949 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
950 if (i != 0)
951 Check += " && ";
952 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +0000953 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000954 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +0000955}
956
957//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000958// SDTypeConstraint implementation
959//
960
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000961SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000962 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000963
Chris Lattner8cab0212008-01-05 22:25:12 +0000964 if (R->isSubClassOf("SDTCisVT")) {
965 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000966 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
967 for (const auto &P : VVT)
968 if (P.second == MVT::isVoid)
969 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +0000970 } else if (R->isSubClassOf("SDTCisPtrTy")) {
971 ConstraintType = SDTCisPtrTy;
972 } else if (R->isSubClassOf("SDTCisInt")) {
973 ConstraintType = SDTCisInt;
974 } else if (R->isSubClassOf("SDTCisFP")) {
975 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000976 } else if (R->isSubClassOf("SDTCisVec")) {
977 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000978 } else if (R->isSubClassOf("SDTCisSameAs")) {
979 ConstraintType = SDTCisSameAs;
980 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
981 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
982 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000983 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000984 R->getValueAsInt("OtherOperandNum");
985 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
986 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000987 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000988 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000989 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
990 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000991 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000992 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
993 ConstraintType = SDTCisSubVecOfVec;
994 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
995 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000996 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
997 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000998 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
999 for (const auto &P : VVT) {
1000 MVT T = P.second;
1001 if (T.isVector())
1002 PrintFatalError(R->getLoc(),
1003 "Cannot use vector type as SDTCVecEltisVT");
1004 if (!T.isInteger() && !T.isFloatingPoint())
1005 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1006 "as SDTCVecEltisVT");
1007 }
Craig Topper0be34582015-03-05 07:11:34 +00001008 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1009 ConstraintType = SDTCisSameNumEltsAs;
1010 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1011 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001012 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1013 ConstraintType = SDTCisSameSizeAs;
1014 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1015 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001016 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001017 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001018 }
1019}
1020
1021/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001022/// N, and the result number in ResNo.
1023static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1024 const SDNodeInfo &NodeInfo,
1025 unsigned &ResNo) {
1026 unsigned NumResults = NodeInfo.getNumResults();
1027 if (OpNo < NumResults) {
1028 ResNo = OpNo;
1029 return N;
1030 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001031
Chris Lattner2db7aba2010-03-19 21:56:21 +00001032 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001033
Chris Lattner2db7aba2010-03-19 21:56:21 +00001034 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001035 std::string S;
1036 raw_string_ostream OS(S);
1037 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001038 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +00001039 N->print(OS);
1040 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001041 }
1042
Chris Lattner2db7aba2010-03-19 21:56:21 +00001043 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001044}
1045
1046/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1047/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001048/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001049bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1050 const SDNodeInfo &NodeInfo,
1051 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001052 if (TP.hasError())
1053 return false;
1054
Chris Lattner2db7aba2010-03-19 21:56:21 +00001055 unsigned ResNo = 0; // The result number being referenced.
1056 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001057 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001058
Chris Lattner8cab0212008-01-05 22:25:12 +00001059 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001060 case SDTCisVT:
1061 // Operand must be a particular type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001062 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001063 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001064 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001065 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001066 case SDTCisInt:
1067 // Require it to be one of the legal integer VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001068 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001069 case SDTCisFP:
1070 // Require it to be one of the legal fp VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001071 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001072 case SDTCisVec:
1073 // Require it to be one of the legal vector VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001074 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001075 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001076 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001077 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001078 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001079 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1080 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001081 }
1082 case SDTCisVTSmallerThanOp: {
1083 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1084 // have an integer type that is smaller than the VT.
1085 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001086 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001087 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001088 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001089 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001090 return false;
1091 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001092 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1093 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1094 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1095 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001096
Chris Lattner2db7aba2010-03-19 21:56:21 +00001097 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001098 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001099 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1100 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001101
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001102 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001103 }
1104 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001105 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001106 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001107 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1108 BResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001109 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1110 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001111 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001112 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001113 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001114 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001115 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1116 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001117 // Filter vector types out of VecOperand that don't have the right element
1118 // type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001119 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1120 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001121 }
David Greene127fd1d2011-01-24 20:53:18 +00001122 case SDTCisSubVecOfVec: {
1123 unsigned VResNo = 0;
1124 TreePatternNode *BigVecOperand =
1125 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1126 VResNo);
1127
1128 // Filter vector types out of BigVecOperand that don't have the
1129 // right subvector type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001130 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1131 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001132 }
Craig Topper0be34582015-03-05 07:11:34 +00001133 case SDTCVecEltisVT: {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001134 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001135 }
1136 case SDTCisSameNumEltsAs: {
1137 unsigned OResNo = 0;
1138 TreePatternNode *OtherNode =
1139 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1140 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001141 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1142 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001143 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001144 case SDTCisSameSizeAs: {
1145 unsigned OResNo = 0;
1146 TreePatternNode *OtherNode =
1147 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1148 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001149 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1150 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001151 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001152 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001153 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001154}
1155
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001156// Update the node type to match an instruction operand or result as specified
1157// in the ins or outs lists on the instruction definition. Return true if the
1158// type was actually changed.
1159bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1160 Record *Operand,
1161 TreePattern &TP) {
1162 // The 'unknown' operand indicates that types should be inferred from the
1163 // context.
1164 if (Operand->isSubClassOf("unknown_class"))
1165 return false;
1166
1167 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001168 if (Operand->isSubClassOf("Operand")) {
1169 Record *R = Operand->getValueAsDef("Type");
1170 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1171 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1172 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001173
1174 // PointerLikeRegClass has a type that is determined at runtime.
1175 if (Operand->isSubClassOf("PointerLikeRegClass"))
1176 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1177
1178 // Both RegisterClass and RegisterOperand operands derive their types from a
1179 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001180 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001181 if (Operand->isSubClassOf("RegisterClass"))
1182 RC = Operand;
1183 else if (Operand->isSubClassOf("RegisterOperand"))
1184 RC = Operand->getValueAsDef("RegClass");
1185
1186 assert(RC && "Unknown operand type");
1187 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1188 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1189}
1190
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001191bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1192 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1193 if (!TP.getInfer().isConcrete(Types[i], true))
1194 return true;
1195 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1196 if (getChild(i)->ContainsUnresolvedType(TP))
1197 return true;
1198 return false;
1199}
1200
1201bool TreePatternNode::hasProperTypeByHwMode() const {
1202 for (const TypeSetByHwMode &S : Types)
1203 if (!S.isDefaultOnly())
1204 return true;
1205 for (TreePatternNode *C : Children)
1206 if (C->hasProperTypeByHwMode())
1207 return true;
1208 return false;
1209}
1210
1211bool TreePatternNode::hasPossibleType() const {
1212 for (const TypeSetByHwMode &S : Types)
1213 if (!S.isPossible())
1214 return false;
1215 for (TreePatternNode *C : Children)
1216 if (!C->hasPossibleType())
1217 return false;
1218 return true;
1219}
1220
1221bool TreePatternNode::setDefaultMode(unsigned Mode) {
1222 for (TypeSetByHwMode &S : Types) {
1223 S.makeSimple(Mode);
1224 // Check if the selected mode had a type conflict.
1225 if (S.get(DefaultMode).empty())
1226 return false;
1227 }
1228 for (TreePatternNode *C : Children)
1229 if (!C->setDefaultMode(Mode))
1230 return false;
1231 return true;
1232}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001233
Chris Lattner8cab0212008-01-05 22:25:12 +00001234//===----------------------------------------------------------------------===//
1235// SDNodeInfo implementation
1236//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001237SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001238 EnumName = R->getValueAsString("Opcode");
1239 SDClassName = R->getValueAsString("SDClass");
1240 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1241 NumResults = TypeProfile->getValueAsInt("NumResults");
1242 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001243
Chris Lattner8cab0212008-01-05 22:25:12 +00001244 // Parse the properties.
1245 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001246 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1247 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001248 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001249 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001250 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001251 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001252 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001253 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001254 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001255 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001256 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001257 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001258 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001259 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001260 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001261 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001262 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001263 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001264 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001265 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001266 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001267 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001268 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001269 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001270 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001271 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001272 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001273 }
1274 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001275
1276
Chris Lattner8cab0212008-01-05 22:25:12 +00001277 // Parse the type constraints.
1278 std::vector<Record*> ConstraintList =
1279 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001280 for (Record *R : ConstraintList)
1281 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001282}
1283
Chris Lattner99e53b32010-02-28 00:22:30 +00001284/// getKnownType - If the type constraints on this node imply a fixed type
1285/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001286/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001287MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001288 unsigned NumResults = getNumResults();
1289 assert(NumResults <= 1 &&
1290 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001291 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001292
Craig Topper306cb122015-11-22 20:46:24 +00001293 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001294 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001295 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001296 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001297
Craig Topper306cb122015-11-22 20:46:24 +00001298 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001299 default: break;
1300 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001301 if (Constraint.VVT.isSimple())
1302 return Constraint.VVT.getSimple().SimpleTy;
1303 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001304 case SDTypeConstraint::SDTCisPtrTy:
1305 return MVT::iPTR;
1306 }
1307 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001308 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001309}
1310
Chris Lattner8cab0212008-01-05 22:25:12 +00001311//===----------------------------------------------------------------------===//
1312// TreePatternNode implementation
1313//
1314
1315TreePatternNode::~TreePatternNode() {
1316#if 0 // FIXME: implement refcounted tree nodes!
1317 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1318 delete getChild(i);
1319#endif
1320}
1321
Chris Lattnerf1447252010-03-19 21:37:09 +00001322static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1323 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001324 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001325 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001326
Chris Lattner2109cb42010-03-22 20:56:36 +00001327 if (Operator->isSubClassOf("Intrinsic"))
1328 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001329
Chris Lattnerf1447252010-03-19 21:37:09 +00001330 if (Operator->isSubClassOf("SDNode"))
1331 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001332
Chris Lattnerf1447252010-03-19 21:37:09 +00001333 if (Operator->isSubClassOf("PatFrag")) {
1334 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1335 // the forward reference case where one pattern fragment references another
1336 // before it is processed.
1337 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1338 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001339
Chris Lattnerf1447252010-03-19 21:37:09 +00001340 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001341 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001342 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001343 if (Tree)
1344 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1345 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001346 assert(Op && "Invalid Fragment");
1347 return GetNumNodeResults(Op, CDP);
1348 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001349
Chris Lattnerf1447252010-03-19 21:37:09 +00001350 if (Operator->isSubClassOf("Instruction")) {
1351 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001352
Craig Topper3a8eb892015-03-20 05:09:06 +00001353 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1354
1355 // Subtract any defaulted outputs.
1356 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1357 Record *OperandNode = InstInfo.Operands[i].Rec;
1358
1359 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1360 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1361 --NumDefsToAdd;
1362 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001363
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001364 // Add on one implicit def if it has a resolvable type.
1365 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1366 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001367 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001368 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001369
Chris Lattnerf1447252010-03-19 21:37:09 +00001370 if (Operator->isSubClassOf("SDNodeXForm"))
1371 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001372
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001373 if (Operator->isSubClassOf("ValueType"))
1374 return 1; // A type-cast of one result.
1375
Tim Northoverc807a172014-05-20 11:52:46 +00001376 if (Operator->isSubClassOf("ComplexPattern"))
1377 return 1;
1378
Matthias Braun8c209aa2017-01-28 02:02:38 +00001379 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001380 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001381}
1382
1383void TreePatternNode::print(raw_ostream &OS) const {
1384 if (isLeaf())
1385 OS << *getLeafValue();
1386 else
1387 OS << '(' << getOperator()->getName();
1388
1389 for (unsigned i = 0, e = Types.size(); i != e; ++i)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001390 OS << ':' << getExtType(i).getAsString();
Chris Lattner8cab0212008-01-05 22:25:12 +00001391
1392 if (!isLeaf()) {
1393 if (getNumChildren() != 0) {
1394 OS << " ";
1395 getChild(0)->print(OS);
1396 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1397 OS << ", ";
1398 getChild(i)->print(OS);
1399 }
1400 }
1401 OS << ")";
1402 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001403
Craig Topper306cb122015-11-22 20:46:24 +00001404 for (const TreePredicateFn &Pred : PredicateFns)
1405 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001406 if (TransformFn)
1407 OS << "<<X:" << TransformFn->getName() << ">>";
1408 if (!getName().empty())
1409 OS << ":$" << getName();
1410
1411}
1412void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001413 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001414}
1415
Scott Michel94420742008-03-05 17:49:05 +00001416/// isIsomorphicTo - Return true if this node is recursively
1417/// isomorphic to the specified node. For this comparison, the node's
1418/// entire state is considered. The assigned name is ignored, since
1419/// nodes with differing names are considered isomorphic. However, if
1420/// the assigned name is present in the dependent variable set, then
1421/// the assigned name is considered significant and the node is
1422/// isomorphic if the names match.
1423bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1424 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001425 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001426 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001427 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001428 getTransformFn() != N->getTransformFn())
1429 return false;
1430
1431 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001432 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1433 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001434 return ((DI->getDef() == NDI->getDef())
1435 && (DepVars.find(getName()) == DepVars.end()
1436 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001437 }
1438 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001439 return getLeafValue() == N->getLeafValue();
1440 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001441
Chris Lattner8cab0212008-01-05 22:25:12 +00001442 if (N->getOperator() != getOperator() ||
1443 N->getNumChildren() != getNumChildren()) return false;
1444 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001445 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001446 return false;
1447 return true;
1448}
1449
1450/// clone - Make a copy of this tree and all of its children.
1451///
1452TreePatternNode *TreePatternNode::clone() const {
1453 TreePatternNode *New;
1454 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001455 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001456 } else {
1457 std::vector<TreePatternNode*> CChildren;
1458 CChildren.reserve(Children.size());
1459 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1460 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001461 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001462 }
1463 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001464 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001465 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001466 New->setTransformFn(getTransformFn());
1467 return New;
1468}
1469
Chris Lattner53c39ba2010-02-14 22:22:58 +00001470/// RemoveAllTypes - Recursively strip all the types of this tree.
1471void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001472 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001473 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001474 if (isLeaf()) return;
1475 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1476 getChild(i)->RemoveAllTypes();
1477}
1478
1479
Chris Lattner8cab0212008-01-05 22:25:12 +00001480/// SubstituteFormalArguments - Replace the formal arguments in this tree
1481/// with actual values specified by ArgMap.
1482void TreePatternNode::
1483SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1484 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001485
Chris Lattner8cab0212008-01-05 22:25:12 +00001486 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1487 TreePatternNode *Child = getChild(i);
1488 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001489 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001490 // Note that, when substituting into an output pattern, Val might be an
1491 // UnsetInit.
1492 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1493 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001494 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001495 TreePatternNode *NewChild = ArgMap[Child->getName()];
1496 assert(NewChild && "Couldn't find formal argument!");
1497 assert((Child->getPredicateFns().empty() ||
1498 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1499 "Non-empty child predicate clobbered!");
1500 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001501 }
1502 } else {
1503 getChild(i)->SubstituteFormalArguments(ArgMap);
1504 }
1505 }
1506}
1507
1508
1509/// InlinePatternFragments - If this pattern refers to any pattern
1510/// fragments, inline them into place, giving us a pattern without any
1511/// PatFrag references.
1512TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001513 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001514 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001515
1516 if (isLeaf())
1517 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001518 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001519
Chris Lattner8cab0212008-01-05 22:25:12 +00001520 if (!Op->isSubClassOf("PatFrag")) {
1521 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001522 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1523 TreePatternNode *Child = getChild(i);
1524 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1525
1526 assert((Child->getPredicateFns().empty() ||
1527 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1528 "Non-empty child predicate clobbered!");
1529
1530 setChild(i, NewChild);
1531 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001532 return this;
1533 }
1534
1535 // Otherwise, we found a reference to a fragment. First, look up its
1536 // TreePattern record.
1537 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001538
Chris Lattner8cab0212008-01-05 22:25:12 +00001539 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001540 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001541 TP.error("'" + Op->getName() + "' fragment requires " +
1542 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001543 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001544 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001545
1546 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1547
Chris Lattner514e2922011-04-17 21:38:24 +00001548 TreePredicateFn PredFn(Frag);
1549 if (!PredFn.isAlwaysTrue())
1550 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001551
Chris Lattner8cab0212008-01-05 22:25:12 +00001552 // Resolve formal arguments to their actual value.
1553 if (Frag->getNumArgs()) {
1554 // Compute the map of formal to actual arguments.
1555 std::map<std::string, TreePatternNode*> ArgMap;
1556 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1557 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001558
Chris Lattner8cab0212008-01-05 22:25:12 +00001559 FragTree->SubstituteFormalArguments(ArgMap);
1560 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001561
Chris Lattner8cab0212008-01-05 22:25:12 +00001562 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001563 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1564 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001565
1566 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001567 for (const TreePredicateFn &Pred : getPredicateFns())
1568 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001569
Chris Lattner8cab0212008-01-05 22:25:12 +00001570 // Get a new copy of this fragment to stitch into here.
1571 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001572
Chris Lattner2e253b42008-06-30 03:02:03 +00001573 // The fragment we inlined could have recursive inlining that is needed. See
1574 // if there are any pattern fragments in it and inline them as needed.
1575 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001576}
1577
1578/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001579/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001580/// references from the register file information, for example.
1581///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001582/// When Unnamed is set, return the type of a DAG operand with no name, such as
1583/// the F8RC register class argument in:
1584///
1585/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1586///
1587/// When Unnamed is false, return the type of a named DAG operand such as the
1588/// GPR:$src operand above.
1589///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001590static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1591 bool NotRegisters,
1592 bool Unnamed,
1593 TreePattern &TP) {
1594 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1595
Owen Andersona84be6c2011-06-27 21:06:21 +00001596 // Check to see if this is a register operand.
1597 if (R->isSubClassOf("RegisterOperand")) {
1598 assert(ResNo == 0 && "Regoperand ref only has one result!");
1599 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001600 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00001601 Record *RegClass = R->getValueAsDef("RegClass");
1602 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001603 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00001604 }
1605
Chris Lattnercabe0372010-03-15 06:00:16 +00001606 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001607 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001608 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001609 // An unnamed register class represents itself as an i32 immediate, for
1610 // example on a COPY_TO_REGCLASS instruction.
1611 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001612 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001613
1614 // In a named operand, the register class provides the possible set of
1615 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001616 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001617 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00001618 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001619 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001620 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001621
Chris Lattner6070ee22010-03-23 23:50:31 +00001622 if (R->isSubClassOf("PatFrag")) {
1623 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001624 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001625 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001626 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001627
Chris Lattner6070ee22010-03-23 23:50:31 +00001628 if (R->isSubClassOf("Register")) {
1629 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001630 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001631 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001632 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001633 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001634 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001635
1636 if (R->isSubClassOf("SubRegIndex")) {
1637 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001638 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001639 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001640
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001641 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001642 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001643 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1644 //
1645 // (sext_inreg GPR:$src, i16)
1646 // ~~~
1647 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001648 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001649 // With a name, the ValueType simply provides the type of the named
1650 // variable.
1651 //
1652 // (sext_inreg i32:$src, i16)
1653 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001654 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001655 return TypeSetByHwMode(); // Unknown.
1656 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1657 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001658 }
1659
1660 if (R->isSubClassOf("CondCode")) {
1661 assert(ResNo == 0 && "This node only has one result!");
1662 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001663 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00001664 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001665
Chris Lattner6070ee22010-03-23 23:50:31 +00001666 if (R->isSubClassOf("ComplexPattern")) {
1667 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001668 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001669 return TypeSetByHwMode(); // Unknown.
1670 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00001671 }
1672 if (R->isSubClassOf("PointerLikeRegClass")) {
1673 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001674 TypeSetByHwMode VTS(MVT::iPTR);
1675 TP.getInfer().expandOverloads(VTS);
1676 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00001677 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001678
Chris Lattner6070ee22010-03-23 23:50:31 +00001679 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1680 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001681 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001682 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001683 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001684
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001685 if (R->isSubClassOf("Operand")) {
1686 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1687 Record *T = R->getValueAsDef("Type");
1688 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
1689 }
Tim Northoverc807a172014-05-20 11:52:46 +00001690
Chris Lattner8cab0212008-01-05 22:25:12 +00001691 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001692 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00001693}
1694
Chris Lattner89c65662008-01-06 05:36:50 +00001695
1696/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1697/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1698const CodeGenIntrinsic *TreePatternNode::
1699getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1700 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1701 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1702 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001703 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001704
Sean Silva88eb8dd2012-10-10 20:24:47 +00001705 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001706 return &CDP.getIntrinsicInfo(IID);
1707}
1708
Chris Lattner53c39ba2010-02-14 22:22:58 +00001709/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1710/// return the ComplexPattern information, otherwise return null.
1711const ComplexPattern *
1712TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001713 Record *Rec;
1714 if (isLeaf()) {
1715 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1716 if (!DI)
1717 return nullptr;
1718 Rec = DI->getDef();
1719 } else
1720 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001721
Tim Northoverc807a172014-05-20 11:52:46 +00001722 if (!Rec->isSubClassOf("ComplexPattern"))
1723 return nullptr;
1724 return &CGP.getComplexPattern(Rec);
1725}
1726
1727unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1728 // A ComplexPattern specifically declares how many results it fills in.
1729 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1730 return CP->getNumOperands();
1731
1732 // If MIOperandInfo is specified, that gives the count.
1733 if (isLeaf()) {
1734 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1735 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1736 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1737 if (MIOps->getNumArgs())
1738 return MIOps->getNumArgs();
1739 }
1740 }
1741
1742 // Otherwise there is just one result.
1743 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001744}
1745
1746/// NodeHasProperty - Return true if this node has the specified property.
1747bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001748 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001749 if (isLeaf()) {
1750 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1751 return CP->hasProperty(Property);
1752 return false;
1753 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001754
Chris Lattner53c39ba2010-02-14 22:22:58 +00001755 Record *Operator = getOperator();
1756 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001757
Chris Lattner53c39ba2010-02-14 22:22:58 +00001758 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1759}
1760
1761
1762
1763
1764/// TreeHasProperty - Return true if any node in this tree has the specified
1765/// property.
1766bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001767 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001768 if (NodeHasProperty(Property, CGP))
1769 return true;
1770 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1771 if (getChild(i)->TreeHasProperty(Property, CGP))
1772 return true;
1773 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001774}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001775
Evan Cheng49bad4c2008-06-16 20:29:38 +00001776/// isCommutativeIntrinsic - Return true if the node corresponds to a
1777/// commutative intrinsic.
1778bool
1779TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1780 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1781 return Int->isCommutative;
1782 return false;
1783}
1784
Matt Arsenaulteb492162014-11-02 23:46:51 +00001785static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1786 if (!N->isLeaf())
1787 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001788
Matt Arsenaulteb492162014-11-02 23:46:51 +00001789 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1790 if (DI && DI->getDef()->isSubClassOf(Class))
1791 return true;
1792
1793 return false;
1794}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001795
1796static void emitTooManyOperandsError(TreePattern &TP,
1797 StringRef InstName,
1798 unsigned Expected,
1799 unsigned Actual) {
1800 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1801 " operands but expected only " + Twine(Expected) + "!");
1802}
1803
1804static void emitTooFewOperandsError(TreePattern &TP,
1805 StringRef InstName,
1806 unsigned Actual) {
1807 TP.error("Instruction '" + InstName +
1808 "' expects more than the provided " + Twine(Actual) + " operands!");
1809}
1810
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001811/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001812/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001813/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001814bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001815 if (TP.hasError())
1816 return false;
1817
Chris Lattnerab3242f2008-01-06 01:10:31 +00001818 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001819 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001820 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001821 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001822 bool MadeChange = false;
1823 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1824 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001825 NotRegisters,
1826 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001827 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001828 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001829
Sean Silvafb509ed2012-10-10 20:24:43 +00001830 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001831 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001832
Chris Lattnerf1447252010-03-19 21:37:09 +00001833 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001834 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001835
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001836 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00001837 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001838
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001839 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
1840 for (auto &P : VVT) {
1841 MVT::SimpleValueType VT = P.second.SimpleTy;
1842 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1843 continue;
1844 unsigned Size = MVT(VT).getSizeInBits();
1845 // Make sure that the value is representable for this type.
1846 if (Size >= 32)
1847 continue;
1848 // Check that the value doesn't use more bits than we have. It must
1849 // either be a sign- or zero-extended equivalent of the original.
1850 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1851 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
1852 SignBitAndAbove == 1)
1853 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001854
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001855 TP.error("Integer value '" + itostr(II->getValue()) +
1856 "' is out of range for type '" + getEnumName(VT) + "'!");
1857 break;
1858 }
1859 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001860 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001861
Chris Lattner8cab0212008-01-05 22:25:12 +00001862 return false;
1863 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001864
Chris Lattner8cab0212008-01-05 22:25:12 +00001865 // special handling for set, which isn't really an SDNode.
1866 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001867 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1868 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001869 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001870
Chris Lattnerf1447252010-03-19 21:37:09 +00001871 TreePatternNode *SetVal = getChild(NC-1);
1872 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1873
Elena Demikhovsky09954792015-03-01 08:23:41 +00001874 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001875 TreePatternNode *Child = getChild(i);
1876 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001877
Chris Lattner8cab0212008-01-05 22:25:12 +00001878 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001879 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1880 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001881 }
1882 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001883 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001884
Chris Lattner5c2182e2010-03-27 02:53:27 +00001885 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001886 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1887
Chris Lattner8cab0212008-01-05 22:25:12 +00001888 bool MadeChange = false;
1889 for (unsigned i = 0; i < getNumChildren(); ++i)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001890 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001891 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001892 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001893
Chris Lattneree820ac2010-02-23 05:51:07 +00001894 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001895 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001896
Chris Lattner8cab0212008-01-05 22:25:12 +00001897 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001898 unsigned NumRetVTs = Int->IS.RetVTs.size();
1899 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001900
Bill Wendling91821472008-11-13 09:08:33 +00001901 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001902 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001903
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001904 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001905 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001906 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001907 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001908 return false;
1909 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001910
1911 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001912 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001913
Chris Lattnerf1447252010-03-19 21:37:09 +00001914 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1915 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001916
Chris Lattnerf1447252010-03-19 21:37:09 +00001917 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1918 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1919 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001920 }
1921 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001922 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001923
Chris Lattneree820ac2010-02-23 05:51:07 +00001924 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001925 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001926
Chris Lattner135091b2010-03-28 08:48:47 +00001927 // Check that the number of operands is sane. Negative operands -> varargs.
1928 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001929 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001930 TP.error(getOperator()->getName() + " node requires exactly " +
1931 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001932 return false;
1933 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001934
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001935 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001936 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1937 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001938 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001939 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001940 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001941
Chris Lattneree820ac2010-02-23 05:51:07 +00001942 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001943 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001944 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001945 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001946
Chris Lattnerd44966f2010-03-27 19:15:02 +00001947 bool MadeChange = false;
1948
1949 // Apply the result types to the node, these come from the things in the
1950 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001951 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1952 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001953 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1954 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001955
Chris Lattnerd44966f2010-03-27 19:15:02 +00001956 // If the instruction has implicit defs, we apply the first one as a result.
1957 // FIXME: This sucks, it should apply all implicit defs.
1958 if (!InstInfo.ImplicitDefs.empty()) {
1959 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001960
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001961 // FIXME: Generalize to multiple possible types and multiple possible
1962 // ImplicitDefs.
1963 MVT::SimpleValueType VT =
1964 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001965
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001966 if (VT != MVT::Other)
1967 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001968 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001969
Chris Lattnercabe0372010-03-15 06:00:16 +00001970 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1971 // be the same.
1972 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001973 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1974 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1975 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001976 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1977 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1978 // variadic.
1979
1980 unsigned NChild = getNumChildren();
1981 if (NChild < 3) {
1982 TP.error("REG_SEQUENCE requires at least 3 operands!");
1983 return false;
1984 }
1985
1986 if (NChild % 2 == 0) {
1987 TP.error("REG_SEQUENCE requires an odd number of operands!");
1988 return false;
1989 }
1990
1991 if (!isOperandClass(getChild(0), "RegisterClass")) {
1992 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1993 return false;
1994 }
1995
1996 for (unsigned I = 1; I < NChild; I += 2) {
1997 TreePatternNode *SubIdxChild = getChild(I + 1);
1998 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1999 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2000 itostr(I + 1) + "!");
2001 return false;
2002 }
2003 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002004 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002005
2006 unsigned ChildNo = 0;
2007 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2008 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002009
Chris Lattner8cab0212008-01-05 22:25:12 +00002010 // If the instruction expects a predicate or optional def operand, we
2011 // codegen this by setting the operand to it's default value if it has a
2012 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002013 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002014 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2015 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002016
Chris Lattner8cab0212008-01-05 22:25:12 +00002017 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002018 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002019 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002020 return false;
2021 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002022
Chris Lattner8cab0212008-01-05 22:25:12 +00002023 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002024 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002025
2026 // If the operand has sub-operands, they may be provided by distinct
2027 // child patterns, so attempt to match each sub-operand separately.
2028 if (OperandNode->isSubClassOf("Operand")) {
2029 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2030 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2031 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002032 // a single ComplexPattern-related Operand.
2033
2034 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002035 // Match first sub-operand against the child we already have.
2036 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2037 MadeChange |=
2038 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2039
2040 // And the remaining sub-operands against subsequent children.
2041 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2042 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002043 emitTooFewOperandsError(TP, getOperator()->getName(),
2044 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002045 return false;
2046 }
2047 Child = getChild(ChildNo++);
2048
2049 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2050 MadeChange |=
2051 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2052 }
2053 continue;
2054 }
2055 }
2056 }
2057
2058 // If we didn't match by pieces above, attempt to match the whole
2059 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002060 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002061 }
Christopher Lamba7312392008-03-11 09:33:47 +00002062
Matt Arsenaulteb492162014-11-02 23:46:51 +00002063 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002064 emitTooManyOperandsError(TP, getOperator()->getName(),
2065 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002066 return false;
2067 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002068
Ulrich Weigande618abd2013-03-19 19:51:09 +00002069 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2070 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002071 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002072 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002073
Tim Northoverc807a172014-05-20 11:52:46 +00002074 if (getOperator()->isSubClassOf("ComplexPattern")) {
2075 bool MadeChange = false;
2076
2077 for (unsigned i = 0; i < getNumChildren(); ++i)
2078 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2079
2080 return MadeChange;
2081 }
2082
Chris Lattneree820ac2010-02-23 05:51:07 +00002083 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002084
Chris Lattneree820ac2010-02-23 05:51:07 +00002085 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002086 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002087 TP.error("Node transform '" + getOperator()->getName() +
2088 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002089 return false;
2090 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002091
Chris Lattnercabe0372010-03-15 06:00:16 +00002092 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002093 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002094}
2095
2096/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2097/// RHS of a commutative operation, not the on LHS.
2098static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2099 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2100 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002101 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002102 return true;
2103 return false;
2104}
2105
2106
2107/// canPatternMatch - If it is impossible for this pattern to match on this
2108/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002109/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002110/// that can never possibly work), and to prevent the pattern permuter from
2111/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002112bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002113 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002114 if (isLeaf()) return true;
2115
2116 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2117 if (!getChild(i)->canPatternMatch(Reason, CDP))
2118 return false;
2119
2120 // If this is an intrinsic, handle cases that would make it not match. For
2121 // example, if an operand is required to be an immediate.
2122 if (getOperator()->isSubClassOf("Intrinsic")) {
2123 // TODO:
2124 return true;
2125 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002126
Tim Northoverc807a172014-05-20 11:52:46 +00002127 if (getOperator()->isSubClassOf("ComplexPattern"))
2128 return true;
2129
Chris Lattner8cab0212008-01-05 22:25:12 +00002130 // If this node is a commutative operator, check that the LHS isn't an
2131 // immediate.
2132 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002133 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2134 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002135 // Scan all of the operands of the node and make sure that only the last one
2136 // is a constant node, unless the RHS also is.
2137 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002138 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002139 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002140 if (OnlyOnRHSOfCommutative(getChild(i))) {
2141 Reason="Immediate value must be on the RHS of commutative operators!";
2142 return false;
2143 }
2144 }
2145 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002146
Chris Lattner8cab0212008-01-05 22:25:12 +00002147 return true;
2148}
2149
2150//===----------------------------------------------------------------------===//
2151// TreePattern implementation
2152//
2153
David Greeneaf8ee2c2011-07-29 22:43:06 +00002154TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002155 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002156 isInputPattern(isInput), HasError(false),
2157 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002158 for (Init *I : RawPat->getValues())
2159 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002160}
2161
David Greeneaf8ee2c2011-07-29 22:43:06 +00002162TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002163 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002164 isInputPattern(isInput), HasError(false),
2165 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002166 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002167}
2168
David Blaikiecf195302014-11-17 22:55:41 +00002169TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002170 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002171 isInputPattern(isInput), HasError(false),
2172 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002173 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002174}
2175
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002176void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002177 if (HasError)
2178 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002179 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002180 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2181 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002182}
2183
Chris Lattnercabe0372010-03-15 06:00:16 +00002184void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002185 for (TreePatternNode *Tree : Trees)
2186 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002187}
2188
2189void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2190 if (!N->getName().empty())
2191 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002192
Chris Lattnercabe0372010-03-15 06:00:16 +00002193 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2194 ComputeNamedNodes(N->getChild(i));
2195}
2196
David Blaikiecf195302014-11-17 22:55:41 +00002197
2198TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002199 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002200 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002201
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002202 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002203 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002204 /// (foo GPR, imm) -> (foo GPR, (imm))
2205 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002206 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002207 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002208 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002209 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002210
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002211 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002212 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002213 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002214 if (OpName.empty())
2215 error("'node' argument requires a name to match with operand list");
2216 Args.push_back(OpName);
2217 }
2218
2219 Res->setName(OpName);
2220 return Res;
2221 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002222
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002223 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002224 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002225 if (OpName.empty())
2226 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002227 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002228 Args.push_back(OpName);
2229 Res->setName(OpName);
2230 return Res;
2231 }
2232
Sean Silvafb509ed2012-10-10 20:24:43 +00002233 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002234 if (!OpName.empty())
2235 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002236 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002237 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002238
Sean Silvafb509ed2012-10-10 20:24:43 +00002239 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002240 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002241 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002242 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002243 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002244 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002245 }
2246
Sean Silvafb509ed2012-10-10 20:24:43 +00002247 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002248 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002249 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002250 error("Pattern has unexpected init kind!");
2251 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002252 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002253 if (!OpDef) error("Pattern has unexpected operator type!");
2254 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002255
Chris Lattner8cab0212008-01-05 22:25:12 +00002256 if (Operator->isSubClassOf("ValueType")) {
2257 // If the operator is a ValueType, then this must be "type cast" of a leaf
2258 // node.
2259 if (Dag->getNumArgs() != 1)
2260 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002261
Matthias Braunbb053162016-12-05 06:00:46 +00002262 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2263 Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002264
Chris Lattner8cab0212008-01-05 22:25:12 +00002265 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002266 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002267 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2268 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002269
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002270 if (!OpName.empty())
2271 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002272 return New;
2273 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002274
Chris Lattner8cab0212008-01-05 22:25:12 +00002275 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002276 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002277 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002278 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002279 !Operator->isSubClassOf("SDNodeXForm") &&
2280 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002281 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002282 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002283 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002284 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002285
Chris Lattner8cab0212008-01-05 22:25:12 +00002286 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002287 if (isInputPattern) {
2288 if (Operator->isSubClassOf("Instruction") ||
2289 Operator->isSubClassOf("SDNodeXForm"))
2290 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2291 } else {
2292 if (Operator->isSubClassOf("Intrinsic"))
2293 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002294
Chris Lattner2e9eae12010-03-28 06:57:56 +00002295 if (Operator->isSubClassOf("SDNode") &&
2296 Operator->getName() != "imm" &&
2297 Operator->getName() != "fpimm" &&
2298 Operator->getName() != "tglobaltlsaddr" &&
2299 Operator->getName() != "tconstpool" &&
2300 Operator->getName() != "tjumptable" &&
2301 Operator->getName() != "tframeindex" &&
2302 Operator->getName() != "texternalsym" &&
2303 Operator->getName() != "tblockaddress" &&
2304 Operator->getName() != "tglobaladdr" &&
2305 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002306 Operator->getName() != "vt" &&
2307 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002308 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2309 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002310
Chris Lattner8cab0212008-01-05 22:25:12 +00002311 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002312
2313 // Parse all the operands.
2314 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002315 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002316
Chris Lattner8cab0212008-01-05 22:25:12 +00002317 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002318 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002319 // convert the intrinsic name to a number.
2320 if (Operator->isSubClassOf("Intrinsic")) {
2321 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2322 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2323
2324 // If this intrinsic returns void, it must have side-effects and thus a
2325 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002326 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002327 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002328 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002329 // Has side-effects, requires chain.
2330 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002331 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002332 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002333
David Greenee32ebf22011-07-29 19:07:07 +00002334 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002335 Children.insert(Children.begin(), IIDNode);
2336 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002337
Tim Northoverc807a172014-05-20 11:52:46 +00002338 if (Operator->isSubClassOf("ComplexPattern")) {
2339 for (unsigned i = 0; i < Children.size(); ++i) {
2340 TreePatternNode *Child = Children[i];
2341
2342 if (Child->getName().empty())
2343 error("All arguments to a ComplexPattern must be named");
2344
2345 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2346 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2347 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2348 auto OperandId = std::make_pair(Operator, i);
2349 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2350 if (PrevOp != ComplexPatternOperands.end()) {
2351 if (PrevOp->getValue() != OperandId)
2352 error("All ComplexPattern operands must appear consistently: "
2353 "in the same order in just one ComplexPattern instance.");
2354 } else
2355 ComplexPatternOperands[Child->getName()] = OperandId;
2356 }
2357 }
2358
Chris Lattnerf1447252010-03-19 21:37:09 +00002359 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002360 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002361 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002362
Matthias Braun7cf3b112016-12-05 06:00:41 +00002363 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002364 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002365 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002366 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002367 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002368}
2369
Chris Lattnera787c9e2010-03-28 08:38:32 +00002370/// SimplifyTree - See if we can simplify this tree to eliminate something that
2371/// will never match in favor of something obvious that will. This is here
2372/// strictly as a convenience to target authors because it allows them to write
2373/// more type generic things and have useless type casts fold away.
2374///
2375/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002376static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002377 if (N->isLeaf())
2378 return false;
2379
2380 // If we have a bitconvert with a resolved type and if the source and
2381 // destination types are the same, then the bitconvert is useless, remove it.
2382 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002383 N->getExtType(0).isValueTypeByHwMode(false) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002384 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2385 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002386 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002387 SimplifyTree(N);
2388 return true;
2389 }
2390
2391 // Walk all children.
2392 bool MadeChange = false;
2393 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002394 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002395 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002396 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002397 }
2398 return MadeChange;
2399}
2400
2401
2402
Chris Lattner8cab0212008-01-05 22:25:12 +00002403/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002404/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002405/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002406bool TreePattern::
2407InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2408 if (NamedNodes.empty())
2409 ComputeNamedNodes();
2410
Chris Lattner8cab0212008-01-05 22:25:12 +00002411 bool MadeChange = true;
2412 while (MadeChange) {
2413 MadeChange = false;
Craig Topper3f7864e2017-08-30 02:05:03 +00002414 for (TreePatternNode *&Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002415 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2416 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002417 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002418
2419 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002420 for (auto &Entry : NamedNodes) {
2421 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002422
Chris Lattnercabe0372010-03-15 06:00:16 +00002423 // If we have input named node types, propagate their types to the named
2424 // values here.
2425 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002426 if (!InNamedTypes->count(Entry.getKey())) {
2427 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002428 "' in output pattern but not input pattern");
2429 return true;
2430 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002431
2432 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002433 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002434
2435 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002436 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002437 // If this node is a register class, and it is the root of the pattern
2438 // then we're mapping something onto an input register. We allow
2439 // changing the type of the input register in this case. This allows
2440 // us to match things like:
2441 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002442 if (Node == Trees[0] && Node->isLeaf()) {
2443 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002444 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2445 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002446 continue;
2447 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002448
Craig Topper306cb122015-11-22 20:46:24 +00002449 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002450 InNodes[0]->getNumTypes() == 1 &&
2451 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002452 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2453 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002454 }
2455 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002456
Chris Lattnercabe0372010-03-15 06:00:16 +00002457 // If there are multiple nodes with the same name, they must all have the
2458 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002459 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002460 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002461 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002462 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002463 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002464
Chris Lattnerf1447252010-03-19 21:37:09 +00002465 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2466 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002467 }
2468 }
2469 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002470 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002471
Chris Lattner8cab0212008-01-05 22:25:12 +00002472 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002473 for (const TreePatternNode *Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002474 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002475 return !HasUnresolvedTypes;
2476}
2477
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002478void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002479 OS << getRecord()->getName();
2480 if (!Args.empty()) {
2481 OS << "(" << Args[0];
2482 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2483 OS << ", " << Args[i];
2484 OS << ")";
2485 }
2486 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002487
Chris Lattner8cab0212008-01-05 22:25:12 +00002488 if (Trees.size() > 1)
2489 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002490 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002491 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002492 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002493 OS << "\n";
2494 }
2495
2496 if (Trees.size() > 1)
2497 OS << "]\n";
2498}
2499
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002500void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002501
2502//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002503// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002504//
2505
Jim Grosbach65586fe2010-12-21 16:16:00 +00002506CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002507 Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002508
Justin Bogner92a8c612016-07-15 16:31:37 +00002509 Intrinsics = CodeGenIntrinsicTable(Records, false);
2510 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002511 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002512 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002513 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002514 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002515 ParseDefaultOperands();
2516 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002517 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002518 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002519
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002520 // Break patterns with parameterized types into a series of patterns,
2521 // where each one has a fixed type and is predicated on the conditions
2522 // of the associated HW mode.
2523 ExpandHwModeBasedTypes();
2524
Chris Lattner8cab0212008-01-05 22:25:12 +00002525 // Generate variants. For example, commutative patterns can match
2526 // multiple ways. Add them to PatternsToMatch as well.
2527 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002528
2529 // Infer instruction flags. For example, we can detect loads,
2530 // stores, and side effects in many cases by examining an
2531 // instruction's pattern.
2532 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002533
2534 // Verify that instruction flags match the patterns.
2535 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002536}
2537
Chris Lattnerab3242f2008-01-06 01:10:31 +00002538Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002539 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002540 if (!N || !N->isSubClassOf("SDNode"))
2541 PrintFatalError("Error getting SDNode '" + Name + "'!");
2542
Chris Lattner8cab0212008-01-05 22:25:12 +00002543 return N;
2544}
2545
2546// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002547void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002548 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002549 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2550
Chris Lattner8cab0212008-01-05 22:25:12 +00002551 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002552 Record *R = Nodes.back();
2553 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002554 Nodes.pop_back();
2555 }
2556
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002557 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002558 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2559 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2560 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2561}
2562
2563/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2564/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002565void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002566 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2567 while (!Xforms.empty()) {
2568 Record *XFormNode = Xforms.back();
2569 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002570 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002571 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002572
2573 Xforms.pop_back();
2574 }
2575}
2576
Chris Lattnerab3242f2008-01-06 01:10:31 +00002577void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002578 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2579 while (!AMs.empty()) {
2580 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2581 AMs.pop_back();
2582 }
2583}
2584
2585
2586/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2587/// file, building up the PatternFragments map. After we've collected them all,
2588/// inline fragments together as necessary, so that there are no references left
2589/// inside a pattern fragment to a pattern fragment.
2590///
Hal Finkel2756dc12014-02-28 00:26:56 +00002591void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002592 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002593
Chris Lattnere7170df2008-01-05 22:43:57 +00002594 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002595 for (Record *Frag : Fragments) {
2596 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002597 continue;
2598
Craig Topper306cb122015-11-22 20:46:24 +00002599 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002600 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002601 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2602 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002603 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002604
Chris Lattnere7170df2008-01-05 22:43:57 +00002605 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002606 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002607 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002608
Chris Lattnere7170df2008-01-05 22:43:57 +00002609 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002610 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002611
Chris Lattner8cab0212008-01-05 22:25:12 +00002612 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002613 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002614 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002615 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002616 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002617 if (!OpsOp ||
2618 (OpsOp->getDef()->getName() != "ops" &&
2619 OpsOp->getDef()->getName() != "outs" &&
2620 OpsOp->getDef()->getName() != "ins"))
2621 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002622
2623 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002624 Args.clear();
2625 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002626 if (!isa<DefInit>(OpsList->getArg(j)) ||
2627 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002628 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00002629 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00002630 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00002631 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2632 if (!OperandsSet.count(ArgNameStr))
2633 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00002634 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00002635 OperandsSet.erase(ArgNameStr);
2636 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00002637 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002638
Chris Lattnere7170df2008-01-05 22:43:57 +00002639 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002640 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002641 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002642
Chris Lattnere7170df2008-01-05 22:43:57 +00002643 // If there is a code init for this fragment, keep track of the fact that
2644 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002645 TreePredicateFn PredFn(P);
2646 if (!PredFn.isAlwaysTrue())
2647 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002648
Chris Lattner8cab0212008-01-05 22:25:12 +00002649 // If there is a node transformation corresponding to this, keep track of
2650 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002651 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002652 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2653 P->getOnlyTree()->setTransformFn(Transform);
2654 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002655
Chris Lattner8cab0212008-01-05 22:25:12 +00002656 // Now that we've parsed all of the tree fragments, do a closure on them so
2657 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002658 for (Record *Frag : Fragments) {
2659 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002660 continue;
2661
Craig Topper306cb122015-11-22 20:46:24 +00002662 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002663 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002664
Chris Lattner8cab0212008-01-05 22:25:12 +00002665 // Infer as many types as possible. Don't worry about it if we don't infer
2666 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002667 ThePat.InferAllTypes();
2668 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002669
Chris Lattner8cab0212008-01-05 22:25:12 +00002670 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002671 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002672 }
2673}
2674
Chris Lattnerab3242f2008-01-06 01:10:31 +00002675void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002676 std::vector<Record*> DefaultOps;
2677 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002678
2679 // Find some SDNode.
2680 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002681 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002682
Tom Stellardb7246a72012-09-06 14:15:52 +00002683 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2684 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002685
Tom Stellardb7246a72012-09-06 14:15:52 +00002686 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2687 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00002688 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00002689 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2690 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2691 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00002692 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002693
Tom Stellardb7246a72012-09-06 14:15:52 +00002694 // Create a TreePattern to parse this.
2695 TreePattern P(DefaultOps[i], DI, false, *this);
2696 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002697
Tom Stellardb7246a72012-09-06 14:15:52 +00002698 // Copy the operands over into a DAGDefaultOperand.
2699 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002700
Tom Stellardb7246a72012-09-06 14:15:52 +00002701 TreePatternNode *T = P.getTree(0);
2702 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2703 TreePatternNode *TPN = T->getChild(op);
2704 while (TPN->ApplyTypeConstraints(P, false))
2705 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002706
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002707 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002708 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2709 DefaultOps[i]->getName() +
2710 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002711 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002712 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002713 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002714
2715 // Insert it into the DefaultOperands map so we can find it later.
2716 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002717 }
2718}
2719
2720/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2721/// instruction input. Return true if this is a real use.
2722static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002723 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002724 // No name -> not interesting.
2725 if (Pat->getName().empty()) {
2726 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002727 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002728 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2729 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002730 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002731 }
2732 return false;
2733 }
2734
2735 Record *Rec;
2736 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002737 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002738 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2739 Rec = DI->getDef();
2740 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002741 Rec = Pat->getOperator();
2742 }
2743
2744 // SRCVALUE nodes are ignored.
2745 if (Rec->getName() == "srcvalue")
2746 return false;
2747
2748 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2749 if (!Slot) {
2750 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002751 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002752 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002753 Record *SlotRec;
2754 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002755 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002756 } else {
2757 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2758 SlotRec = Slot->getOperator();
2759 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002760
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002761 // Ensure that the inputs agree if we've already seen this input.
2762 if (Rec != SlotRec)
2763 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002764 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002765 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002766 return true;
2767}
2768
2769/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2770/// part of "I", the instruction), computing the set of inputs and outputs of
2771/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002772void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002773FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2774 std::map<std::string, TreePatternNode*> &InstInputs,
2775 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002776 std::vector<Record*> &InstImpResults) {
2777 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002778 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002779 if (!isUse && Pat->getTransformFn())
2780 I->error("Cannot specify a transform function for a non-input value!");
2781 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002782 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002783
Chris Lattnerf2d70992010-02-17 06:53:36 +00002784 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002785 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2786 TreePatternNode *Dest = Pat->getChild(i);
2787 if (!Dest->isLeaf())
2788 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002789
Sean Silvafb509ed2012-10-10 20:24:43 +00002790 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002791 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2792 I->error("implicitly defined value should be a register!");
2793 InstImpResults.push_back(Val->getDef());
2794 }
2795 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002796 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002797
Chris Lattnerf2d70992010-02-17 06:53:36 +00002798 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002799 // If this is not a set, verify that the children nodes are not void typed,
2800 // and recurse.
2801 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002802 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002803 I->error("Cannot have void nodes inside of patterns!");
2804 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002805 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002806 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002807
Chris Lattner8cab0212008-01-05 22:25:12 +00002808 // If this is a non-leaf node with no children, treat it basically as if
2809 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002810 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002811
Chris Lattner8cab0212008-01-05 22:25:12 +00002812 if (!isUse && Pat->getTransformFn())
2813 I->error("Cannot specify a transform function for a non-input value!");
2814 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002815 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002816
Chris Lattner8cab0212008-01-05 22:25:12 +00002817 // Otherwise, this is a set, validate and collect instruction results.
2818 if (Pat->getNumChildren() == 0)
2819 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002820
Chris Lattner8cab0212008-01-05 22:25:12 +00002821 if (Pat->getTransformFn())
2822 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002823
Chris Lattner8cab0212008-01-05 22:25:12 +00002824 // Check the set destinations.
2825 unsigned NumDests = Pat->getNumChildren()-1;
2826 for (unsigned i = 0; i != NumDests; ++i) {
2827 TreePatternNode *Dest = Pat->getChild(i);
2828 if (!Dest->isLeaf())
2829 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002830
Sean Silvafb509ed2012-10-10 20:24:43 +00002831 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002832 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002833 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002834 continue;
2835 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002836
2837 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002838 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002839 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002840 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002841 if (Dest->getName().empty())
2842 I->error("set destination must have a name!");
2843 if (InstResults.count(Dest->getName()))
2844 I->error("cannot set '" + Dest->getName() +"' multiple times");
2845 InstResults[Dest->getName()] = Dest;
2846 } else if (Val->getDef()->isSubClassOf("Register")) {
2847 InstImpResults.push_back(Val->getDef());
2848 } else {
2849 I->error("set destination should be a register!");
2850 }
2851 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002852
Chris Lattner8cab0212008-01-05 22:25:12 +00002853 // Verify and collect info from the computation.
2854 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002855 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002856}
2857
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002858//===----------------------------------------------------------------------===//
2859// Instruction Analysis
2860//===----------------------------------------------------------------------===//
2861
2862class InstAnalyzer {
2863 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002864public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002865 bool hasSideEffects;
2866 bool mayStore;
2867 bool mayLoad;
2868 bool isBitcast;
2869 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002870
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002871 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2872 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2873 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002874
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002875 void Analyze(const TreePattern *Pat) {
2876 // Assume only the first tree is the pattern. The others are clobber nodes.
2877 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002878 }
2879
Craig Topper2a053a92017-06-20 16:34:37 +00002880 void Analyze(const PatternToMatch &Pat) {
2881 AnalyzeNode(Pat.getSrcPattern());
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002882 }
2883
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002884private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002885 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002886 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002887 return false;
2888
2889 if (N->getNumChildren() != 2)
2890 return false;
2891
2892 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002893 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002894 return false;
2895
2896 const TreePatternNode *N1 = N->getChild(1);
2897 if (N1->isLeaf())
2898 return false;
2899 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2900 return false;
2901
2902 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2903 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2904 return false;
2905 return OpInfo.getEnumName() == "ISD::BITCAST";
2906 }
2907
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002908public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002909 void AnalyzeNode(const TreePatternNode *N) {
2910 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002911 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002912 Record *LeafRec = DI->getDef();
2913 // Handle ComplexPattern leaves.
2914 if (LeafRec->isSubClassOf("ComplexPattern")) {
2915 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2916 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2917 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002918 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002919 }
2920 }
2921 return;
2922 }
2923
2924 // Analyze children.
2925 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2926 AnalyzeNode(N->getChild(i));
2927
2928 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002929 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002930 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002931 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002932 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002933
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002934 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002935 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2936 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2937 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2938 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002939
2940 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2941 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002942 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002943 mayLoad = true;// These may load memory.
2944
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002945 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002946 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2947
Matt Arsenault868af922017-04-28 21:01:46 +00002948 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
2949 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002950 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002951 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002952 }
2953 }
2954
2955};
2956
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002957static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002958 const InstAnalyzer &PatInfo,
2959 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002960 bool Error = false;
2961
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002962 // Remember where InstInfo got its flags.
2963 if (InstInfo.hasUndefFlags())
2964 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002965
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002966 // Check explicitly set flags for consistency.
2967 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2968 !InstInfo.hasSideEffects_Unset) {
2969 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2970 // the pattern has no side effects. That could be useful for div/rem
2971 // instructions that may trap.
2972 if (!InstInfo.hasSideEffects) {
2973 Error = true;
2974 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2975 Twine(InstInfo.hasSideEffects));
2976 }
2977 }
2978
2979 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2980 Error = true;
2981 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2982 Twine(InstInfo.mayStore));
2983 }
2984
2985 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2986 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00002987 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002988 if (!InstInfo.mayLoad) {
2989 Error = true;
2990 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2991 Twine(InstInfo.mayLoad));
2992 }
2993 }
2994
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002995 // Transfer inferred flags.
2996 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2997 InstInfo.mayStore |= PatInfo.mayStore;
2998 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002999
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003000 // These flags are silently added without any verification.
3001 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003002
3003 // Don't infer isVariadic. This flag means something different on SDNodes and
3004 // instructions. For example, a CALL SDNode is variadic because it has the
3005 // call arguments as operands, but a CALL instruction is not variadic - it
3006 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003007
3008 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003009}
3010
Jim Grosbach514410b2012-07-17 00:47:06 +00003011/// hasNullFragReference - Return true if the DAG has any reference to the
3012/// null_frag operator.
3013static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003014 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003015 if (!OpDef) return false;
3016 Record *Operator = OpDef->getDef();
3017
3018 // If this is the null fragment, return true.
3019 if (Operator->getName() == "null_frag") return true;
3020 // If any of the arguments reference the null fragment, return true.
3021 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003022 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003023 if (Arg && hasNullFragReference(Arg))
3024 return true;
3025 }
3026
3027 return false;
3028}
3029
3030/// hasNullFragReference - Return true if any DAG in the list references
3031/// the null_frag operator.
3032static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003033 for (Init *I : LI->getValues()) {
3034 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003035 assert(DI && "non-dag in an instruction Pattern list?!");
3036 if (hasNullFragReference(DI))
3037 return true;
3038 }
3039 return false;
3040}
3041
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003042/// Get all the instructions in a tree.
3043static void
3044getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3045 if (Tree->isLeaf())
3046 return;
3047 if (Tree->getOperator()->isSubClassOf("Instruction"))
3048 Instrs.push_back(Tree->getOperator());
3049 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3050 getInstructionsInTree(Tree->getChild(i), Instrs);
3051}
3052
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003053/// Check the class of a pattern leaf node against the instruction operand it
3054/// represents.
3055static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3056 Record *Leaf) {
3057 if (OI.Rec == Leaf)
3058 return true;
3059
3060 // Allow direct value types to be used in instruction set patterns.
3061 // The type will be checked later.
3062 if (Leaf->isSubClassOf("ValueType"))
3063 return true;
3064
3065 // Patterns can also be ComplexPattern instances.
3066 if (Leaf->isSubClassOf("ComplexPattern"))
3067 return true;
3068
3069 return false;
3070}
3071
Ahmed Bougacha14107512013-10-28 18:07:21 +00003072const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
3073 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003074
Craig Topper0d1fb902015-03-10 03:25:04 +00003075 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003076
Craig Topper0d1fb902015-03-10 03:25:04 +00003077 // Parse the instruction.
3078 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
3079 // Inline pattern fragments into it.
3080 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003081
Craig Topper0d1fb902015-03-10 03:25:04 +00003082 // Infer as many types as possible. If we cannot infer all of them, we can
3083 // never do anything with this instruction pattern: report it to the user.
3084 if (!I->InferAllTypes())
3085 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003086
Craig Topper0d1fb902015-03-10 03:25:04 +00003087 // InstInputs - Keep track of all of the inputs of the instruction, along
3088 // with the record they are declared as.
3089 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003090
Craig Topper0d1fb902015-03-10 03:25:04 +00003091 // InstResults - Keep track of all the virtual registers that are 'set'
3092 // in the instruction, including what reg class they are.
3093 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003094
Craig Topper0d1fb902015-03-10 03:25:04 +00003095 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003096
Craig Topper0d1fb902015-03-10 03:25:04 +00003097 // Verify that the top-level forms in the instruction are of void type, and
3098 // fill in the InstResults map.
3099 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
3100 TreePatternNode *Pat = I->getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003101 if (Pat->getNumTypes() != 0) {
3102 std::string Types;
3103 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3104 if (k > 0)
3105 Types += ", ";
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003106 Types += Pat->getExtType(k).getAsString();
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003107 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003108 I->error("Top-level forms in instruction pattern should have"
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003109 " void types, has types " + Types);
3110 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003111
Craig Topper0d1fb902015-03-10 03:25:04 +00003112 // Find inputs and outputs, and verify the structure of the uses/defs.
3113 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3114 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003115 }
3116
Craig Topper0d1fb902015-03-10 03:25:04 +00003117 // Now that we have inputs and outputs of the pattern, inspect the operands
3118 // list for the instruction. This determines the order that operands are
3119 // added to the machine instruction the node corresponds to.
3120 unsigned NumResults = InstResults.size();
3121
3122 // Parse the operands list from the (ops) list, validating it.
3123 assert(I->getArgList().empty() && "Args list should still be empty here!");
3124
3125 // Check that all of the results occur first in the list.
3126 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00003127 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003128 for (unsigned i = 0; i != NumResults; ++i) {
3129 if (i == CGI.Operands.size())
3130 I->error("'" + InstResults.begin()->first +
3131 "' set but does not appear in operand list!");
3132 const std::string &OpName = CGI.Operands[i].Name;
3133
3134 // Check that it exists in InstResults.
3135 TreePatternNode *RNode = InstResults[OpName];
3136 if (!RNode)
3137 I->error("Operand $" + OpName + " does not exist in operand list!");
3138
Craig Topper3a8eb892015-03-20 05:09:06 +00003139 ResNodes.push_back(RNode);
3140
Craig Topper0d1fb902015-03-10 03:25:04 +00003141 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3142 if (!R)
3143 I->error("Operand $" + OpName + " should be a set destination: all "
3144 "outputs must occur before inputs in operand list!");
3145
3146 if (!checkOperandClass(CGI.Operands[i], R))
3147 I->error("Operand $" + OpName + " class mismatch!");
3148
3149 // Remember the return type.
3150 Results.push_back(CGI.Operands[i].Rec);
3151
3152 // Okay, this one checks out.
3153 InstResults.erase(OpName);
3154 }
3155
3156 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3157 // the copy while we're checking the inputs.
3158 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3159
3160 std::vector<TreePatternNode*> ResultNodeOperands;
3161 std::vector<Record*> Operands;
3162 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3163 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3164 const std::string &OpName = Op.Name;
3165 if (OpName.empty())
3166 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3167
3168 if (!InstInputsCheck.count(OpName)) {
3169 // If this is an operand with a DefaultOps set filled in, we can ignore
3170 // this. When we codegen it, we will do so as always executed.
3171 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3172 // Does it have a non-empty DefaultOps field? If so, ignore this
3173 // operand.
3174 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3175 continue;
3176 }
3177 I->error("Operand $" + OpName +
3178 " does not appear in the instruction pattern");
3179 }
3180 TreePatternNode *InVal = InstInputsCheck[OpName];
3181 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3182
3183 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3184 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3185 if (!checkOperandClass(Op, InRec))
3186 I->error("Operand $" + OpName + "'s register class disagrees"
3187 " between the operand and pattern");
3188 }
3189 Operands.push_back(Op.Rec);
3190
3191 // Construct the result for the dest-pattern operand list.
3192 TreePatternNode *OpNode = InVal->clone();
3193
3194 // No predicate is useful on the result.
3195 OpNode->clearPredicateFns();
3196
3197 // Promote the xform function to be an explicit node if set.
3198 if (Record *Xform = OpNode->getTransformFn()) {
3199 OpNode->setTransformFn(nullptr);
3200 std::vector<TreePatternNode*> Children;
3201 Children.push_back(OpNode);
3202 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3203 }
3204
3205 ResultNodeOperands.push_back(OpNode);
3206 }
3207
3208 if (!InstInputsCheck.empty())
3209 I->error("Input operand $" + InstInputsCheck.begin()->first +
3210 " occurs in pattern but not in operands list!");
3211
3212 TreePatternNode *ResultPattern =
3213 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3214 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003215 // Copy fully inferred output node types to instruction result pattern.
3216 for (unsigned i = 0; i != NumResults; ++i) {
3217 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3218 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3219 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003220
3221 // Create and insert the instruction.
3222 // FIXME: InstImpResults should not be part of DAGInstruction.
3223 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3224 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3225
3226 // Use a temporary tree pattern to infer all types and make sure that the
3227 // constructed result is correct. This depends on the instruction already
3228 // being inserted into the DAGInsts map.
3229 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3230 Temp.InferAllTypes(&I->getNamedNodesMap());
3231
3232 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3233 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3234
3235 return TheInsertedInst;
3236}
3237
Ahmed Bougacha14107512013-10-28 18:07:21 +00003238/// ParseInstructions - Parse all of the instructions, inlining and resolving
3239/// any fragments involved. This populates the Instructions list with fully
3240/// resolved instructions.
3241void CodeGenDAGPatterns::ParseInstructions() {
3242 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3243
Craig Topper306cb122015-11-22 20:46:24 +00003244 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003245 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003246
Craig Topper306cb122015-11-22 20:46:24 +00003247 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3248 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003249
3250 // If there is no pattern, only collect minimal information about the
3251 // instruction for its operand list. We have to assume that there is one
3252 // result, as we have no detailed info. A pattern which references the
3253 // null_frag operator is as-if no pattern were specified. Normally this
3254 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3255 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003256 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003257 std::vector<Record*> Results;
3258 std::vector<Record*> Operands;
3259
Craig Topper306cb122015-11-22 20:46:24 +00003260 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003261
3262 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003263 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3264 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003265
Craig Topper3a8eb892015-03-20 05:09:06 +00003266 // The rest are inputs.
3267 for (unsigned j = InstInfo.Operands.NumDefs,
3268 e = InstInfo.Operands.size(); j < e; ++j)
3269 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003270 }
3271
3272 // Create and insert the instruction.
3273 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003274 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003275 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003276 continue; // no pattern.
3277 }
3278
Craig Topper306cb122015-11-22 20:46:24 +00003279 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003280 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3281
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003282 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003283 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003284 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003285
Chris Lattner8cab0212008-01-05 22:25:12 +00003286 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003287 for (auto &Entry : Instructions) {
3288 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003289 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003290 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003291
3292 // FIXME: Assume only the first tree is the pattern. The others are clobber
3293 // nodes.
3294 TreePatternNode *Pattern = I->getTree(0);
3295 TreePatternNode *SrcPattern;
3296 if (Pattern->getOperator()->getName() == "set") {
3297 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3298 } else{
3299 // Not a set (store or something?)
3300 SrcPattern = Pattern;
3301 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003302
Craig Topper306cb122015-11-22 20:46:24 +00003303 Record *Instr = Entry.first;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003304 ListInit *Preds = Instr->getValueAsListInit("Predicates");
3305 int Complexity = Instr->getValueAsInt("AddedComplexity");
3306 AddPatternToMatch(
3307 I,
3308 PatternToMatch(Instr, makePredList(Preds), SrcPattern,
3309 TheInst.getResultPattern(), TheInst.getImpResults(),
3310 Complexity, Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003311 }
3312}
3313
Chris Lattnera7722b62010-02-23 06:55:24 +00003314
3315typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3316
Jim Grosbach65586fe2010-12-21 16:16:00 +00003317static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003318 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003319 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003320 if (!P->getName().empty()) {
3321 NameRecord &Rec = Names[P->getName()];
3322 // If this is the first instance of the name, remember the node.
3323 if (Rec.second++ == 0)
3324 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003325 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003326 PatternTop->error("repetition of value: $" + P->getName() +
3327 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003328 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003329
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003330 if (!P->isLeaf()) {
3331 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003332 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003333 }
3334}
3335
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003336std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3337 std::vector<Predicate> Preds;
3338 for (Init *I : L->getValues()) {
3339 if (DefInit *Pred = dyn_cast<DefInit>(I))
3340 Preds.push_back(Pred->getDef());
3341 else
3342 llvm_unreachable("Non-def on the list");
3343 }
3344
3345 // Sort so that different orders get canonicalized to the same string.
3346 std::sort(Preds.begin(), Preds.end());
3347 return Preds;
3348}
3349
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003350void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003351 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003352 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003353 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003354 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3355 PrintWarning(Pattern->getRecord()->getLoc(),
3356 Twine("Pattern can never match: ") + Reason);
3357 return;
3358 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003359
Chris Lattner1e634e32010-03-01 22:29:19 +00003360 // If the source pattern's root is a complex pattern, that complex pattern
3361 // must specify the nodes it can potentially match.
3362 if (const ComplexPattern *CP =
3363 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3364 if (CP->getRootNodes().empty())
3365 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3366 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003367
3368
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003369 // Find all of the named values in the input and output, ensure they have the
3370 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003371 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003372 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3373 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003374
3375 // Scan all of the named values in the destination pattern, rejecting them if
3376 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003377 for (const auto &Entry : DstNames) {
3378 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003379 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003380 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003381 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003382
Chris Lattnera7722b62010-02-23 06:55:24 +00003383 // Scan all of the named values in the source pattern, rejecting them if the
3384 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003385 for (const auto &Entry : SrcNames)
3386 if (DstNames[Entry.first].first == nullptr &&
3387 SrcNames[Entry.first].second == 1)
3388 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003389
Craig Topper18e6b572017-06-25 17:33:49 +00003390 PatternsToMatch.push_back(std::move(PTM));
Chris Lattner0c0baa92010-02-23 06:16:51 +00003391}
3392
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003393void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003394 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003395 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003396
3397 // First try to infer flags from the primary instruction pattern, if any.
3398 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003399 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003400 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3401 CodeGenInstruction &InstInfo =
3402 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003403
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003404 // Get the primary instruction pattern.
3405 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3406 if (!Pattern) {
3407 if (InstInfo.hasUndefFlags())
3408 Revisit.push_back(&InstInfo);
3409 continue;
3410 }
3411 InstAnalyzer PatInfo(*this);
3412 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003413 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003414 }
3415
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003416 // Second, look for single-instruction patterns defined outside the
3417 // instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003418 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003419 // We can only infer from single-instruction patterns, otherwise we won't
3420 // know which instruction should get the flags.
3421 SmallVector<Record*, 8> PatInstrs;
3422 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3423 if (PatInstrs.size() != 1)
3424 continue;
3425
3426 // Get the single instruction.
3427 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3428
3429 // Only infer properties from the first pattern. We'll verify the others.
3430 if (InstInfo.InferredFrom)
3431 continue;
3432
3433 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003434 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003435 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3436 }
3437
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003438 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003439 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003440
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003441 // Revisit instructions with undefined flags and no pattern.
3442 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003443 for (CodeGenInstruction *InstInfo : Revisit) {
3444 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003445 continue;
3446 // The mayLoad and mayStore flags default to false.
3447 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003448 if (InstInfo->hasSideEffects_Unset)
3449 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003450 }
3451 return;
3452 }
3453
3454 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003455 for (CodeGenInstruction *InstInfo : Revisit) {
3456 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003457 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003458 if (InstInfo->hasSideEffects_Unset)
3459 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003460 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003461 if (InstInfo->mayStore_Unset)
3462 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003463 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003464 if (InstInfo->mayLoad_Unset)
3465 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003466 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003467 }
3468}
3469
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003470
3471/// Verify instruction flags against pattern node properties.
3472void CodeGenDAGPatterns::VerifyInstructionFlags() {
3473 unsigned Errors = 0;
3474 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3475 const PatternToMatch &PTM = *I;
3476 SmallVector<Record*, 8> Instrs;
3477 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3478 if (Instrs.empty())
3479 continue;
3480
3481 // Count the number of instructions with each flag set.
3482 unsigned NumSideEffects = 0;
3483 unsigned NumStores = 0;
3484 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003485 for (const Record *Instr : Instrs) {
3486 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003487 NumSideEffects += InstInfo.hasSideEffects;
3488 NumStores += InstInfo.mayStore;
3489 NumLoads += InstInfo.mayLoad;
3490 }
3491
3492 // Analyze the source pattern.
3493 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003494 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003495
3496 // Collect error messages.
3497 SmallVector<std::string, 4> Msgs;
3498
3499 // Check for missing flags in the output.
3500 // Permit extra flags for now at least.
3501 if (PatInfo.hasSideEffects && !NumSideEffects)
3502 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3503
3504 // Don't verify store flags on instructions with side effects. At least for
3505 // intrinsics, side effects implies mayStore.
3506 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3507 Msgs.push_back("pattern may store, but mayStore isn't set");
3508
3509 // Similarly, mayStore implies mayLoad on intrinsics.
3510 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3511 Msgs.push_back("pattern may load, but mayLoad isn't set");
3512
3513 // Print error messages.
3514 if (Msgs.empty())
3515 continue;
3516 ++Errors;
3517
Craig Topper306cb122015-11-22 20:46:24 +00003518 for (const std::string &Msg : Msgs)
3519 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003520 (Instrs.size() == 1 ?
3521 "instruction" : "output instructions"));
3522 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003523 for (const Record *Instr : Instrs) {
3524 if (Instr != PTM.getSrcRecord())
3525 PrintError(Instr->getLoc(), "defined here");
3526 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003527 if (InstInfo.InferredFrom &&
3528 InstInfo.InferredFrom != InstInfo.TheDef &&
3529 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003530 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003531 }
3532 }
3533 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003534 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003535}
3536
Chris Lattnercabe0372010-03-15 06:00:16 +00003537/// Given a pattern result with an unresolved type, see if we can find one
3538/// instruction with an unresolved result type. Force this result type to an
3539/// arbitrary element if it's possible types to converge results.
3540static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3541 if (N->isLeaf())
3542 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003543
Chris Lattnercabe0372010-03-15 06:00:16 +00003544 // Analyze children.
3545 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3546 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3547 return true;
3548
3549 if (!N->getOperator()->isSubClassOf("Instruction"))
3550 return false;
3551
3552 // If this type is already concrete or completely unknown we can't do
3553 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003554 TypeInfer &TI = TP.getInfer();
Chris Lattnerf1447252010-03-19 21:37:09 +00003555 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003556 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003557 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003558
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003559 // Otherwise, force its type to an arbitrary choice.
3560 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003561 return true;
3562 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003563
Chris Lattnerf1447252010-03-19 21:37:09 +00003564 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003565}
3566
Chris Lattnerab3242f2008-01-06 01:10:31 +00003567void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003568 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3569
Craig Topper306cb122015-11-22 20:46:24 +00003570 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003571 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003572
3573 // If the pattern references the null_frag, there's nothing to do.
3574 if (hasNullFragReference(Tree))
3575 continue;
3576
Chris Lattner5c2182e2010-03-27 02:53:27 +00003577 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003578
3579 // Inline pattern fragments into it.
3580 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003581
David Greeneaf8ee2c2011-07-29 22:43:06 +00003582 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003583 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003584
Chris Lattner8cab0212008-01-05 22:25:12 +00003585 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003586 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003587
Chris Lattner8cab0212008-01-05 22:25:12 +00003588 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003589 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003590
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003591 if (Result.getNumTrees() != 1)
3592 Result.error("Cannot handle instructions producing instructions "
3593 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003594
Chris Lattner8cab0212008-01-05 22:25:12 +00003595 bool IterateInference;
3596 bool InferredAllPatternTypes, InferredAllResultTypes;
3597 do {
3598 // Infer as many types as possible. If we cannot infer all of them, we
3599 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003600 InferredAllPatternTypes =
3601 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003602
Chris Lattner8cab0212008-01-05 22:25:12 +00003603 // Infer as many types as possible. If we cannot infer all of them, we
3604 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003605 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003606 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003607
Chris Lattnerfdc20712010-03-18 23:15:10 +00003608 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003609
Chris Lattner8cab0212008-01-05 22:25:12 +00003610 // Apply the type of the result to the source pattern. This helps us
3611 // resolve cases where the input type is known to be a pointer type (which
3612 // is considered resolved), but the result knows it needs to be 32- or
3613 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003614 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003615 Pattern->getTree(0)->getNumTypes());
3616 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003617 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3618 i, Result.getTree(0)->getExtType(i), Result);
3619 IterateInference |= Result.getTree(0)->UpdateNodeType(
3620 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003621 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003622
Chris Lattnercabe0372010-03-15 06:00:16 +00003623 // If our iteration has converged and the input pattern's types are fully
3624 // resolved but the result pattern is not fully resolved, we may have a
3625 // situation where we have two instructions in the result pattern and
3626 // the instructions require a common register class, but don't care about
3627 // what actual MVT is used. This is actually a bug in our modelling:
3628 // output patterns should have register classes, not MVTs.
3629 //
3630 // In any case, to handle this, we just go through and disambiguate some
3631 // arbitrary types to the result pattern's nodes.
3632 if (!IterateInference && InferredAllPatternTypes &&
3633 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003634 IterateInference =
3635 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003636 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003637
Chris Lattner8cab0212008-01-05 22:25:12 +00003638 // Verify that we inferred enough types that we can do something with the
3639 // pattern and result. If these fire the user has to add type casts.
3640 if (!InferredAllPatternTypes)
3641 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003642 if (!InferredAllResultTypes) {
3643 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003644 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003645 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003646
Chris Lattner8cab0212008-01-05 22:25:12 +00003647 // Validate that the input pattern is correct.
3648 std::map<std::string, TreePatternNode*> InstInputs;
3649 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003650 std::vector<Record*> InstImpResults;
3651 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3652 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3653 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003654 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003655
3656 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003657 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003658 std::vector<TreePatternNode*> ResultNodeOperands;
3659 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3660 TreePatternNode *OpNode = DstPattern->getChild(ii);
3661 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003662 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003663 std::vector<TreePatternNode*> Children;
3664 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003665 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003666 }
3667 ResultNodeOperands.push_back(OpNode);
3668 }
David Blaikiecf195302014-11-17 22:55:41 +00003669 DstPattern = Result.getOnlyTree();
3670 if (!DstPattern->isLeaf())
3671 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3672 ResultNodeOperands,
3673 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003674
David Blaikiecf195302014-11-17 22:55:41 +00003675 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3676 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3677
3678 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003679 Temp.InferAllTypes();
3680
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003681 // A pattern may end up with an "impossible" type, i.e. a situation
3682 // where all types have been eliminated for some node in this pattern.
3683 // This could occur for intrinsics that only make sense for a specific
3684 // value type, and use a specific register class. If, for some mode,
3685 // that register class does not accept that type, the type inference
3686 // will lead to a contradiction, which is not an error however, but
3687 // a sign that this pattern will simply never match.
3688 if (Pattern->getTree(0)->hasPossibleType() &&
3689 Temp.getOnlyTree()->hasPossibleType()) {
3690 ListInit *Preds = CurPattern->getValueAsListInit("Predicates");
3691 int Complexity = CurPattern->getValueAsInt("AddedComplexity");
3692 AddPatternToMatch(
3693 Pattern,
3694 PatternToMatch(
3695 CurPattern, makePredList(Preds), Pattern->getTree(0),
3696 Temp.getOnlyTree(), std::move(InstImpResults), Complexity,
3697 CurPattern->getID()));
3698 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003699 }
3700}
3701
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003702static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
3703 for (const TypeSetByHwMode &VTS : N->getExtTypes())
3704 for (const auto &I : VTS)
3705 Modes.insert(I.first);
3706
3707 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3708 collectModes(Modes, N->getChild(i));
3709}
3710
3711void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
3712 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3713 std::map<unsigned,std::vector<Predicate>> ModeChecks;
3714 std::vector<PatternToMatch> Copy = PatternsToMatch;
3715 PatternsToMatch.clear();
3716
3717 auto AppendPattern = [this,&ModeChecks](PatternToMatch &P, unsigned Mode) {
3718 TreePatternNode *NewSrc = P.SrcPattern->clone();
3719 TreePatternNode *NewDst = P.DstPattern->clone();
3720 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
3721 delete NewSrc;
3722 delete NewDst;
3723 return;
3724 }
3725
3726 std::vector<Predicate> Preds = P.Predicates;
3727 const std::vector<Predicate> &MC = ModeChecks[Mode];
3728 Preds.insert(Preds.end(), MC.begin(), MC.end());
3729 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, NewSrc, NewDst,
3730 P.getDstRegs(), P.getAddedComplexity(),
3731 Record::getNewUID(), Mode);
3732 };
3733
3734 for (PatternToMatch &P : Copy) {
3735 TreePatternNode *SrcP = nullptr, *DstP = nullptr;
3736 if (P.SrcPattern->hasProperTypeByHwMode())
3737 SrcP = P.SrcPattern;
3738 if (P.DstPattern->hasProperTypeByHwMode())
3739 DstP = P.DstPattern;
3740 if (!SrcP && !DstP) {
3741 PatternsToMatch.push_back(P);
3742 continue;
3743 }
3744
3745 std::set<unsigned> Modes;
3746 if (SrcP)
3747 collectModes(Modes, SrcP);
3748 if (DstP)
3749 collectModes(Modes, DstP);
3750
3751 // The predicate for the default mode needs to be constructed for each
3752 // pattern separately.
3753 // Since not all modes must be present in each pattern, if a mode m is
3754 // absent, then there is no point in constructing a check for m. If such
3755 // a check was created, it would be equivalent to checking the default
3756 // mode, except not all modes' predicates would be a part of the checking
3757 // code. The subsequently generated check for the default mode would then
3758 // have the exact same patterns, but a different predicate code. To avoid
3759 // duplicated patterns with different predicate checks, construct the
3760 // default check as a negation of all predicates that are actually present
3761 // in the source/destination patterns.
3762 std::vector<Predicate> DefaultPred;
3763
3764 for (unsigned M : Modes) {
3765 if (M == DefaultMode)
3766 continue;
3767 if (ModeChecks.find(M) != ModeChecks.end())
3768 continue;
3769
3770 // Fill the map entry for this mode.
3771 const HwMode &HM = CGH.getMode(M);
3772 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
3773
3774 // Add negations of the HM's predicates to the default predicate.
3775 DefaultPred.emplace_back(Predicate(HM.Features, false));
3776 }
3777
3778 for (unsigned M : Modes) {
3779 if (M == DefaultMode)
3780 continue;
3781 AppendPattern(P, M);
3782 }
3783
3784 bool HasDefault = Modes.count(DefaultMode);
3785 if (HasDefault)
3786 AppendPattern(P, DefaultMode);
3787 }
3788}
3789
3790/// Dependent variable map for CodeGenDAGPattern variant generation
3791typedef std::map<std::string, int> DepVarMap;
3792
3793static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
3794 if (N->isLeaf()) {
3795 if (isa<DefInit>(N->getLeafValue()))
3796 DepMap[N->getName()]++;
3797 } else {
3798 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
3799 FindDepVarsOf(N->getChild(i), DepMap);
3800 }
3801}
3802
3803/// Find dependent variables within child patterns
3804static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
3805 DepVarMap depcounts;
3806 FindDepVarsOf(N, depcounts);
3807 for (const std::pair<std::string, int> &Pair : depcounts) {
3808 if (Pair.second > 1)
3809 DepVars.insert(Pair.first);
3810 }
3811}
3812
3813#ifndef NDEBUG
3814/// Dump the dependent variable set:
3815static void DumpDepVars(MultipleUseVarSet &DepVars) {
3816 if (DepVars.empty()) {
3817 DEBUG(errs() << "<empty set>");
3818 } else {
3819 DEBUG(errs() << "[ ");
3820 for (const std::string &DepVar : DepVars) {
3821 DEBUG(errs() << DepVar << " ");
3822 }
3823 DEBUG(errs() << "]");
3824 }
3825}
3826#endif
3827
3828
Chris Lattner8cab0212008-01-05 22:25:12 +00003829/// CombineChildVariants - Given a bunch of permutations of each child of the
3830/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003831static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003832 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3833 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003834 CodeGenDAGPatterns &CDP,
3835 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003836 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003837 for (const auto &Variants : ChildVariants)
3838 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003839 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003840
Chris Lattner8cab0212008-01-05 22:25:12 +00003841 // The end result is an all-pairs construction of the resultant pattern.
3842 std::vector<unsigned> Idxs;
3843 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003844 bool NotDone;
3845 do {
3846#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003847 DEBUG(if (!Idxs.empty()) {
3848 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003849 for (unsigned Idx : Idxs) {
3850 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003851 }
3852 errs() << "]\n";
3853 });
Scott Michel94420742008-03-05 17:49:05 +00003854#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003855 // Create the variant and add it to the output list.
3856 std::vector<TreePatternNode*> NewChildren;
3857 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3858 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003859 auto R = llvm::make_unique<TreePatternNode>(
3860 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003861
Chris Lattner8cab0212008-01-05 22:25:12 +00003862 // Copy over properties.
3863 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003864 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003865 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003866 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3867 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003868
Scott Michel94420742008-03-05 17:49:05 +00003869 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003870 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003871 // Scan to see if this pattern has already been emitted. We can get
3872 // duplication due to things like commuting:
3873 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3874 // which are the same pattern. Ignore the dups.
3875 if (R->canPatternMatch(ErrString, CDP) &&
David Majnemer0a16c222016-08-11 21:15:00 +00003876 none_of(OutVariants, [&](TreePatternNode *Variant) {
3877 return R->isIsomorphicTo(Variant, DepVars);
3878 }))
David Blaikiefda69dd2015-11-22 20:11:21 +00003879 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003880
Scott Michel94420742008-03-05 17:49:05 +00003881 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003882 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003883 // [0, 0], [0, 1], [1, 0], [1, 1].
3884 int IdxsIdx;
3885 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3886 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3887 Idxs[IdxsIdx] = 0;
3888 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003889 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003890 }
Scott Michel94420742008-03-05 17:49:05 +00003891 NotDone = (IdxsIdx >= 0);
3892 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003893}
3894
3895/// CombineChildVariants - A helper function for binary operators.
3896///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003897static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003898 const std::vector<TreePatternNode*> &LHS,
3899 const std::vector<TreePatternNode*> &RHS,
3900 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003901 CodeGenDAGPatterns &CDP,
3902 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003903 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3904 ChildVariants.push_back(LHS);
3905 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003906 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003907}
Chris Lattner8cab0212008-01-05 22:25:12 +00003908
3909
3910static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3911 std::vector<TreePatternNode *> &Children) {
3912 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3913 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003914
Chris Lattner8cab0212008-01-05 22:25:12 +00003915 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003916 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003917 N->getTransformFn()) {
3918 Children.push_back(N);
3919 return;
3920 }
3921
3922 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3923 Children.push_back(N->getChild(0));
3924 else
3925 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3926
3927 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3928 Children.push_back(N->getChild(1));
3929 else
3930 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3931}
3932
3933/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3934/// the (potentially recursive) pattern by using algebraic laws.
3935///
3936static void GenerateVariantsOf(TreePatternNode *N,
3937 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003938 CodeGenDAGPatterns &CDP,
3939 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003940 // We cannot permute leaves or ComplexPattern uses.
3941 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003942 OutVariants.push_back(N);
3943 return;
3944 }
3945
3946 // Look up interesting info about the node.
3947 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3948
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003949 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003950 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003951 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003952 std::vector<TreePatternNode*> MaximalChildren;
3953 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3954
3955 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3956 // permutations.
3957 if (MaximalChildren.size() == 3) {
3958 // Find the variants of all of our maximal children.
3959 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003960 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3961 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3962 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003963
Chris Lattner8cab0212008-01-05 22:25:12 +00003964 // There are only two ways we can permute the tree:
3965 // (A op B) op C and A op (B op C)
3966 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003967
Chris Lattner8cab0212008-01-05 22:25:12 +00003968 // Generate legal pair permutations of A/B/C.
3969 std::vector<TreePatternNode*> ABVariants;
3970 std::vector<TreePatternNode*> BAVariants;
3971 std::vector<TreePatternNode*> ACVariants;
3972 std::vector<TreePatternNode*> CAVariants;
3973 std::vector<TreePatternNode*> BCVariants;
3974 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003975 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3976 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3977 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3978 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3979 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3980 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003981
3982 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003983 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3984 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3985 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3986 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3987 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3988 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003989
3990 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003991 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3992 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3993 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3994 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3995 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3996 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003997 return;
3998 }
3999 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004000
Chris Lattner8cab0212008-01-05 22:25:12 +00004001 // Compute permutations of all children.
4002 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4003 ChildVariants.resize(N->getNumChildren());
4004 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00004005 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004006
4007 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00004008 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004009
4010 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004011 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4012 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004013 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004014 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004015 // Don't count children which are actually register references.
4016 unsigned NC = 0;
4017 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4018 TreePatternNode *Child = N->getChild(i);
4019 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00004020 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004021 Record *RR = DI->getDef();
4022 if (RR->isSubClassOf("Register"))
4023 continue;
4024 }
4025 NC++;
4026 }
4027 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004028 if (isCommIntrinsic) {
4029 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4030 // operands are the commutative operands, and there might be more operands
4031 // after those.
4032 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004033 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00004034 std::vector<std::vector<TreePatternNode*> > Variants;
4035 Variants.push_back(ChildVariants[0]); // Intrinsic id.
4036 Variants.push_back(ChildVariants[2]);
4037 Variants.push_back(ChildVariants[1]);
4038 for (unsigned i = 3; i != NC; ++i)
4039 Variants.push_back(ChildVariants[i]);
4040 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004041 } else if (NC == N->getNumChildren()) {
4042 std::vector<std::vector<TreePatternNode*> > Variants;
4043 Variants.push_back(ChildVariants[1]);
4044 Variants.push_back(ChildVariants[0]);
4045 for (unsigned i = 2; i != NC; ++i)
4046 Variants.push_back(ChildVariants[i]);
4047 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4048 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004049 }
4050}
4051
4052
4053// GenerateVariants - Generate variants. For example, commutative patterns can
4054// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004055void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00004056 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004057
Chris Lattner8cab0212008-01-05 22:25:12 +00004058 // Loop over all of the patterns we've collected, checking to see if we can
4059 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004060 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004061 // the .td file having to contain tons of variants of instructions.
4062 //
4063 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4064 // intentionally do not reconsider these. Any variants of added patterns have
4065 // already been added.
4066 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00004067 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00004068 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00004069 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004070 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00004071 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00004072 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00004073 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00004074 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00004075 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004076
4077 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00004078 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004079 continue;
4080
Chris Lattner34822f62009-08-23 04:44:11 +00004081 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00004082 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00004083 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004084
4085 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4086 TreePatternNode *Variant = Variants[v];
4087
Chris Lattner34822f62009-08-23 04:44:11 +00004088 DEBUG(errs() << " VAR#" << v << ": ";
4089 Variant->dump();
4090 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004091
Chris Lattner8cab0212008-01-05 22:25:12 +00004092 // Scan to see if an instruction or explicit pattern already matches this.
4093 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004094 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004095 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004096 if (PatternsToMatch[i].getPredicates() !=
4097 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00004098 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004099 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004100 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4101 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00004102 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004103 AlreadyExists = true;
4104 break;
4105 }
4106 }
4107 // If we already have it, ignore the variant.
4108 if (AlreadyExists) continue;
4109
4110 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004111 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004112 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4113 Variant, PatternsToMatch[i].getDstPattern(),
4114 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004115 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00004116 }
4117
Chris Lattner34822f62009-08-23 04:44:11 +00004118 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004119 }
4120}