blob: b8ba5db6ef4c31fe05e9be89f1b230283802a822 [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"
Zachary Turner249dc142017-09-20 18:01:40 +000016#include "llvm/ADT/DenseSet.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000017#include "llvm/ADT/STLExtras.h"
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000018#include "llvm/ADT/SmallSet.h"
Craig Topper3522ab32015-11-28 08:23:02 +000019#include "llvm/ADT/SmallString.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000020#include "llvm/ADT/StringExtras.h"
Craig Topperddfdd942017-09-21 04:55:03 +000021#include "llvm/ADT/StringMap.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000022#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000023#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000024#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000025#include "llvm/TableGen/Error.h"
26#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000027#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000028#include <cstdio>
29#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000030using namespace llvm;
31
Chandler Carruthe96dd892014-04-21 22:55:11 +000032#define DEBUG_TYPE "dag-patterns"
33
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000034static inline bool isIntegerOrPtr(MVT VT) {
35 return VT.isInteger() || VT == MVT::iPTR;
Duncan Sands13237ac2008-06-06 12:08:01 +000036}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000037static inline bool isFloatingPoint(MVT VT) {
38 return VT.isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000039}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000040static inline bool isVector(MVT VT) {
41 return VT.isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000042}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000043static inline bool isScalar(MVT VT) {
44 return !VT.isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000045}
Duncan Sands13237ac2008-06-06 12:08:01 +000046
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000047template <typename Predicate>
48static bool berase_if(MachineValueTypeSet &S, Predicate P) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000049 bool Erased = false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000050 // It is ok to iterate over MachineValueTypeSet and remove elements from it
51 // at the same time.
52 for (MVT T : S) {
53 if (!P(T))
54 continue;
55 Erased = true;
56 S.erase(T);
Chris Lattnercabe0372010-03-15 06:00:16 +000057 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000058 return Erased;
Chris Lattner8cab0212008-01-05 22:25:12 +000059}
60
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000061// --- TypeSetByHwMode
Chris Lattnercabe0372010-03-15 06:00:16 +000062
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000063// This is a parameterized type-set class. For each mode there is a list
64// of types that are currently possible for a given tree node. Type
65// inference will apply to each mode separately.
Jim Grosbach65586fe2010-12-21 16:16:00 +000066
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000067TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
68 for (const ValueTypeByHwMode &VVT : VTList)
69 insert(VVT);
Chris Lattner8cab0212008-01-05 22:25:12 +000070}
71
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000072bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
73 for (const auto &I : *this) {
74 if (I.second.size() > 1)
75 return false;
76 if (!AllowEmpty && I.second.empty())
77 return false;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000078 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000079 return true;
80}
Chris Lattnercabe0372010-03-15 06:00:16 +000081
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000082ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
83 assert(isValueTypeByHwMode(true) &&
84 "The type set has multiple types for at least one HW mode");
85 ValueTypeByHwMode VVT;
86 for (const auto &I : *this) {
87 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
88 VVT.getOrCreateTypeForMode(I.first, T);
Chris Lattnercabe0372010-03-15 06:00:16 +000089 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000090 return VVT;
Bob Wilson2cd5da82009-08-11 01:14:02 +000091}
Chris Lattnercabe0372010-03-15 06:00:16 +000092
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000093bool TypeSetByHwMode::isPossible() const {
94 for (const auto &I : *this)
95 if (!I.second.empty())
96 return true;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000097 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +000098}
99
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000100bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
101 bool Changed = false;
Zachary Turner249dc142017-09-20 18:01:40 +0000102 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000103 for (const auto &P : VVT) {
104 unsigned M = P.first;
105 Modes.insert(M);
106 // Make sure there exists a set for each specific mode from VVT.
107 Changed |= getOrCreate(M).insert(P.second).second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000108 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000109
110 // If VVT has a default mode, add the corresponding type to all
111 // modes in "this" that do not exist in VVT.
112 if (Modes.count(DefaultMode)) {
113 MVT DT = VVT.getType(DefaultMode);
114 for (auto &I : *this)
115 if (!Modes.count(I.first))
116 Changed |= I.second.insert(DT).second;
117 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000118 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000119}
120
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000121// Constrain the type set to be the intersection with VTS.
122bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
123 bool Changed = false;
124 if (hasDefault()) {
125 for (const auto &I : VTS) {
126 unsigned M = I.first;
127 if (M == DefaultMode || hasMode(M))
128 continue;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000129 Map.insert({M, Map.at(DefaultMode)});
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000130 Changed = true;
131 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000132 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000133
134 for (auto &I : *this) {
135 unsigned M = I.first;
136 SetType &S = I.second;
137 if (VTS.hasMode(M) || VTS.hasDefault()) {
138 Changed |= intersect(I.second, VTS.get(M));
139 } else if (!S.empty()) {
140 S.clear();
141 Changed = true;
142 }
143 }
144 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000145}
146
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000147template <typename Predicate>
148bool TypeSetByHwMode::constrain(Predicate P) {
149 bool Changed = false;
150 for (auto &I : *this)
Benjamin Kramere57308e2017-09-17 11:19:53 +0000151 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000152 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000153}
154
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000155template <typename Predicate>
156bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
157 assert(empty());
158 for (const auto &I : VTS) {
159 SetType &S = getOrCreate(I.first);
160 for (auto J : I.second)
161 if (P(J))
162 S.insert(J);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000163 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000164 return !empty();
Chris Lattnercabe0372010-03-15 06:00:16 +0000165}
166
Zachary Turner249dc142017-09-20 18:01:40 +0000167void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
168 SmallVector<unsigned, 4> Modes;
169 Modes.reserve(Map.size());
Chris Lattnercabe0372010-03-15 06:00:16 +0000170
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000171 for (const auto &I : *this)
172 Modes.push_back(I.first);
Zachary Turner249dc142017-09-20 18:01:40 +0000173 if (Modes.empty()) {
174 OS << "{}";
175 return;
176 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000177 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000178
Zachary Turner249dc142017-09-20 18:01:40 +0000179 OS << '{';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000180 for (unsigned M : Modes) {
Zachary Turner249dc142017-09-20 18:01:40 +0000181 OS << ' ' << getModeName(M) << ':';
182 writeToStream(get(M), OS);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000183 }
Zachary Turner249dc142017-09-20 18:01:40 +0000184 OS << " }";
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000185}
186
Zachary Turner249dc142017-09-20 18:01:40 +0000187void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
188 SmallVector<MVT, 4> Types(S.begin(), S.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000189 array_pod_sort(Types.begin(), Types.end());
190
Zachary Turner249dc142017-09-20 18:01:40 +0000191 OS << '[';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000192 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
Zachary Turner249dc142017-09-20 18:01:40 +0000193 OS << ValueTypeByHwMode::getMVTName(Types[i]);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000194 if (i != e-1)
Zachary Turner249dc142017-09-20 18:01:40 +0000195 OS << ' ';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000196 }
Zachary Turner249dc142017-09-20 18:01:40 +0000197 OS << ']';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000198}
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 Parzyszekaffd2012017-09-19 18:42:34 +0000205 if (isSimple()) {
206 if (VTS.isSimple())
207 return *begin() == *VTS.begin();
208 return false;
209 }
210
Zachary Turner249dc142017-09-20 18:01:40 +0000211 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000212 for (auto &I : *this)
213 Modes.insert(I.first);
214 for (const auto &I : VTS)
215 Modes.insert(I.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000216
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000217 if (HaveDefault) {
218 // Both sets have default mode.
219 for (unsigned M : Modes) {
220 if (get(M) != VTS.get(M))
David Majnemerc7004902016-08-12 04:32:37 +0000221 return false;
Craig Topper5712d462015-11-24 08:20:47 +0000222 }
Scott Michel94420742008-03-05 17:49:05 +0000223 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000224 // Neither set has default mode.
225 for (unsigned M : Modes) {
226 // If there is no default mode, an empty set is equivalent to not having
227 // the corresponding mode.
228 bool NoModeThis = !hasMode(M) || get(M).empty();
229 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
230 if (NoModeThis != NoModeVTS)
231 return false;
232 if (!NoModeThis)
233 if (get(M) != VTS.get(M))
234 return false;
235 }
Scott Michel94420742008-03-05 17:49:05 +0000236 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000237
238 return true;
Scott Michel94420742008-03-05 17:49:05 +0000239}
240
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000241namespace llvm {
242 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
243 T.writeToStream(OS);
244 return OS;
245 }
246}
247
Krzysztof Parzyszek426bf362017-09-12 15:31:26 +0000248LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000249void TypeSetByHwMode::dump() const {
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000250 dbgs() << *this << '\n';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000251}
252
253bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
254 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
255 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
256
257 if (OutP == InP)
258 return berase_if(Out, Int);
259
260 // Compute the intersection of scalars separately to account for only
261 // one set containing iPTR.
262 // The itersection of iPTR with a set of integer scalar types that does not
263 // include iPTR will result in the most specific scalar type:
264 // - iPTR is more specific than any set with two elements or more
265 // - iPTR is less specific than any single integer scalar type.
266 // For example
267 // { iPTR } * { i32 } -> { i32 }
268 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000269 // and
270 // { iPTR i32 } * { i32 } -> { i32 }
271 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
272 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000273
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000274 // Compute the difference between the two sets in such a way that the
275 // iPTR is in the set that is being subtracted. This is to see if there
276 // are any extra scalars in the set without iPTR that are not in the
277 // set containing iPTR. Then the iPTR could be considered a "wildcard"
278 // matching these scalars. If there is only one such scalar, it would
279 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000280 SetType Diff;
281 if (InP) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000282 Diff = Out;
283 berase_if(Diff, [&In](MVT T) { return In.count(T); });
284 // Pre-remove these elements and rely only on InP/OutP to determine
285 // whether a change has been made.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000286 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000287 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000288 Diff = In;
289 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000290 Out.erase(MVT::iPTR);
291 }
292
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000293 // The actual intersection.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000294 bool Changed = berase_if(Out, Int);
295 unsigned NumD = Diff.size();
296 if (NumD == 0)
297 return Changed;
298
299 if (NumD == 1) {
300 Out.insert(*Diff.begin());
301 // This is a change only if Out was the one with iPTR (which is now
302 // being replaced).
303 Changed |= OutP;
304 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000305 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000306 Out.insert(MVT::iPTR);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000307 Changed |= !OutP;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000308 }
309 return Changed;
310}
311
312void TypeSetByHwMode::validate() const {
313#ifndef NDEBUG
314 if (empty())
315 return;
316 bool AllEmpty = true;
317 for (const auto &I : *this)
318 AllEmpty &= I.second.empty();
319 assert(!AllEmpty &&
320 "type set is empty for each HW mode: type contradiction?");
321#endif
322}
323
324// --- TypeInfer
325
326bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
327 const TypeSetByHwMode &In) {
328 ValidateOnExit _1(Out);
329 In.validate();
330 if (In.empty() || Out == In || TP.hasError())
331 return false;
332 if (Out.empty()) {
333 Out = In;
334 return true;
335 }
336
337 bool Changed = Out.constrain(In);
338 if (Changed && Out.empty())
339 TP.error("Type contradiction");
340
341 return Changed;
342}
343
344bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
345 ValidateOnExit _1(Out);
346 if (TP.hasError())
347 return false;
348 assert(!Out.empty() && "cannot pick from an empty set");
349
350 bool Changed = false;
351 for (auto &I : Out) {
352 TypeSetByHwMode::SetType &S = I.second;
353 if (S.size() <= 1)
354 continue;
355 MVT T = *S.begin(); // Pick the first element.
356 S.clear();
357 S.insert(T);
358 Changed = true;
359 }
360 return Changed;
361}
362
363bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
364 ValidateOnExit _1(Out);
365 if (TP.hasError())
366 return false;
367 if (!Out.empty())
368 return Out.constrain(isIntegerOrPtr);
369
370 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
371}
372
373bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
374 ValidateOnExit _1(Out);
375 if (TP.hasError())
376 return false;
377 if (!Out.empty())
378 return Out.constrain(isFloatingPoint);
379
380 return Out.assign_if(getLegalTypes(), isFloatingPoint);
381}
382
383bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
384 ValidateOnExit _1(Out);
385 if (TP.hasError())
386 return false;
387 if (!Out.empty())
388 return Out.constrain(isScalar);
389
390 return Out.assign_if(getLegalTypes(), isScalar);
391}
392
393bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
394 ValidateOnExit _1(Out);
395 if (TP.hasError())
396 return false;
397 if (!Out.empty())
398 return Out.constrain(isVector);
399
400 return Out.assign_if(getLegalTypes(), isVector);
401}
402
403bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
404 ValidateOnExit _1(Out);
405 if (TP.hasError() || !Out.empty())
406 return false;
407
408 Out = getLegalTypes();
409 return true;
410}
411
412template <typename Iter, typename Pred, typename Less>
413static Iter min_if(Iter B, Iter E, Pred P, Less L) {
414 if (B == E)
415 return E;
416 Iter Min = E;
417 for (Iter I = B; I != E; ++I) {
418 if (!P(*I))
419 continue;
420 if (Min == E || L(*I, *Min))
421 Min = I;
422 }
423 return Min;
424}
425
426template <typename Iter, typename Pred, typename Less>
427static Iter max_if(Iter B, Iter E, Pred P, Less L) {
428 if (B == E)
429 return E;
430 Iter Max = E;
431 for (Iter I = B; I != E; ++I) {
432 if (!P(*I))
433 continue;
434 if (Max == E || L(*Max, *I))
435 Max = I;
436 }
437 return Max;
438}
439
440/// Make sure that for each type in Small, there exists a larger type in Big.
441bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
442 TypeSetByHwMode &Big) {
443 ValidateOnExit _1(Small), _2(Big);
444 if (TP.hasError())
445 return false;
446 bool Changed = false;
447
448 if (Small.empty())
449 Changed |= EnforceAny(Small);
450 if (Big.empty())
451 Changed |= EnforceAny(Big);
452
453 assert(Small.hasDefault() && Big.hasDefault());
454
455 std::vector<unsigned> Modes = union_modes(Small, Big);
456
457 // 1. Only allow integer or floating point types and make sure that
458 // both sides are both integer or both floating point.
459 // 2. Make sure that either both sides have vector types, or neither
460 // of them does.
461 for (unsigned M : Modes) {
462 TypeSetByHwMode::SetType &S = Small.get(M);
463 TypeSetByHwMode::SetType &B = Big.get(M);
464
465 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000466 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000467 Changed |= berase_if(S, NotInt) |
468 berase_if(B, NotInt);
469 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000470 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000471 Changed |= berase_if(S, NotFP) |
472 berase_if(B, NotFP);
473 } else if (S.empty() || B.empty()) {
474 Changed = !S.empty() || !B.empty();
475 S.clear();
476 B.clear();
477 } else {
478 TP.error("Incompatible types");
479 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000480 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000481
482 if (none_of(S, isVector) || none_of(B, isVector)) {
483 Changed |= berase_if(S, isVector) |
484 berase_if(B, isVector);
485 }
486 }
487
488 auto LT = [](MVT A, MVT B) -> bool {
489 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
490 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
491 A.getSizeInBits() < B.getSizeInBits());
492 };
493 auto LE = [](MVT A, MVT B) -> bool {
494 // This function is used when removing elements: when a vector is compared
495 // to a non-vector, it should return false (to avoid removal).
496 if (A.isVector() != B.isVector())
497 return false;
498
499 // Note on the < comparison below:
500 // X86 has patterns like
501 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
502 // where the truncated vector is given a type v16i8, while the source
503 // vector has type v4i32. They both have the same size in bits.
504 // The minimal type in the result is obviously v16i8, and when we remove
505 // all types from the source that are smaller-or-equal than v8i16, the
506 // only source type would also be removed (since it's equal in size).
507 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
508 A.getSizeInBits() < B.getSizeInBits();
509 };
510
511 for (unsigned M : Modes) {
512 TypeSetByHwMode::SetType &S = Small.get(M);
513 TypeSetByHwMode::SetType &B = Big.get(M);
514 // MinS = min scalar in Small, remove all scalars from Big that are
515 // smaller-or-equal than MinS.
516 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000517 if (MinS != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000518 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000519
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000520 // MaxS = max scalar in Big, remove all scalars from Small that are
521 // larger than MaxS.
522 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000523 if (MaxS != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000524 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000525
526 // MinV = min vector in Small, remove all vectors from Big that are
527 // smaller-or-equal than MinV.
528 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000529 if (MinV != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000530 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000531
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000532 // MaxV = max vector in Big, remove all vectors from Small that are
533 // larger than MaxV.
534 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000535 if (MaxV != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000536 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000537 }
538
539 return Changed;
540}
541
542/// 1. Ensure that for each type T in Vec, T is a vector type, and that
543/// for each type U in Elem, U is a scalar type.
544/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
545/// type T in Vec, such that U is the element type of T.
546bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
547 TypeSetByHwMode &Elem) {
548 ValidateOnExit _1(Vec), _2(Elem);
549 if (TP.hasError())
550 return false;
551 bool Changed = false;
552
553 if (Vec.empty())
554 Changed |= EnforceVector(Vec);
555 if (Elem.empty())
556 Changed |= EnforceScalar(Elem);
557
558 for (unsigned M : union_modes(Vec, Elem)) {
559 TypeSetByHwMode::SetType &V = Vec.get(M);
560 TypeSetByHwMode::SetType &E = Elem.get(M);
561
562 Changed |= berase_if(V, isScalar); // Scalar = !vector
563 Changed |= berase_if(E, isVector); // Vector = !scalar
564 assert(!V.empty() && !E.empty());
565
566 SmallSet<MVT,4> VT, ST;
567 // Collect element types from the "vector" set.
568 for (MVT T : V)
569 VT.insert(T.getVectorElementType());
570 // Collect scalar types from the "element" set.
571 for (MVT T : E)
572 ST.insert(T);
573
574 // Remove from V all (vector) types whose element type is not in S.
575 Changed |= berase_if(V, [&ST](MVT T) -> bool {
576 return !ST.count(T.getVectorElementType());
577 });
578 // Remove from E all (scalar) types, for which there is no corresponding
579 // type in V.
580 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000581 }
582
583 return Changed;
584}
585
586bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
587 const ValueTypeByHwMode &VVT) {
588 TypeSetByHwMode Tmp(VVT);
589 ValidateOnExit _1(Vec), _2(Tmp);
590 return EnforceVectorEltTypeIs(Vec, Tmp);
591}
592
593/// Ensure that for each type T in Sub, T is a vector type, and there
594/// exists a type U in Vec such that U is a vector type with the same
595/// element type as T and at least as many elements as T.
596bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
597 TypeSetByHwMode &Sub) {
598 ValidateOnExit _1(Vec), _2(Sub);
599 if (TP.hasError())
600 return false;
601
602 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
603 auto IsSubVec = [](MVT B, MVT P) -> bool {
604 if (!B.isVector() || !P.isVector())
605 return false;
Florian Hahn603c6452017-11-07 10:43:56 +0000606 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
607 // but until there are obvious use-cases for this, keep the
608 // types separate.
609 if (B.isScalableVector() != P.isScalableVector())
610 return false;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000611 if (B.getVectorElementType() != P.getVectorElementType())
612 return false;
613 return B.getVectorNumElements() < P.getVectorNumElements();
614 };
615
616 /// Return true if S has no element (vector type) that T is a sub-vector of,
617 /// i.e. has the same element type as T and more elements.
618 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
619 for (const auto &I : S)
620 if (IsSubVec(T, I))
621 return false;
622 return true;
623 };
624
625 /// Return true if S has no element (vector type) that T is a super-vector
626 /// of, i.e. has the same element type as T and fewer elements.
627 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
628 for (const auto &I : S)
629 if (IsSubVec(I, T))
630 return false;
631 return true;
632 };
633
634 bool Changed = false;
635
636 if (Vec.empty())
637 Changed |= EnforceVector(Vec);
638 if (Sub.empty())
639 Changed |= EnforceVector(Sub);
640
641 for (unsigned M : union_modes(Vec, Sub)) {
642 TypeSetByHwMode::SetType &S = Sub.get(M);
643 TypeSetByHwMode::SetType &V = Vec.get(M);
644
645 Changed |= berase_if(S, isScalar);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000646
647 // Erase all types from S that are not sub-vectors of a type in V.
648 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000649
650 // Erase all types from V that are not super-vectors of a type in S.
651 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000652 }
653
654 return Changed;
655}
656
657/// 1. Ensure that V has a scalar type iff W has a scalar type.
658/// 2. Ensure that for each vector type T in V, there exists a vector
659/// type U in W, such that T and U have the same number of elements.
660/// 3. Ensure that for each vector type U in W, there exists a vector
661/// type T in V, such that T and U have the same number of elements
662/// (reverse of 2).
663bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
664 ValidateOnExit _1(V), _2(W);
665 if (TP.hasError())
666 return false;
667
668 bool Changed = false;
669 if (V.empty())
670 Changed |= EnforceAny(V);
671 if (W.empty())
672 Changed |= EnforceAny(W);
673
674 // An actual vector type cannot have 0 elements, so we can treat scalars
675 // as zero-length vectors. This way both vectors and scalars can be
676 // processed identically.
677 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
678 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
679 };
680
681 for (unsigned M : union_modes(V, W)) {
682 TypeSetByHwMode::SetType &VS = V.get(M);
683 TypeSetByHwMode::SetType &WS = W.get(M);
684
685 SmallSet<unsigned,2> VN, WN;
686 for (MVT T : VS)
687 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
688 for (MVT T : WS)
689 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
690
691 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
692 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
693 }
694 return Changed;
695}
696
697/// 1. Ensure that for each type T in A, there exists a type U in B,
698/// such that T and U have equal size in bits.
699/// 2. Ensure that for each type U in B, there exists a type T in A
700/// such that T and U have equal size in bits (reverse of 1).
701bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
702 ValidateOnExit _1(A), _2(B);
703 if (TP.hasError())
704 return false;
705 bool Changed = false;
706 if (A.empty())
707 Changed |= EnforceAny(A);
708 if (B.empty())
709 Changed |= EnforceAny(B);
710
711 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
712 return !Sizes.count(T.getSizeInBits());
713 };
714
715 for (unsigned M : union_modes(A, B)) {
716 TypeSetByHwMode::SetType &AS = A.get(M);
717 TypeSetByHwMode::SetType &BS = B.get(M);
718 SmallSet<unsigned,2> AN, BN;
719
720 for (MVT T : AS)
721 AN.insert(T.getSizeInBits());
722 for (MVT T : BS)
723 BN.insert(T.getSizeInBits());
724
725 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
726 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
727 }
728
729 return Changed;
730}
731
732void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
733 ValidateOnExit _1(VTS);
734 TypeSetByHwMode Legal = getLegalTypes();
735 bool HaveLegalDef = Legal.hasDefault();
736
737 for (auto &I : VTS) {
738 unsigned M = I.first;
739 if (!Legal.hasMode(M) && !HaveLegalDef) {
740 TP.error("Invalid mode " + Twine(M));
741 return;
742 }
743 expandOverloads(I.second, Legal.get(M));
Scott Michel94420742008-03-05 17:49:05 +0000744 }
745}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000746
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000747void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
748 const TypeSetByHwMode::SetType &Legal) {
749 std::set<MVT> Ovs;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000750 for (MVT T : Out) {
751 if (!T.isOverloaded())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000752 continue;
Zachary Turner249dc142017-09-20 18:01:40 +0000753
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000754 Ovs.insert(T);
755 // MachineValueTypeSet allows iteration and erasing.
756 Out.erase(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000757 }
758
759 for (MVT Ov : Ovs) {
760 switch (Ov.SimpleTy) {
761 case MVT::iPTRAny:
762 Out.insert(MVT::iPTR);
763 return;
764 case MVT::iAny:
765 for (MVT T : MVT::integer_valuetypes())
766 if (Legal.count(T))
767 Out.insert(T);
768 for (MVT T : MVT::integer_vector_valuetypes())
769 if (Legal.count(T))
770 Out.insert(T);
771 return;
772 case MVT::fAny:
773 for (MVT T : MVT::fp_valuetypes())
774 if (Legal.count(T))
775 Out.insert(T);
776 for (MVT T : MVT::fp_vector_valuetypes())
777 if (Legal.count(T))
778 Out.insert(T);
779 return;
780 case MVT::vAny:
781 for (MVT T : MVT::vector_valuetypes())
782 if (Legal.count(T))
783 Out.insert(T);
784 return;
785 case MVT::Any:
786 for (MVT T : MVT::all_valuetypes())
787 if (Legal.count(T))
788 Out.insert(T);
789 return;
790 default:
791 break;
792 }
793 }
794}
795
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000796TypeSetByHwMode TypeInfer::getLegalTypes() {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000797 if (!LegalTypesCached) {
798 // Stuff all types from all modes into the default mode.
799 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
800 for (const auto &I : LTS)
801 LegalCache.insert(I.second);
802 LegalTypesCached = true;
803 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000804 TypeSetByHwMode VTS;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000805 VTS.getOrCreate(DefaultMode) = LegalCache;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000806 return VTS;
807}
Chris Lattner514e2922011-04-17 21:38:24 +0000808
809//===----------------------------------------------------------------------===//
810// TreePredicateFn Implementation
811//===----------------------------------------------------------------------===//
812
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000813/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
814TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000815 assert(
816 (!hasPredCode() || !hasImmCode()) &&
817 ".td file corrupt: can't have a node predicate *and* an imm predicate");
818}
819
820bool TreePredicateFn::hasPredCode() const {
Daniel Sanders87d196c2017-11-13 22:26:13 +0000821 return isLoad() || isStore() || isAtomic() ||
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000822 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000823}
824
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000825std::string TreePredicateFn::getPredCode() const {
826 std::string Code = "";
827
Daniel Sanders87d196c2017-11-13 22:26:13 +0000828 if (!isLoad() && !isStore() && !isAtomic()) {
829 Record *MemoryVT = getMemoryVT();
830
831 if (MemoryVT)
832 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
833 "MemoryVT requires IsLoad or IsStore");
834 }
835
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000836 if (!isLoad() && !isStore()) {
837 if (isUnindexed())
838 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
839 "IsUnindexed requires IsLoad or IsStore");
840
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000841 Record *ScalarMemoryVT = getScalarMemoryVT();
842
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000843 if (ScalarMemoryVT)
844 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
845 "ScalarMemoryVT requires IsLoad or IsStore");
846 }
847
Daniel Sanders87d196c2017-11-13 22:26:13 +0000848 if (isLoad() + isStore() + isAtomic() > 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000849 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
Daniel Sanders87d196c2017-11-13 22:26:13 +0000850 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000851
852 if (isLoad()) {
853 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
854 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
855 getScalarMemoryVT() == nullptr)
856 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
857 "IsLoad cannot be used by itself");
858 } else {
859 if (isNonExtLoad())
860 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
861 "IsNonExtLoad requires IsLoad");
862 if (isAnyExtLoad())
863 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
864 "IsAnyExtLoad requires IsLoad");
865 if (isSignExtLoad())
866 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
867 "IsSignExtLoad requires IsLoad");
868 if (isZeroExtLoad())
869 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
870 "IsZeroExtLoad requires IsLoad");
871 }
872
873 if (isStore()) {
874 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
875 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
876 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
877 "IsStore cannot be used by itself");
878 } else {
879 if (isNonTruncStore())
880 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
881 "IsNonTruncStore requires IsStore");
882 if (isTruncStore())
883 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
884 "IsTruncStore requires IsStore");
885 }
886
Daniel Sanders87d196c2017-11-13 22:26:13 +0000887 if (isAtomic()) {
888 if (getMemoryVT() == nullptr)
889 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
890 "IsAtomic cannot be used by itself");
891 }
892 if (isLoad() || isStore() || isAtomic()) {
893 StringRef SDNodeName =
894 isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
895
896 Record *MemoryVT = getMemoryVT();
897
898 if (MemoryVT)
899 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
900 MemoryVT->getName() + ") return false;\n")
901 .str();
902 }
903
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000904 if (isLoad() || isStore()) {
905 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
906
907 if (isUnindexed())
908 Code += ("if (cast<" + SDNodeName +
909 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
910 "return false;\n")
911 .str();
912
913 if (isLoad()) {
914 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
915 isZeroExtLoad()) > 1)
916 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
917 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
918 "IsZeroExtLoad are mutually exclusive");
919 if (isNonExtLoad())
920 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
921 "ISD::NON_EXTLOAD) return false;\n";
922 if (isAnyExtLoad())
923 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
924 "return false;\n";
925 if (isSignExtLoad())
926 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
927 "return false;\n";
928 if (isZeroExtLoad())
929 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
930 "return false;\n";
931 } else {
932 if ((isNonTruncStore() + isTruncStore()) > 1)
933 PrintFatalError(
934 getOrigPatFragRecord()->getRecord()->getLoc(),
935 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
936 if (isNonTruncStore())
937 Code +=
938 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
939 if (isTruncStore())
940 Code +=
941 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
942 }
943
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000944 Record *ScalarMemoryVT = getScalarMemoryVT();
945
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000946 if (ScalarMemoryVT)
947 Code += ("if (cast<" + SDNodeName +
948 ">(N)->getMemoryVT().getScalarType() != MVT::" +
949 ScalarMemoryVT->getName() + ") return false;\n")
950 .str();
951 }
952
953 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
954
955 Code += PredicateCode;
956
957 if (PredicateCode.empty() && !Code.empty())
958 Code += "return true;\n";
959
960 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +0000961}
962
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000963bool TreePredicateFn::hasImmCode() const {
964 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
965}
966
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000967std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000968 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000969}
970
Daniel Sanders649c5852017-10-13 20:42:18 +0000971bool TreePredicateFn::immCodeUsesAPInt() const {
972 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
973}
974
975bool TreePredicateFn::immCodeUsesAPFloat() const {
976 bool Unset;
977 // The return value will be false when IsAPFloat is unset.
978 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
979 Unset);
980}
981
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000982bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
983 bool Value) const {
984 bool Unset;
985 bool Result =
986 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
987 if (Unset)
988 return false;
989 return Result == Value;
990}
991bool TreePredicateFn::isLoad() const {
992 return isPredefinedPredicateEqualTo("IsLoad", true);
993}
994bool TreePredicateFn::isStore() const {
995 return isPredefinedPredicateEqualTo("IsStore", true);
996}
Daniel Sanders87d196c2017-11-13 22:26:13 +0000997bool TreePredicateFn::isAtomic() const {
998 return isPredefinedPredicateEqualTo("IsAtomic", true);
999}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001000bool TreePredicateFn::isUnindexed() const {
1001 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1002}
1003bool TreePredicateFn::isNonExtLoad() const {
1004 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1005}
1006bool TreePredicateFn::isAnyExtLoad() const {
1007 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1008}
1009bool TreePredicateFn::isSignExtLoad() const {
1010 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1011}
1012bool TreePredicateFn::isZeroExtLoad() const {
1013 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1014}
1015bool TreePredicateFn::isNonTruncStore() const {
1016 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1017}
1018bool TreePredicateFn::isTruncStore() const {
1019 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1020}
1021Record *TreePredicateFn::getMemoryVT() const {
1022 Record *R = getOrigPatFragRecord()->getRecord();
1023 if (R->isValueUnset("MemoryVT"))
1024 return nullptr;
1025 return R->getValueAsDef("MemoryVT");
1026}
1027Record *TreePredicateFn::getScalarMemoryVT() const {
1028 Record *R = getOrigPatFragRecord()->getRecord();
1029 if (R->isValueUnset("ScalarMemoryVT"))
1030 return nullptr;
1031 return R->getValueAsDef("ScalarMemoryVT");
1032}
1033
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001034StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001035 if (immCodeUsesAPInt())
1036 return "const APInt &";
1037 if (immCodeUsesAPFloat())
1038 return "const APFloat &";
1039 return "int64_t";
1040}
Chris Lattner514e2922011-04-17 21:38:24 +00001041
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001042StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001043 if (immCodeUsesAPInt())
1044 return "APInt";
1045 else if (immCodeUsesAPFloat())
1046 return "APFloat";
1047 return "I64";
1048}
1049
Chris Lattner514e2922011-04-17 21:38:24 +00001050/// isAlwaysTrue - Return true if this is a noop predicate.
1051bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001052 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001053}
1054
1055/// Return the name to use in the generated code to reference this, this is
1056/// "Predicate_foo" if from a pattern fragment "foo".
1057std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001058 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001059}
1060
1061/// getCodeToRunOnSDNode - Return the code for the function body that
1062/// evaluates this predicate. The argument is expected to be in "Node",
1063/// not N. This handles casting and conversion to a concrete node type as
1064/// appropriate.
1065std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001066 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001067 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001068 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001069 if (isLoad())
1070 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1071 "IsLoad cannot be used with ImmLeaf or its subclasses");
1072 if (isStore())
1073 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1074 "IsStore cannot be used with ImmLeaf or its subclasses");
1075 if (isUnindexed())
1076 PrintFatalError(
1077 getOrigPatFragRecord()->getRecord()->getLoc(),
1078 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1079 if (isNonExtLoad())
1080 PrintFatalError(
1081 getOrigPatFragRecord()->getRecord()->getLoc(),
1082 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1083 if (isAnyExtLoad())
1084 PrintFatalError(
1085 getOrigPatFragRecord()->getRecord()->getLoc(),
1086 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1087 if (isSignExtLoad())
1088 PrintFatalError(
1089 getOrigPatFragRecord()->getRecord()->getLoc(),
1090 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1091 if (isZeroExtLoad())
1092 PrintFatalError(
1093 getOrigPatFragRecord()->getRecord()->getLoc(),
1094 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1095 if (isNonTruncStore())
1096 PrintFatalError(
1097 getOrigPatFragRecord()->getRecord()->getLoc(),
1098 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1099 if (isTruncStore())
1100 PrintFatalError(
1101 getOrigPatFragRecord()->getRecord()->getLoc(),
1102 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1103 if (getMemoryVT())
1104 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1105 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1106 if (getScalarMemoryVT())
1107 PrintFatalError(
1108 getOrigPatFragRecord()->getRecord()->getLoc(),
1109 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1110
1111 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001112 if (immCodeUsesAPFloat())
1113 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1114 else if (immCodeUsesAPInt())
1115 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1116 else
1117 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001118 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001119 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001120
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001121 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001122 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001123 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +00001124 if (PatFragRec->getOnlyTree()->isLeaf())
1125 ClassName = "SDNode";
1126 else {
1127 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1128 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1129 }
1130 std::string Result;
1131 if (ClassName == "SDNode")
1132 Result = " SDNode *N = Node;\n";
1133 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001134 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001135
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001136 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +00001137}
1138
Chris Lattner8cab0212008-01-05 22:25:12 +00001139//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001140// PatternToMatch implementation
1141//
1142
Chris Lattner05925fe2010-03-29 01:40:38 +00001143/// getPatternSize - Return the 'size' of this pattern. We want to match large
1144/// patterns before small ones. This is used to determine the size of a
1145/// pattern.
1146static unsigned getPatternSize(const TreePatternNode *P,
1147 const CodeGenDAGPatterns &CGP) {
1148 unsigned Size = 3; // The node itself.
1149 // If the root node is a ConstantSDNode, increases its size.
1150 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +00001151 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001152 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001153
Simon Pilgrim40687012017-09-26 12:59:01 +00001154 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001155 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001156 // We don't want to count any children twice, so return early.
1157 return Size;
1158 }
1159
Chris Lattner05925fe2010-03-29 01:40:38 +00001160 // If this node has some predicate function that must match, it adds to the
1161 // complexity of this node.
1162 if (!P->getPredicateFns().empty())
1163 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001164
Chris Lattner05925fe2010-03-29 01:40:38 +00001165 // Count children in the count if they are also nodes.
1166 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
Simon Pilgrima932bfc2017-09-27 10:03:17 +00001167 const TreePatternNode *Child = P->getChild(i);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001168 if (!Child->isLeaf() && Child->getNumTypes()) {
1169 const TypeSetByHwMode &T0 = Child->getType(0);
1170 // At this point, all variable type sets should be simple, i.e. only
1171 // have a default mode.
1172 if (T0.getMachineValueType() != MVT::Other) {
1173 Size += getPatternSize(Child, CGP);
1174 continue;
1175 }
1176 }
1177 if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001178 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001179 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1180 else if (Child->getComplexPatternInfo(CGP))
1181 Size += getPatternSize(Child, CGP);
1182 else if (!Child->getPredicateFns().empty())
1183 ++Size;
1184 }
1185 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001186
Chris Lattner05925fe2010-03-29 01:40:38 +00001187 return Size;
1188}
1189
1190/// Compute the complexity metric for the input pattern. This roughly
1191/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001192int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001193getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1194 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1195}
1196
Dan Gohman49e19e92008-08-22 00:20:26 +00001197/// getPredicateCheck - Return a single string containing all of this
1198/// pattern's predicates concatenated with "&&" operators.
1199///
1200std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001201 SmallVector<const Predicate*,4> PredList;
1202 for (const Predicate &P : Predicates)
1203 PredList.push_back(&P);
1204 std::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +00001205
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001206 std::string Check;
1207 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1208 if (i != 0)
1209 Check += " && ";
1210 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001211 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001212 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001213}
1214
1215//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001216// SDTypeConstraint implementation
1217//
1218
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001219SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001220 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001221
Chris Lattner8cab0212008-01-05 22:25:12 +00001222 if (R->isSubClassOf("SDTCisVT")) {
1223 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001224 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1225 for (const auto &P : VVT)
1226 if (P.second == MVT::isVoid)
1227 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001228 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1229 ConstraintType = SDTCisPtrTy;
1230 } else if (R->isSubClassOf("SDTCisInt")) {
1231 ConstraintType = SDTCisInt;
1232 } else if (R->isSubClassOf("SDTCisFP")) {
1233 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001234 } else if (R->isSubClassOf("SDTCisVec")) {
1235 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001236 } else if (R->isSubClassOf("SDTCisSameAs")) {
1237 ConstraintType = SDTCisSameAs;
1238 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1239 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1240 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001241 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001242 R->getValueAsInt("OtherOperandNum");
1243 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1244 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001245 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001246 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001247 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1248 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001249 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001250 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1251 ConstraintType = SDTCisSubVecOfVec;
1252 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1253 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001254 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1255 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001256 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1257 for (const auto &P : VVT) {
1258 MVT T = P.second;
1259 if (T.isVector())
1260 PrintFatalError(R->getLoc(),
1261 "Cannot use vector type as SDTCVecEltisVT");
1262 if (!T.isInteger() && !T.isFloatingPoint())
1263 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1264 "as SDTCVecEltisVT");
1265 }
Craig Topper0be34582015-03-05 07:11:34 +00001266 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1267 ConstraintType = SDTCisSameNumEltsAs;
1268 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1269 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001270 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1271 ConstraintType = SDTCisSameSizeAs;
1272 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1273 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001274 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001275 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001276 }
1277}
1278
1279/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001280/// N, and the result number in ResNo.
1281static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1282 const SDNodeInfo &NodeInfo,
1283 unsigned &ResNo) {
1284 unsigned NumResults = NodeInfo.getNumResults();
1285 if (OpNo < NumResults) {
1286 ResNo = OpNo;
1287 return N;
1288 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001289
Chris Lattner2db7aba2010-03-19 21:56:21 +00001290 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001291
Chris Lattner2db7aba2010-03-19 21:56:21 +00001292 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001293 std::string S;
1294 raw_string_ostream OS(S);
1295 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001296 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +00001297 N->print(OS);
1298 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001299 }
1300
Chris Lattner2db7aba2010-03-19 21:56:21 +00001301 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001302}
1303
1304/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1305/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001306/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001307bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1308 const SDNodeInfo &NodeInfo,
1309 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001310 if (TP.hasError())
1311 return false;
1312
Chris Lattner2db7aba2010-03-19 21:56:21 +00001313 unsigned ResNo = 0; // The result number being referenced.
1314 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001315 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001316
Chris Lattner8cab0212008-01-05 22:25:12 +00001317 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001318 case SDTCisVT:
1319 // Operand must be a particular type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001320 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001321 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001322 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001323 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001324 case SDTCisInt:
1325 // Require it to be one of the legal integer VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001326 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001327 case SDTCisFP:
1328 // Require it to be one of the legal fp VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001329 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001330 case SDTCisVec:
1331 // Require it to be one of the legal vector VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001332 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001333 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001334 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001335 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001336 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001337 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1338 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001339 }
1340 case SDTCisVTSmallerThanOp: {
1341 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1342 // have an integer type that is smaller than the VT.
1343 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001344 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001345 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001346 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001347 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001348 return false;
1349 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001350 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1351 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1352 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1353 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001354
Chris Lattner2db7aba2010-03-19 21:56:21 +00001355 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001356 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001357 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1358 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001359
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001360 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001361 }
1362 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001363 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001364 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001365 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1366 BResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001367 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1368 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001369 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001370 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001371 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001372 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001373 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1374 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001375 // Filter vector types out of VecOperand that don't have the right element
1376 // type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001377 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1378 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001379 }
David Greene127fd1d2011-01-24 20:53:18 +00001380 case SDTCisSubVecOfVec: {
1381 unsigned VResNo = 0;
1382 TreePatternNode *BigVecOperand =
1383 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1384 VResNo);
1385
1386 // Filter vector types out of BigVecOperand that don't have the
1387 // right subvector type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001388 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1389 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001390 }
Craig Topper0be34582015-03-05 07:11:34 +00001391 case SDTCVecEltisVT: {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001392 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001393 }
1394 case SDTCisSameNumEltsAs: {
1395 unsigned OResNo = 0;
1396 TreePatternNode *OtherNode =
1397 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1398 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001399 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1400 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001401 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001402 case SDTCisSameSizeAs: {
1403 unsigned OResNo = 0;
1404 TreePatternNode *OtherNode =
1405 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1406 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001407 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1408 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001409 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001410 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001411 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001412}
1413
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001414// Update the node type to match an instruction operand or result as specified
1415// in the ins or outs lists on the instruction definition. Return true if the
1416// type was actually changed.
1417bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1418 Record *Operand,
1419 TreePattern &TP) {
1420 // The 'unknown' operand indicates that types should be inferred from the
1421 // context.
1422 if (Operand->isSubClassOf("unknown_class"))
1423 return false;
1424
1425 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001426 if (Operand->isSubClassOf("Operand")) {
1427 Record *R = Operand->getValueAsDef("Type");
1428 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1429 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1430 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001431
1432 // PointerLikeRegClass has a type that is determined at runtime.
1433 if (Operand->isSubClassOf("PointerLikeRegClass"))
1434 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1435
1436 // Both RegisterClass and RegisterOperand operands derive their types from a
1437 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001438 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001439 if (Operand->isSubClassOf("RegisterClass"))
1440 RC = Operand;
1441 else if (Operand->isSubClassOf("RegisterOperand"))
1442 RC = Operand->getValueAsDef("RegClass");
1443
1444 assert(RC && "Unknown operand type");
1445 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1446 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1447}
1448
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001449bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1450 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1451 if (!TP.getInfer().isConcrete(Types[i], true))
1452 return true;
1453 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1454 if (getChild(i)->ContainsUnresolvedType(TP))
1455 return true;
1456 return false;
1457}
1458
1459bool TreePatternNode::hasProperTypeByHwMode() const {
1460 for (const TypeSetByHwMode &S : Types)
1461 if (!S.isDefaultOnly())
1462 return true;
1463 for (TreePatternNode *C : Children)
1464 if (C->hasProperTypeByHwMode())
1465 return true;
1466 return false;
1467}
1468
1469bool TreePatternNode::hasPossibleType() const {
1470 for (const TypeSetByHwMode &S : Types)
1471 if (!S.isPossible())
1472 return false;
1473 for (TreePatternNode *C : Children)
1474 if (!C->hasPossibleType())
1475 return false;
1476 return true;
1477}
1478
1479bool TreePatternNode::setDefaultMode(unsigned Mode) {
1480 for (TypeSetByHwMode &S : Types) {
1481 S.makeSimple(Mode);
1482 // Check if the selected mode had a type conflict.
1483 if (S.get(DefaultMode).empty())
1484 return false;
1485 }
1486 for (TreePatternNode *C : Children)
1487 if (!C->setDefaultMode(Mode))
1488 return false;
1489 return true;
1490}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001491
Chris Lattner8cab0212008-01-05 22:25:12 +00001492//===----------------------------------------------------------------------===//
1493// SDNodeInfo implementation
1494//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001495SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001496 EnumName = R->getValueAsString("Opcode");
1497 SDClassName = R->getValueAsString("SDClass");
1498 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1499 NumResults = TypeProfile->getValueAsInt("NumResults");
1500 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001501
Chris Lattner8cab0212008-01-05 22:25:12 +00001502 // Parse the properties.
1503 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001504 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1505 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001506 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001507 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001508 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001509 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001510 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001511 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001512 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001513 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001514 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001515 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001516 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001517 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001518 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001519 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001520 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001521 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001522 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001523 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001524 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001525 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001526 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001527 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001528 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001529 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001530 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001531 }
1532 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001533
1534
Chris Lattner8cab0212008-01-05 22:25:12 +00001535 // Parse the type constraints.
1536 std::vector<Record*> ConstraintList =
1537 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001538 for (Record *R : ConstraintList)
1539 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001540}
1541
Chris Lattner99e53b32010-02-28 00:22:30 +00001542/// getKnownType - If the type constraints on this node imply a fixed type
1543/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001544/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001545MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001546 unsigned NumResults = getNumResults();
1547 assert(NumResults <= 1 &&
1548 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001549 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001550
Craig Topper306cb122015-11-22 20:46:24 +00001551 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001552 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001553 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001554 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001555
Craig Topper306cb122015-11-22 20:46:24 +00001556 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001557 default: break;
1558 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001559 if (Constraint.VVT.isSimple())
1560 return Constraint.VVT.getSimple().SimpleTy;
1561 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001562 case SDTypeConstraint::SDTCisPtrTy:
1563 return MVT::iPTR;
1564 }
1565 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001566 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001567}
1568
Chris Lattner8cab0212008-01-05 22:25:12 +00001569//===----------------------------------------------------------------------===//
1570// TreePatternNode implementation
1571//
1572
1573TreePatternNode::~TreePatternNode() {
1574#if 0 // FIXME: implement refcounted tree nodes!
1575 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1576 delete getChild(i);
1577#endif
1578}
1579
Chris Lattnerf1447252010-03-19 21:37:09 +00001580static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1581 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001582 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001583 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001584
Chris Lattner2109cb42010-03-22 20:56:36 +00001585 if (Operator->isSubClassOf("Intrinsic"))
1586 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001587
Chris Lattnerf1447252010-03-19 21:37:09 +00001588 if (Operator->isSubClassOf("SDNode"))
1589 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001590
Chris Lattnerf1447252010-03-19 21:37:09 +00001591 if (Operator->isSubClassOf("PatFrag")) {
1592 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1593 // the forward reference case where one pattern fragment references another
1594 // before it is processed.
1595 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1596 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001597
Chris Lattnerf1447252010-03-19 21:37:09 +00001598 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001599 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001600 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001601 if (Tree)
1602 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1603 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001604 assert(Op && "Invalid Fragment");
1605 return GetNumNodeResults(Op, CDP);
1606 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001607
Chris Lattnerf1447252010-03-19 21:37:09 +00001608 if (Operator->isSubClassOf("Instruction")) {
1609 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001610
Craig Topper3a8eb892015-03-20 05:09:06 +00001611 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1612
1613 // Subtract any defaulted outputs.
1614 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1615 Record *OperandNode = InstInfo.Operands[i].Rec;
1616
1617 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1618 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1619 --NumDefsToAdd;
1620 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001621
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001622 // Add on one implicit def if it has a resolvable type.
1623 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1624 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001625 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001626 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001627
Chris Lattnerf1447252010-03-19 21:37:09 +00001628 if (Operator->isSubClassOf("SDNodeXForm"))
1629 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001630
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001631 if (Operator->isSubClassOf("ValueType"))
1632 return 1; // A type-cast of one result.
1633
Tim Northoverc807a172014-05-20 11:52:46 +00001634 if (Operator->isSubClassOf("ComplexPattern"))
1635 return 1;
1636
Matthias Braun8c209aa2017-01-28 02:02:38 +00001637 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001638 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001639}
1640
1641void TreePatternNode::print(raw_ostream &OS) const {
1642 if (isLeaf())
1643 OS << *getLeafValue();
1644 else
1645 OS << '(' << getOperator()->getName();
1646
Zachary Turner249dc142017-09-20 18:01:40 +00001647 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1648 OS << ':';
1649 getExtType(i).writeToStream(OS);
1650 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001651
1652 if (!isLeaf()) {
1653 if (getNumChildren() != 0) {
1654 OS << " ";
1655 getChild(0)->print(OS);
1656 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1657 OS << ", ";
1658 getChild(i)->print(OS);
1659 }
1660 }
1661 OS << ")";
1662 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001663
Craig Topper306cb122015-11-22 20:46:24 +00001664 for (const TreePredicateFn &Pred : PredicateFns)
1665 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001666 if (TransformFn)
1667 OS << "<<X:" << TransformFn->getName() << ">>";
1668 if (!getName().empty())
1669 OS << ":$" << getName();
1670
1671}
1672void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001673 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001674}
1675
Scott Michel94420742008-03-05 17:49:05 +00001676/// isIsomorphicTo - Return true if this node is recursively
1677/// isomorphic to the specified node. For this comparison, the node's
1678/// entire state is considered. The assigned name is ignored, since
1679/// nodes with differing names are considered isomorphic. However, if
1680/// the assigned name is present in the dependent variable set, then
1681/// the assigned name is considered significant and the node is
1682/// isomorphic if the names match.
1683bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1684 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001685 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001686 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001687 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001688 getTransformFn() != N->getTransformFn())
1689 return false;
1690
1691 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001692 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1693 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001694 return ((DI->getDef() == NDI->getDef())
1695 && (DepVars.find(getName()) == DepVars.end()
1696 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001697 }
1698 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001699 return getLeafValue() == N->getLeafValue();
1700 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001701
Chris Lattner8cab0212008-01-05 22:25:12 +00001702 if (N->getOperator() != getOperator() ||
1703 N->getNumChildren() != getNumChildren()) return false;
1704 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001705 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001706 return false;
1707 return true;
1708}
1709
1710/// clone - Make a copy of this tree and all of its children.
1711///
1712TreePatternNode *TreePatternNode::clone() const {
1713 TreePatternNode *New;
1714 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001715 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001716 } else {
1717 std::vector<TreePatternNode*> CChildren;
1718 CChildren.reserve(Children.size());
1719 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1720 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001721 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001722 }
1723 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001724 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001725 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001726 New->setTransformFn(getTransformFn());
1727 return New;
1728}
1729
Chris Lattner53c39ba2010-02-14 22:22:58 +00001730/// RemoveAllTypes - Recursively strip all the types of this tree.
1731void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001732 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001733 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001734 if (isLeaf()) return;
1735 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1736 getChild(i)->RemoveAllTypes();
1737}
1738
1739
Chris Lattner8cab0212008-01-05 22:25:12 +00001740/// SubstituteFormalArguments - Replace the formal arguments in this tree
1741/// with actual values specified by ArgMap.
1742void TreePatternNode::
1743SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1744 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001745
Chris Lattner8cab0212008-01-05 22:25:12 +00001746 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1747 TreePatternNode *Child = getChild(i);
1748 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001749 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001750 // Note that, when substituting into an output pattern, Val might be an
1751 // UnsetInit.
1752 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1753 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001754 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001755 TreePatternNode *NewChild = ArgMap[Child->getName()];
1756 assert(NewChild && "Couldn't find formal argument!");
1757 assert((Child->getPredicateFns().empty() ||
1758 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1759 "Non-empty child predicate clobbered!");
1760 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001761 }
1762 } else {
1763 getChild(i)->SubstituteFormalArguments(ArgMap);
1764 }
1765 }
1766}
1767
1768
1769/// InlinePatternFragments - If this pattern refers to any pattern
1770/// fragments, inline them into place, giving us a pattern without any
1771/// PatFrag references.
1772TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001773 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001774 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001775
1776 if (isLeaf())
1777 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001778 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001779
Chris Lattner8cab0212008-01-05 22:25:12 +00001780 if (!Op->isSubClassOf("PatFrag")) {
1781 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001782 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1783 TreePatternNode *Child = getChild(i);
1784 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1785
1786 assert((Child->getPredicateFns().empty() ||
1787 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1788 "Non-empty child predicate clobbered!");
1789
1790 setChild(i, NewChild);
1791 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001792 return this;
1793 }
1794
1795 // Otherwise, we found a reference to a fragment. First, look up its
1796 // TreePattern record.
1797 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001798
Chris Lattner8cab0212008-01-05 22:25:12 +00001799 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001800 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001801 TP.error("'" + Op->getName() + "' fragment requires " +
1802 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001803 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001804 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001805
1806 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1807
Chris Lattner514e2922011-04-17 21:38:24 +00001808 TreePredicateFn PredFn(Frag);
1809 if (!PredFn.isAlwaysTrue())
1810 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001811
Chris Lattner8cab0212008-01-05 22:25:12 +00001812 // Resolve formal arguments to their actual value.
1813 if (Frag->getNumArgs()) {
1814 // Compute the map of formal to actual arguments.
1815 std::map<std::string, TreePatternNode*> ArgMap;
1816 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1817 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001818
Chris Lattner8cab0212008-01-05 22:25:12 +00001819 FragTree->SubstituteFormalArguments(ArgMap);
1820 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001821
Chris Lattner8cab0212008-01-05 22:25:12 +00001822 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001823 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1824 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001825
1826 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001827 for (const TreePredicateFn &Pred : getPredicateFns())
1828 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001829
Chris Lattner8cab0212008-01-05 22:25:12 +00001830 // Get a new copy of this fragment to stitch into here.
1831 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001832
Chris Lattner2e253b42008-06-30 03:02:03 +00001833 // The fragment we inlined could have recursive inlining that is needed. See
1834 // if there are any pattern fragments in it and inline them as needed.
1835 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001836}
1837
1838/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001839/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001840/// references from the register file information, for example.
1841///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001842/// When Unnamed is set, return the type of a DAG operand with no name, such as
1843/// the F8RC register class argument in:
1844///
1845/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1846///
1847/// When Unnamed is false, return the type of a named DAG operand such as the
1848/// GPR:$src operand above.
1849///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001850static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1851 bool NotRegisters,
1852 bool Unnamed,
1853 TreePattern &TP) {
1854 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1855
Owen Andersona84be6c2011-06-27 21:06:21 +00001856 // Check to see if this is a register operand.
1857 if (R->isSubClassOf("RegisterOperand")) {
1858 assert(ResNo == 0 && "Regoperand ref only has one result!");
1859 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001860 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00001861 Record *RegClass = R->getValueAsDef("RegClass");
1862 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001863 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00001864 }
1865
Chris Lattnercabe0372010-03-15 06:00:16 +00001866 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001867 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001868 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001869 // An unnamed register class represents itself as an i32 immediate, for
1870 // example on a COPY_TO_REGCLASS instruction.
1871 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001872 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001873
1874 // In a named operand, the register class provides the possible set of
1875 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001876 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001877 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00001878 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001879 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001880 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001881
Chris Lattner6070ee22010-03-23 23:50:31 +00001882 if (R->isSubClassOf("PatFrag")) {
1883 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001884 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001885 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001886 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001887
Chris Lattner6070ee22010-03-23 23:50:31 +00001888 if (R->isSubClassOf("Register")) {
1889 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001890 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001891 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001892 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001893 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001894 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001895
1896 if (R->isSubClassOf("SubRegIndex")) {
1897 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001898 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001899 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001900
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001901 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001902 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001903 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1904 //
1905 // (sext_inreg GPR:$src, i16)
1906 // ~~~
1907 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001908 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001909 // With a name, the ValueType simply provides the type of the named
1910 // variable.
1911 //
1912 // (sext_inreg i32:$src, i16)
1913 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001914 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001915 return TypeSetByHwMode(); // Unknown.
1916 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1917 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001918 }
1919
1920 if (R->isSubClassOf("CondCode")) {
1921 assert(ResNo == 0 && "This node only has one result!");
1922 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001923 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00001924 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001925
Chris Lattner6070ee22010-03-23 23:50:31 +00001926 if (R->isSubClassOf("ComplexPattern")) {
1927 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001928 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001929 return TypeSetByHwMode(); // Unknown.
1930 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00001931 }
1932 if (R->isSubClassOf("PointerLikeRegClass")) {
1933 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001934 TypeSetByHwMode VTS(MVT::iPTR);
1935 TP.getInfer().expandOverloads(VTS);
1936 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00001937 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001938
Chris Lattner6070ee22010-03-23 23:50:31 +00001939 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1940 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001941 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001942 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001943 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001944
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001945 if (R->isSubClassOf("Operand")) {
1946 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1947 Record *T = R->getValueAsDef("Type");
1948 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
1949 }
Tim Northoverc807a172014-05-20 11:52:46 +00001950
Chris Lattner8cab0212008-01-05 22:25:12 +00001951 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001952 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00001953}
1954
Chris Lattner89c65662008-01-06 05:36:50 +00001955
1956/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1957/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1958const CodeGenIntrinsic *TreePatternNode::
1959getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1960 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1961 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1962 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001963 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001964
Sean Silva88eb8dd2012-10-10 20:24:47 +00001965 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001966 return &CDP.getIntrinsicInfo(IID);
1967}
1968
Chris Lattner53c39ba2010-02-14 22:22:58 +00001969/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1970/// return the ComplexPattern information, otherwise return null.
1971const ComplexPattern *
1972TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001973 Record *Rec;
1974 if (isLeaf()) {
1975 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1976 if (!DI)
1977 return nullptr;
1978 Rec = DI->getDef();
1979 } else
1980 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001981
Tim Northoverc807a172014-05-20 11:52:46 +00001982 if (!Rec->isSubClassOf("ComplexPattern"))
1983 return nullptr;
1984 return &CGP.getComplexPattern(Rec);
1985}
1986
1987unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1988 // A ComplexPattern specifically declares how many results it fills in.
1989 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1990 return CP->getNumOperands();
1991
1992 // If MIOperandInfo is specified, that gives the count.
1993 if (isLeaf()) {
1994 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1995 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1996 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1997 if (MIOps->getNumArgs())
1998 return MIOps->getNumArgs();
1999 }
2000 }
2001
2002 // Otherwise there is just one result.
2003 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00002004}
2005
2006/// NodeHasProperty - Return true if this node has the specified property.
2007bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002008 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002009 if (isLeaf()) {
2010 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2011 return CP->hasProperty(Property);
2012 return false;
2013 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002014
Chris Lattner53c39ba2010-02-14 22:22:58 +00002015 Record *Operator = getOperator();
2016 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002017
Chris Lattner53c39ba2010-02-14 22:22:58 +00002018 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2019}
2020
2021
2022
2023
2024/// TreeHasProperty - Return true if any node in this tree has the specified
2025/// property.
2026bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002027 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002028 if (NodeHasProperty(Property, CGP))
2029 return true;
2030 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2031 if (getChild(i)->TreeHasProperty(Property, CGP))
2032 return true;
2033 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002034}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002035
Evan Cheng49bad4c2008-06-16 20:29:38 +00002036/// isCommutativeIntrinsic - Return true if the node corresponds to a
2037/// commutative intrinsic.
2038bool
2039TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2040 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2041 return Int->isCommutative;
2042 return false;
2043}
2044
Matt Arsenaulteb492162014-11-02 23:46:51 +00002045static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2046 if (!N->isLeaf())
2047 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002048
Matt Arsenaulteb492162014-11-02 23:46:51 +00002049 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
2050 if (DI && DI->getDef()->isSubClassOf(Class))
2051 return true;
2052
2053 return false;
2054}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002055
2056static void emitTooManyOperandsError(TreePattern &TP,
2057 StringRef InstName,
2058 unsigned Expected,
2059 unsigned Actual) {
2060 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2061 " operands but expected only " + Twine(Expected) + "!");
2062}
2063
2064static void emitTooFewOperandsError(TreePattern &TP,
2065 StringRef InstName,
2066 unsigned Actual) {
2067 TP.error("Instruction '" + InstName +
2068 "' expects more than the provided " + Twine(Actual) + " operands!");
2069}
2070
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002071/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002072/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002073/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002074bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002075 if (TP.hasError())
2076 return false;
2077
Chris Lattnerab3242f2008-01-06 01:10:31 +00002078 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002079 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002080 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002081 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002082 bool MadeChange = false;
2083 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2084 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002085 NotRegisters,
2086 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002087 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002088 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002089
Sean Silvafb509ed2012-10-10 20:24:43 +00002090 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002091 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002092
Chris Lattnerf1447252010-03-19 21:37:09 +00002093 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002094 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002095
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002096 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002097 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002098
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002099 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2100 for (auto &P : VVT) {
2101 MVT::SimpleValueType VT = P.second.SimpleTy;
2102 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2103 continue;
2104 unsigned Size = MVT(VT).getSizeInBits();
2105 // Make sure that the value is representable for this type.
2106 if (Size >= 32)
2107 continue;
2108 // Check that the value doesn't use more bits than we have. It must
2109 // either be a sign- or zero-extended equivalent of the original.
2110 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2111 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2112 SignBitAndAbove == 1)
2113 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002114
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002115 TP.error("Integer value '" + itostr(II->getValue()) +
2116 "' is out of range for type '" + getEnumName(VT) + "'!");
2117 break;
2118 }
2119 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002120 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002121
Chris Lattner8cab0212008-01-05 22:25:12 +00002122 return false;
2123 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002124
Chris Lattner8cab0212008-01-05 22:25:12 +00002125 // special handling for set, which isn't really an SDNode.
2126 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002127 assert(getNumTypes() == 0 && "Set doesn't produce a value");
2128 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002129 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002130
Chris Lattnerf1447252010-03-19 21:37:09 +00002131 TreePatternNode *SetVal = getChild(NC-1);
2132 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
2133
Elena Demikhovsky09954792015-03-01 08:23:41 +00002134 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002135 TreePatternNode *Child = getChild(i);
2136 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002137
Chris Lattner8cab0212008-01-05 22:25:12 +00002138 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00002139 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
2140 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002141 }
2142 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002143 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002144
Chris Lattner5c2182e2010-03-27 02:53:27 +00002145 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002146 assert(getNumTypes() == 0 && "Node doesn't produce a value");
2147
Chris Lattner8cab0212008-01-05 22:25:12 +00002148 bool MadeChange = false;
2149 for (unsigned i = 0; i < getNumChildren(); ++i)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002150 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002151 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002152 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002153
Chris Lattneree820ac2010-02-23 05:51:07 +00002154 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002155 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002156
Chris Lattner8cab0212008-01-05 22:25:12 +00002157 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002158 unsigned NumRetVTs = Int->IS.RetVTs.size();
2159 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002160
Bill Wendling91821472008-11-13 09:08:33 +00002161 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002162 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002163
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002164 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00002165 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00002166 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00002167 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002168 return false;
2169 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002170
2171 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00002172 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002173
Chris Lattnerf1447252010-03-19 21:37:09 +00002174 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
2175 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002176
Chris Lattnerf1447252010-03-19 21:37:09 +00002177 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
2178 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2179 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002180 }
2181 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002182 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002183
Chris Lattneree820ac2010-02-23 05:51:07 +00002184 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002185 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002186
Chris Lattner135091b2010-03-28 08:48:47 +00002187 // Check that the number of operands is sane. Negative operands -> varargs.
2188 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002189 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002190 TP.error(getOperator()->getName() + " node requires exactly " +
2191 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002192 return false;
2193 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002194
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002195 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002196 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2197 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002198 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002199 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002200 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002201
Chris Lattneree820ac2010-02-23 05:51:07 +00002202 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002203 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002204 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002205 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002206
Chris Lattnerd44966f2010-03-27 19:15:02 +00002207 bool MadeChange = false;
2208
2209 // Apply the result types to the node, these come from the things in the
2210 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002211 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2212 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002213 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2214 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002215
Chris Lattnerd44966f2010-03-27 19:15:02 +00002216 // If the instruction has implicit defs, we apply the first one as a result.
2217 // FIXME: This sucks, it should apply all implicit defs.
2218 if (!InstInfo.ImplicitDefs.empty()) {
2219 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002220
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002221 // FIXME: Generalize to multiple possible types and multiple possible
2222 // ImplicitDefs.
2223 MVT::SimpleValueType VT =
2224 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002225
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002226 if (VT != MVT::Other)
2227 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002228 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002229
Chris Lattnercabe0372010-03-15 06:00:16 +00002230 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2231 // be the same.
2232 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002233 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2234 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2235 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002236 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2237 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2238 // variadic.
2239
2240 unsigned NChild = getNumChildren();
2241 if (NChild < 3) {
2242 TP.error("REG_SEQUENCE requires at least 3 operands!");
2243 return false;
2244 }
2245
2246 if (NChild % 2 == 0) {
2247 TP.error("REG_SEQUENCE requires an odd number of operands!");
2248 return false;
2249 }
2250
2251 if (!isOperandClass(getChild(0), "RegisterClass")) {
2252 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2253 return false;
2254 }
2255
2256 for (unsigned I = 1; I < NChild; I += 2) {
2257 TreePatternNode *SubIdxChild = getChild(I + 1);
2258 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2259 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2260 itostr(I + 1) + "!");
2261 return false;
2262 }
2263 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002264 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002265
2266 unsigned ChildNo = 0;
2267 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2268 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002269
Chris Lattner8cab0212008-01-05 22:25:12 +00002270 // If the instruction expects a predicate or optional def operand, we
2271 // codegen this by setting the operand to it's default value if it has a
2272 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002273 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002274 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2275 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002276
Chris Lattner8cab0212008-01-05 22:25:12 +00002277 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002278 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002279 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002280 return false;
2281 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002282
Chris Lattner8cab0212008-01-05 22:25:12 +00002283 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002284 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002285
2286 // If the operand has sub-operands, they may be provided by distinct
2287 // child patterns, so attempt to match each sub-operand separately.
2288 if (OperandNode->isSubClassOf("Operand")) {
2289 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2290 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2291 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002292 // a single ComplexPattern-related Operand.
2293
2294 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002295 // Match first sub-operand against the child we already have.
2296 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2297 MadeChange |=
2298 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2299
2300 // And the remaining sub-operands against subsequent children.
2301 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2302 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002303 emitTooFewOperandsError(TP, getOperator()->getName(),
2304 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002305 return false;
2306 }
2307 Child = getChild(ChildNo++);
2308
2309 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2310 MadeChange |=
2311 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2312 }
2313 continue;
2314 }
2315 }
2316 }
2317
2318 // If we didn't match by pieces above, attempt to match the whole
2319 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002320 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002321 }
Christopher Lamba7312392008-03-11 09:33:47 +00002322
Matt Arsenaulteb492162014-11-02 23:46:51 +00002323 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002324 emitTooManyOperandsError(TP, getOperator()->getName(),
2325 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002326 return false;
2327 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002328
Ulrich Weigande618abd2013-03-19 19:51:09 +00002329 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2330 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002331 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002332 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002333
Tim Northoverc807a172014-05-20 11:52:46 +00002334 if (getOperator()->isSubClassOf("ComplexPattern")) {
2335 bool MadeChange = false;
2336
2337 for (unsigned i = 0; i < getNumChildren(); ++i)
2338 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2339
2340 return MadeChange;
2341 }
2342
Chris Lattneree820ac2010-02-23 05:51:07 +00002343 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002344
Chris Lattneree820ac2010-02-23 05:51:07 +00002345 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002346 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002347 TP.error("Node transform '" + getOperator()->getName() +
2348 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002349 return false;
2350 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002351
Chris Lattnercabe0372010-03-15 06:00:16 +00002352 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002353 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002354}
2355
2356/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2357/// RHS of a commutative operation, not the on LHS.
2358static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2359 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2360 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002361 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002362 return true;
2363 return false;
2364}
2365
2366
2367/// canPatternMatch - If it is impossible for this pattern to match on this
2368/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002369/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002370/// that can never possibly work), and to prevent the pattern permuter from
2371/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002372bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002373 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002374 if (isLeaf()) return true;
2375
2376 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2377 if (!getChild(i)->canPatternMatch(Reason, CDP))
2378 return false;
2379
2380 // If this is an intrinsic, handle cases that would make it not match. For
2381 // example, if an operand is required to be an immediate.
2382 if (getOperator()->isSubClassOf("Intrinsic")) {
2383 // TODO:
2384 return true;
2385 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002386
Tim Northoverc807a172014-05-20 11:52:46 +00002387 if (getOperator()->isSubClassOf("ComplexPattern"))
2388 return true;
2389
Chris Lattner8cab0212008-01-05 22:25:12 +00002390 // If this node is a commutative operator, check that the LHS isn't an
2391 // immediate.
2392 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002393 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2394 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002395 // Scan all of the operands of the node and make sure that only the last one
2396 // is a constant node, unless the RHS also is.
2397 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002398 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002399 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002400 if (OnlyOnRHSOfCommutative(getChild(i))) {
2401 Reason="Immediate value must be on the RHS of commutative operators!";
2402 return false;
2403 }
2404 }
2405 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002406
Chris Lattner8cab0212008-01-05 22:25:12 +00002407 return true;
2408}
2409
2410//===----------------------------------------------------------------------===//
2411// TreePattern implementation
2412//
2413
David Greeneaf8ee2c2011-07-29 22:43:06 +00002414TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002415 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002416 isInputPattern(isInput), HasError(false),
2417 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002418 for (Init *I : RawPat->getValues())
2419 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002420}
2421
David Greeneaf8ee2c2011-07-29 22:43:06 +00002422TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002423 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002424 isInputPattern(isInput), HasError(false),
2425 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002426 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002427}
2428
David Blaikiecf195302014-11-17 22:55:41 +00002429TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002430 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002431 isInputPattern(isInput), HasError(false),
2432 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002433 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002434}
2435
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002436void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002437 if (HasError)
2438 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002439 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002440 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2441 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002442}
2443
Chris Lattnercabe0372010-03-15 06:00:16 +00002444void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002445 for (TreePatternNode *Tree : Trees)
2446 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002447}
2448
2449void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2450 if (!N->getName().empty())
2451 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002452
Chris Lattnercabe0372010-03-15 06:00:16 +00002453 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2454 ComputeNamedNodes(N->getChild(i));
2455}
2456
David Blaikiecf195302014-11-17 22:55:41 +00002457
2458TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002459 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002460 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002461
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002462 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002463 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002464 /// (foo GPR, imm) -> (foo GPR, (imm))
2465 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002466 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002467 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002468 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002469 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002470
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002471 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002472 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002473 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002474 if (OpName.empty())
2475 error("'node' argument requires a name to match with operand list");
2476 Args.push_back(OpName);
2477 }
2478
2479 Res->setName(OpName);
2480 return Res;
2481 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002482
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002483 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002484 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002485 if (OpName.empty())
2486 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002487 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002488 Args.push_back(OpName);
2489 Res->setName(OpName);
2490 return Res;
2491 }
2492
Sean Silvafb509ed2012-10-10 20:24:43 +00002493 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002494 if (!OpName.empty())
2495 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002496 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002497 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002498
Sean Silvafb509ed2012-10-10 20:24:43 +00002499 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002500 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002501 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002502 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002503 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002504 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002505 }
2506
Sean Silvafb509ed2012-10-10 20:24:43 +00002507 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002508 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002509 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002510 error("Pattern has unexpected init kind!");
2511 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002512 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002513 if (!OpDef) error("Pattern has unexpected operator type!");
2514 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002515
Chris Lattner8cab0212008-01-05 22:25:12 +00002516 if (Operator->isSubClassOf("ValueType")) {
2517 // If the operator is a ValueType, then this must be "type cast" of a leaf
2518 // node.
2519 if (Dag->getNumArgs() != 1)
2520 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002521
Matthias Braunbb053162016-12-05 06:00:46 +00002522 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2523 Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002524
Chris Lattner8cab0212008-01-05 22:25:12 +00002525 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002526 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002527 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2528 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002529
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002530 if (!OpName.empty())
2531 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002532 return New;
2533 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002534
Chris Lattner8cab0212008-01-05 22:25:12 +00002535 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002536 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002537 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002538 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002539 !Operator->isSubClassOf("SDNodeXForm") &&
2540 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002541 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002542 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002543 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002544 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002545
Chris Lattner8cab0212008-01-05 22:25:12 +00002546 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002547 if (isInputPattern) {
2548 if (Operator->isSubClassOf("Instruction") ||
2549 Operator->isSubClassOf("SDNodeXForm"))
2550 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2551 } else {
2552 if (Operator->isSubClassOf("Intrinsic"))
2553 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002554
Chris Lattner2e9eae12010-03-28 06:57:56 +00002555 if (Operator->isSubClassOf("SDNode") &&
2556 Operator->getName() != "imm" &&
2557 Operator->getName() != "fpimm" &&
2558 Operator->getName() != "tglobaltlsaddr" &&
2559 Operator->getName() != "tconstpool" &&
2560 Operator->getName() != "tjumptable" &&
2561 Operator->getName() != "tframeindex" &&
2562 Operator->getName() != "texternalsym" &&
2563 Operator->getName() != "tblockaddress" &&
2564 Operator->getName() != "tglobaladdr" &&
2565 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002566 Operator->getName() != "vt" &&
2567 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002568 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2569 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002570
Chris Lattner8cab0212008-01-05 22:25:12 +00002571 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002572
2573 // Parse all the operands.
2574 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002575 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002576
Chris Lattner8cab0212008-01-05 22:25:12 +00002577 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002578 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002579 // convert the intrinsic name to a number.
2580 if (Operator->isSubClassOf("Intrinsic")) {
2581 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2582 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2583
2584 // If this intrinsic returns void, it must have side-effects and thus a
2585 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002586 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002587 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002588 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002589 // Has side-effects, requires chain.
2590 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002591 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002592 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002593
David Greenee32ebf22011-07-29 19:07:07 +00002594 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002595 Children.insert(Children.begin(), IIDNode);
2596 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002597
Tim Northoverc807a172014-05-20 11:52:46 +00002598 if (Operator->isSubClassOf("ComplexPattern")) {
2599 for (unsigned i = 0; i < Children.size(); ++i) {
2600 TreePatternNode *Child = Children[i];
2601
2602 if (Child->getName().empty())
2603 error("All arguments to a ComplexPattern must be named");
2604
2605 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2606 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2607 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2608 auto OperandId = std::make_pair(Operator, i);
2609 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2610 if (PrevOp != ComplexPatternOperands.end()) {
2611 if (PrevOp->getValue() != OperandId)
2612 error("All ComplexPattern operands must appear consistently: "
2613 "in the same order in just one ComplexPattern instance.");
2614 } else
2615 ComplexPatternOperands[Child->getName()] = OperandId;
2616 }
2617 }
2618
Chris Lattnerf1447252010-03-19 21:37:09 +00002619 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002620 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002621 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002622
Matthias Braun7cf3b112016-12-05 06:00:41 +00002623 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002624 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002625 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002626 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002627 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002628}
2629
Chris Lattnera787c9e2010-03-28 08:38:32 +00002630/// SimplifyTree - See if we can simplify this tree to eliminate something that
2631/// will never match in favor of something obvious that will. This is here
2632/// strictly as a convenience to target authors because it allows them to write
2633/// more type generic things and have useless type casts fold away.
2634///
2635/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002636static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002637 if (N->isLeaf())
2638 return false;
2639
2640 // If we have a bitconvert with a resolved type and if the source and
2641 // destination types are the same, then the bitconvert is useless, remove it.
2642 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002643 N->getExtType(0).isValueTypeByHwMode(false) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002644 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2645 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002646 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002647 SimplifyTree(N);
2648 return true;
2649 }
2650
2651 // Walk all children.
2652 bool MadeChange = false;
2653 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002654 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002655 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002656 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002657 }
2658 return MadeChange;
2659}
2660
2661
2662
Chris Lattner8cab0212008-01-05 22:25:12 +00002663/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002664/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002665/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002666bool TreePattern::
2667InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2668 if (NamedNodes.empty())
2669 ComputeNamedNodes();
2670
Chris Lattner8cab0212008-01-05 22:25:12 +00002671 bool MadeChange = true;
2672 while (MadeChange) {
2673 MadeChange = false;
Craig Topper3f7864e2017-08-30 02:05:03 +00002674 for (TreePatternNode *&Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002675 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2676 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002677 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002678
2679 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002680 for (auto &Entry : NamedNodes) {
2681 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002682
Chris Lattnercabe0372010-03-15 06:00:16 +00002683 // If we have input named node types, propagate their types to the named
2684 // values here.
2685 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002686 if (!InNamedTypes->count(Entry.getKey())) {
2687 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002688 "' in output pattern but not input pattern");
2689 return true;
2690 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002691
2692 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002693 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002694
2695 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002696 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002697 // If this node is a register class, and it is the root of the pattern
2698 // then we're mapping something onto an input register. We allow
2699 // changing the type of the input register in this case. This allows
2700 // us to match things like:
2701 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002702 if (Node == Trees[0] && Node->isLeaf()) {
2703 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002704 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2705 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002706 continue;
2707 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002708
Craig Topper306cb122015-11-22 20:46:24 +00002709 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002710 InNodes[0]->getNumTypes() == 1 &&
2711 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002712 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2713 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002714 }
2715 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002716
Chris Lattnercabe0372010-03-15 06:00:16 +00002717 // If there are multiple nodes with the same name, they must all have the
2718 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002719 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002720 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002721 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002722 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002723 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002724
Chris Lattnerf1447252010-03-19 21:37:09 +00002725 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2726 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002727 }
2728 }
2729 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002730 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002731
Chris Lattner8cab0212008-01-05 22:25:12 +00002732 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002733 for (const TreePatternNode *Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002734 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002735 return !HasUnresolvedTypes;
2736}
2737
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002738void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002739 OS << getRecord()->getName();
2740 if (!Args.empty()) {
2741 OS << "(" << Args[0];
2742 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2743 OS << ", " << Args[i];
2744 OS << ")";
2745 }
2746 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002747
Chris Lattner8cab0212008-01-05 22:25:12 +00002748 if (Trees.size() > 1)
2749 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002750 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002751 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002752 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002753 OS << "\n";
2754 }
2755
2756 if (Trees.size() > 1)
2757 OS << "]\n";
2758}
2759
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002760void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002761
2762//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002763// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002764//
2765
Daniel Sanders7e523672017-11-11 03:23:44 +00002766CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2767 PatternRewriterFn PatternRewriter)
2768 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2769 PatternRewriter(PatternRewriter) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002770
Justin Bogner92a8c612016-07-15 16:31:37 +00002771 Intrinsics = CodeGenIntrinsicTable(Records, false);
2772 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002773 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002774 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002775 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002776 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002777 ParseDefaultOperands();
2778 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002779 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002780 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002781
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002782 // Break patterns with parameterized types into a series of patterns,
2783 // where each one has a fixed type and is predicated on the conditions
2784 // of the associated HW mode.
2785 ExpandHwModeBasedTypes();
2786
Chris Lattner8cab0212008-01-05 22:25:12 +00002787 // Generate variants. For example, commutative patterns can match
2788 // multiple ways. Add them to PatternsToMatch as well.
2789 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002790
2791 // Infer instruction flags. For example, we can detect loads,
2792 // stores, and side effects in many cases by examining an
2793 // instruction's pattern.
2794 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002795
2796 // Verify that instruction flags match the patterns.
2797 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002798}
2799
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00002800Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002801 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002802 if (!N || !N->isSubClassOf("SDNode"))
2803 PrintFatalError("Error getting SDNode '" + Name + "'!");
2804
Chris Lattner8cab0212008-01-05 22:25:12 +00002805 return N;
2806}
2807
2808// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002809void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002810 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002811 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2812
Chris Lattner8cab0212008-01-05 22:25:12 +00002813 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002814 Record *R = Nodes.back();
2815 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002816 Nodes.pop_back();
2817 }
2818
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002819 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002820 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2821 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2822 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2823}
2824
2825/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2826/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002827void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002828 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2829 while (!Xforms.empty()) {
2830 Record *XFormNode = Xforms.back();
2831 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002832 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002833 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002834
2835 Xforms.pop_back();
2836 }
2837}
2838
Chris Lattnerab3242f2008-01-06 01:10:31 +00002839void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002840 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2841 while (!AMs.empty()) {
2842 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2843 AMs.pop_back();
2844 }
2845}
2846
2847
2848/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2849/// file, building up the PatternFragments map. After we've collected them all,
2850/// inline fragments together as necessary, so that there are no references left
2851/// inside a pattern fragment to a pattern fragment.
2852///
Hal Finkel2756dc12014-02-28 00:26:56 +00002853void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002854 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002855
Chris Lattnere7170df2008-01-05 22:43:57 +00002856 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002857 for (Record *Frag : Fragments) {
2858 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002859 continue;
2860
Craig Topper306cb122015-11-22 20:46:24 +00002861 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002862 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002863 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2864 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002865 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002866
Chris Lattnere7170df2008-01-05 22:43:57 +00002867 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002868 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00002869 // Copy the args so we can take StringRefs to them.
2870 auto ArgsCopy = Args;
2871 SmallDenseSet<StringRef, 4> OperandsSet;
2872 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002873
Chris Lattnere7170df2008-01-05 22:43:57 +00002874 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002875 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002876
Chris Lattner8cab0212008-01-05 22:25:12 +00002877 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002878 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002879 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002880 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002881 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002882 if (!OpsOp ||
2883 (OpsOp->getDef()->getName() != "ops" &&
2884 OpsOp->getDef()->getName() != "outs" &&
2885 OpsOp->getDef()->getName() != "ins"))
2886 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002887
2888 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002889 Args.clear();
2890 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002891 if (!isa<DefInit>(OpsList->getArg(j)) ||
2892 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002893 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00002894 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00002895 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00002896 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2897 if (!OperandsSet.count(ArgNameStr))
2898 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00002899 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00002900 OperandsSet.erase(ArgNameStr);
2901 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00002902 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002903
Chris Lattnere7170df2008-01-05 22:43:57 +00002904 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002905 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002906 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002907
Chris Lattnere7170df2008-01-05 22:43:57 +00002908 // If there is a code init for this fragment, keep track of the fact that
2909 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002910 TreePredicateFn PredFn(P);
2911 if (!PredFn.isAlwaysTrue())
2912 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002913
Chris Lattner8cab0212008-01-05 22:25:12 +00002914 // If there is a node transformation corresponding to this, keep track of
2915 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002916 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002917 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2918 P->getOnlyTree()->setTransformFn(Transform);
2919 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002920
Chris Lattner8cab0212008-01-05 22:25:12 +00002921 // Now that we've parsed all of the tree fragments, do a closure on them so
2922 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002923 for (Record *Frag : Fragments) {
2924 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002925 continue;
2926
Craig Topper306cb122015-11-22 20:46:24 +00002927 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002928 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002929
Chris Lattner8cab0212008-01-05 22:25:12 +00002930 // Infer as many types as possible. Don't worry about it if we don't infer
2931 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002932 ThePat.InferAllTypes();
2933 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002934
Chris Lattner8cab0212008-01-05 22:25:12 +00002935 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002936 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002937 }
2938}
2939
Chris Lattnerab3242f2008-01-06 01:10:31 +00002940void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002941 std::vector<Record*> DefaultOps;
2942 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002943
2944 // Find some SDNode.
2945 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002946 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002947
Tom Stellardb7246a72012-09-06 14:15:52 +00002948 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2949 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002950
Tom Stellardb7246a72012-09-06 14:15:52 +00002951 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2952 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00002953 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00002954 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2955 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2956 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00002957 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002958
Tom Stellardb7246a72012-09-06 14:15:52 +00002959 // Create a TreePattern to parse this.
2960 TreePattern P(DefaultOps[i], DI, false, *this);
2961 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002962
Tom Stellardb7246a72012-09-06 14:15:52 +00002963 // Copy the operands over into a DAGDefaultOperand.
2964 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002965
Tom Stellardb7246a72012-09-06 14:15:52 +00002966 TreePatternNode *T = P.getTree(0);
2967 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2968 TreePatternNode *TPN = T->getChild(op);
2969 while (TPN->ApplyTypeConstraints(P, false))
2970 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002971
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002972 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002973 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2974 DefaultOps[i]->getName() +
2975 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002976 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002977 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002978 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002979
2980 // Insert it into the DefaultOperands map so we can find it later.
2981 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002982 }
2983}
2984
2985/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2986/// instruction input. Return true if this is a real use.
2987static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002988 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002989 // No name -> not interesting.
2990 if (Pat->getName().empty()) {
2991 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002992 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002993 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2994 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002995 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002996 }
2997 return false;
2998 }
2999
3000 Record *Rec;
3001 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003002 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003003 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
3004 Rec = DI->getDef();
3005 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003006 Rec = Pat->getOperator();
3007 }
3008
3009 // SRCVALUE nodes are ignored.
3010 if (Rec->getName() == "srcvalue")
3011 return false;
3012
3013 TreePatternNode *&Slot = InstInputs[Pat->getName()];
3014 if (!Slot) {
3015 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003016 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00003017 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003018 Record *SlotRec;
3019 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003020 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003021 } else {
3022 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3023 SlotRec = Slot->getOperator();
3024 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003025
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003026 // Ensure that the inputs agree if we've already seen this input.
3027 if (Rec != SlotRec)
3028 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00003029 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003030 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003031 return true;
3032}
3033
3034/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3035/// part of "I", the instruction), computing the set of inputs and outputs of
3036/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003037void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00003038FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
3039 std::map<std::string, TreePatternNode*> &InstInputs,
3040 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00003041 std::vector<Record*> &InstImpResults) {
3042 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003043 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00003044 if (!isUse && Pat->getTransformFn())
3045 I->error("Cannot specify a transform function for a non-input value!");
3046 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003047 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003048
Chris Lattnerf2d70992010-02-17 06:53:36 +00003049 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003050 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3051 TreePatternNode *Dest = Pat->getChild(i);
3052 if (!Dest->isLeaf())
3053 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003054
Sean Silvafb509ed2012-10-10 20:24:43 +00003055 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003056 if (!Val || !Val->getDef()->isSubClassOf("Register"))
3057 I->error("implicitly defined value should be a register!");
3058 InstImpResults.push_back(Val->getDef());
3059 }
3060 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003061 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003062
Chris Lattnerf2d70992010-02-17 06:53:36 +00003063 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003064 // If this is not a set, verify that the children nodes are not void typed,
3065 // and recurse.
3066 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003067 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00003068 I->error("Cannot have void nodes inside of patterns!");
3069 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003070 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003071 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003072
Chris Lattner8cab0212008-01-05 22:25:12 +00003073 // If this is a non-leaf node with no children, treat it basically as if
3074 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003075 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003076
Chris Lattner8cab0212008-01-05 22:25:12 +00003077 if (!isUse && Pat->getTransformFn())
3078 I->error("Cannot specify a transform function for a non-input value!");
3079 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003080 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003081
Chris Lattner8cab0212008-01-05 22:25:12 +00003082 // Otherwise, this is a set, validate and collect instruction results.
3083 if (Pat->getNumChildren() == 0)
3084 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003085
Chris Lattner8cab0212008-01-05 22:25:12 +00003086 if (Pat->getTransformFn())
3087 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003088
Chris Lattner8cab0212008-01-05 22:25:12 +00003089 // Check the set destinations.
3090 unsigned NumDests = Pat->getNumChildren()-1;
3091 for (unsigned i = 0; i != NumDests; ++i) {
3092 TreePatternNode *Dest = Pat->getChild(i);
3093 if (!Dest->isLeaf())
3094 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003095
Sean Silvafb509ed2012-10-10 20:24:43 +00003096 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003097 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003098 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003099 continue;
3100 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003101
3102 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003103 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003104 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003105 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003106 if (Dest->getName().empty())
3107 I->error("set destination must have a name!");
3108 if (InstResults.count(Dest->getName()))
3109 I->error("cannot set '" + Dest->getName() +"' multiple times");
3110 InstResults[Dest->getName()] = Dest;
3111 } else if (Val->getDef()->isSubClassOf("Register")) {
3112 InstImpResults.push_back(Val->getDef());
3113 } else {
3114 I->error("set destination should be a register!");
3115 }
3116 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003117
Chris Lattner8cab0212008-01-05 22:25:12 +00003118 // Verify and collect info from the computation.
3119 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00003120 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003121}
3122
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003123//===----------------------------------------------------------------------===//
3124// Instruction Analysis
3125//===----------------------------------------------------------------------===//
3126
3127class InstAnalyzer {
3128 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003129public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003130 bool hasSideEffects;
3131 bool mayStore;
3132 bool mayLoad;
3133 bool isBitcast;
3134 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003135
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003136 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3137 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3138 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003139
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003140 void Analyze(const TreePattern *Pat) {
3141 // Assume only the first tree is the pattern. The others are clobber nodes.
3142 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003143 }
3144
Craig Topper2a053a92017-06-20 16:34:37 +00003145 void Analyze(const PatternToMatch &Pat) {
3146 AnalyzeNode(Pat.getSrcPattern());
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003147 }
3148
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003149private:
Evan Cheng880e299d2011-03-15 05:09:26 +00003150 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003151 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003152 return false;
3153
3154 if (N->getNumChildren() != 2)
3155 return false;
3156
3157 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00003158 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00003159 return false;
3160
3161 const TreePatternNode *N1 = N->getChild(1);
3162 if (N1->isLeaf())
3163 return false;
3164 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
3165 return false;
3166
3167 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
3168 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3169 return false;
3170 return OpInfo.getEnumName() == "ISD::BITCAST";
3171 }
3172
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003173public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003174 void AnalyzeNode(const TreePatternNode *N) {
3175 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003176 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003177 Record *LeafRec = DI->getDef();
3178 // Handle ComplexPattern leaves.
3179 if (LeafRec->isSubClassOf("ComplexPattern")) {
3180 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3181 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3182 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003183 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003184 }
3185 }
3186 return;
3187 }
3188
3189 // Analyze children.
3190 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3191 AnalyzeNode(N->getChild(i));
3192
3193 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00003194 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003195 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003196 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00003197 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003198
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003199 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00003200 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3201 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3202 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3203 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003204
3205 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3206 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003207 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003208 mayLoad = true;// These may load memory.
3209
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003210 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003211 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3212
Matt Arsenault868af922017-04-28 21:01:46 +00003213 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3214 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003215 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003216 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003217 }
3218 }
3219
3220};
3221
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003222static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003223 const InstAnalyzer &PatInfo,
3224 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003225 bool Error = false;
3226
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003227 // Remember where InstInfo got its flags.
3228 if (InstInfo.hasUndefFlags())
3229 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003230
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003231 // Check explicitly set flags for consistency.
3232 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3233 !InstInfo.hasSideEffects_Unset) {
3234 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3235 // the pattern has no side effects. That could be useful for div/rem
3236 // instructions that may trap.
3237 if (!InstInfo.hasSideEffects) {
3238 Error = true;
3239 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3240 Twine(InstInfo.hasSideEffects));
3241 }
3242 }
3243
3244 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3245 Error = true;
3246 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3247 Twine(InstInfo.mayStore));
3248 }
3249
3250 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3251 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003252 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003253 if (!InstInfo.mayLoad) {
3254 Error = true;
3255 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3256 Twine(InstInfo.mayLoad));
3257 }
3258 }
3259
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003260 // Transfer inferred flags.
3261 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3262 InstInfo.mayStore |= PatInfo.mayStore;
3263 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003264
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003265 // These flags are silently added without any verification.
3266 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003267
3268 // Don't infer isVariadic. This flag means something different on SDNodes and
3269 // instructions. For example, a CALL SDNode is variadic because it has the
3270 // call arguments as operands, but a CALL instruction is not variadic - it
3271 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003272
3273 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003274}
3275
Jim Grosbach514410b2012-07-17 00:47:06 +00003276/// hasNullFragReference - Return true if the DAG has any reference to the
3277/// null_frag operator.
3278static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003279 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003280 if (!OpDef) return false;
3281 Record *Operator = OpDef->getDef();
3282
3283 // If this is the null fragment, return true.
3284 if (Operator->getName() == "null_frag") return true;
3285 // If any of the arguments reference the null fragment, return true.
3286 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003287 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003288 if (Arg && hasNullFragReference(Arg))
3289 return true;
3290 }
3291
3292 return false;
3293}
3294
3295/// hasNullFragReference - Return true if any DAG in the list references
3296/// the null_frag operator.
3297static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003298 for (Init *I : LI->getValues()) {
3299 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003300 assert(DI && "non-dag in an instruction Pattern list?!");
3301 if (hasNullFragReference(DI))
3302 return true;
3303 }
3304 return false;
3305}
3306
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003307/// Get all the instructions in a tree.
3308static void
3309getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3310 if (Tree->isLeaf())
3311 return;
3312 if (Tree->getOperator()->isSubClassOf("Instruction"))
3313 Instrs.push_back(Tree->getOperator());
3314 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3315 getInstructionsInTree(Tree->getChild(i), Instrs);
3316}
3317
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003318/// Check the class of a pattern leaf node against the instruction operand it
3319/// represents.
3320static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3321 Record *Leaf) {
3322 if (OI.Rec == Leaf)
3323 return true;
3324
3325 // Allow direct value types to be used in instruction set patterns.
3326 // The type will be checked later.
3327 if (Leaf->isSubClassOf("ValueType"))
3328 return true;
3329
3330 // Patterns can also be ComplexPattern instances.
3331 if (Leaf->isSubClassOf("ComplexPattern"))
3332 return true;
3333
3334 return false;
3335}
3336
Ahmed Bougacha14107512013-10-28 18:07:21 +00003337const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
3338 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003339
Craig Topper0d1fb902015-03-10 03:25:04 +00003340 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003341
Craig Topper0d1fb902015-03-10 03:25:04 +00003342 // Parse the instruction.
3343 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
3344 // Inline pattern fragments into it.
3345 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003346
Craig Topper0d1fb902015-03-10 03:25:04 +00003347 // Infer as many types as possible. If we cannot infer all of them, we can
3348 // never do anything with this instruction pattern: report it to the user.
3349 if (!I->InferAllTypes())
3350 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003351
Craig Topper0d1fb902015-03-10 03:25:04 +00003352 // InstInputs - Keep track of all of the inputs of the instruction, along
3353 // with the record they are declared as.
3354 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003355
Craig Topper0d1fb902015-03-10 03:25:04 +00003356 // InstResults - Keep track of all the virtual registers that are 'set'
3357 // in the instruction, including what reg class they are.
3358 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003359
Craig Topper0d1fb902015-03-10 03:25:04 +00003360 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003361
Craig Topper0d1fb902015-03-10 03:25:04 +00003362 // Verify that the top-level forms in the instruction are of void type, and
3363 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003364 SmallString<32> TypesString;
Craig Topper0d1fb902015-03-10 03:25:04 +00003365 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003366 TypesString.clear();
Craig Topper0d1fb902015-03-10 03:25:04 +00003367 TreePatternNode *Pat = I->getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003368 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003369 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003370 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3371 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003372 OS << ", ";
3373 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003374 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003375 I->error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003376 " void types, has types " +
3377 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003378 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003379
Craig Topper0d1fb902015-03-10 03:25:04 +00003380 // Find inputs and outputs, and verify the structure of the uses/defs.
3381 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3382 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003383 }
3384
Craig Topper0d1fb902015-03-10 03:25:04 +00003385 // Now that we have inputs and outputs of the pattern, inspect the operands
3386 // list for the instruction. This determines the order that operands are
3387 // added to the machine instruction the node corresponds to.
3388 unsigned NumResults = InstResults.size();
3389
3390 // Parse the operands list from the (ops) list, validating it.
3391 assert(I->getArgList().empty() && "Args list should still be empty here!");
3392
3393 // Check that all of the results occur first in the list.
3394 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00003395 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003396 for (unsigned i = 0; i != NumResults; ++i) {
3397 if (i == CGI.Operands.size())
3398 I->error("'" + InstResults.begin()->first +
3399 "' set but does not appear in operand list!");
3400 const std::string &OpName = CGI.Operands[i].Name;
3401
3402 // Check that it exists in InstResults.
3403 TreePatternNode *RNode = InstResults[OpName];
3404 if (!RNode)
3405 I->error("Operand $" + OpName + " does not exist in operand list!");
3406
Craig Topper3a8eb892015-03-20 05:09:06 +00003407 ResNodes.push_back(RNode);
3408
Craig Topper0d1fb902015-03-10 03:25:04 +00003409 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3410 if (!R)
3411 I->error("Operand $" + OpName + " should be a set destination: all "
3412 "outputs must occur before inputs in operand list!");
3413
3414 if (!checkOperandClass(CGI.Operands[i], R))
3415 I->error("Operand $" + OpName + " class mismatch!");
3416
3417 // Remember the return type.
3418 Results.push_back(CGI.Operands[i].Rec);
3419
3420 // Okay, this one checks out.
3421 InstResults.erase(OpName);
3422 }
3423
3424 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3425 // the copy while we're checking the inputs.
3426 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3427
3428 std::vector<TreePatternNode*> ResultNodeOperands;
3429 std::vector<Record*> Operands;
3430 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3431 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3432 const std::string &OpName = Op.Name;
3433 if (OpName.empty())
3434 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3435
3436 if (!InstInputsCheck.count(OpName)) {
3437 // If this is an operand with a DefaultOps set filled in, we can ignore
3438 // this. When we codegen it, we will do so as always executed.
3439 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3440 // Does it have a non-empty DefaultOps field? If so, ignore this
3441 // operand.
3442 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3443 continue;
3444 }
3445 I->error("Operand $" + OpName +
3446 " does not appear in the instruction pattern");
3447 }
3448 TreePatternNode *InVal = InstInputsCheck[OpName];
3449 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3450
3451 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3452 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3453 if (!checkOperandClass(Op, InRec))
3454 I->error("Operand $" + OpName + "'s register class disagrees"
3455 " between the operand and pattern");
3456 }
3457 Operands.push_back(Op.Rec);
3458
3459 // Construct the result for the dest-pattern operand list.
3460 TreePatternNode *OpNode = InVal->clone();
3461
3462 // No predicate is useful on the result.
3463 OpNode->clearPredicateFns();
3464
3465 // Promote the xform function to be an explicit node if set.
3466 if (Record *Xform = OpNode->getTransformFn()) {
3467 OpNode->setTransformFn(nullptr);
3468 std::vector<TreePatternNode*> Children;
3469 Children.push_back(OpNode);
3470 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3471 }
3472
3473 ResultNodeOperands.push_back(OpNode);
3474 }
3475
3476 if (!InstInputsCheck.empty())
3477 I->error("Input operand $" + InstInputsCheck.begin()->first +
3478 " occurs in pattern but not in operands list!");
3479
3480 TreePatternNode *ResultPattern =
3481 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3482 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003483 // Copy fully inferred output node types to instruction result pattern.
3484 for (unsigned i = 0; i != NumResults; ++i) {
3485 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3486 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3487 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003488
3489 // Create and insert the instruction.
3490 // FIXME: InstImpResults should not be part of DAGInstruction.
3491 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3492 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3493
3494 // Use a temporary tree pattern to infer all types and make sure that the
3495 // constructed result is correct. This depends on the instruction already
3496 // being inserted into the DAGInsts map.
3497 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3498 Temp.InferAllTypes(&I->getNamedNodesMap());
3499
3500 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3501 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3502
3503 return TheInsertedInst;
3504}
3505
Ahmed Bougacha14107512013-10-28 18:07:21 +00003506/// ParseInstructions - Parse all of the instructions, inlining and resolving
3507/// any fragments involved. This populates the Instructions list with fully
3508/// resolved instructions.
3509void CodeGenDAGPatterns::ParseInstructions() {
3510 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3511
Craig Topper306cb122015-11-22 20:46:24 +00003512 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003513 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003514
Craig Topper306cb122015-11-22 20:46:24 +00003515 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3516 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003517
3518 // If there is no pattern, only collect minimal information about the
3519 // instruction for its operand list. We have to assume that there is one
3520 // result, as we have no detailed info. A pattern which references the
3521 // null_frag operator is as-if no pattern were specified. Normally this
3522 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3523 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003524 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003525 std::vector<Record*> Results;
3526 std::vector<Record*> Operands;
3527
Craig Topper306cb122015-11-22 20:46:24 +00003528 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003529
3530 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003531 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3532 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003533
Craig Topper3a8eb892015-03-20 05:09:06 +00003534 // The rest are inputs.
3535 for (unsigned j = InstInfo.Operands.NumDefs,
3536 e = InstInfo.Operands.size(); j < e; ++j)
3537 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003538 }
3539
3540 // Create and insert the instruction.
3541 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003542 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003543 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003544 continue; // no pattern.
3545 }
3546
Craig Topper306cb122015-11-22 20:46:24 +00003547 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003548 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3549
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003550 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003551 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003552 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003553
Chris Lattner8cab0212008-01-05 22:25:12 +00003554 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003555 for (auto &Entry : Instructions) {
3556 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003557 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003558 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003559
Daniel Sanders7e523672017-11-11 03:23:44 +00003560 if (PatternRewriter)
3561 PatternRewriter(I);
Chris Lattner8cab0212008-01-05 22:25:12 +00003562 // FIXME: Assume only the first tree is the pattern. The others are clobber
3563 // nodes.
3564 TreePatternNode *Pattern = I->getTree(0);
3565 TreePatternNode *SrcPattern;
3566 if (Pattern->getOperator()->getName() == "set") {
3567 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3568 } else{
3569 // Not a set (store or something?)
3570 SrcPattern = Pattern;
3571 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003572
Craig Topper306cb122015-11-22 20:46:24 +00003573 Record *Instr = Entry.first;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003574 ListInit *Preds = Instr->getValueAsListInit("Predicates");
3575 int Complexity = Instr->getValueAsInt("AddedComplexity");
3576 AddPatternToMatch(
3577 I,
3578 PatternToMatch(Instr, makePredList(Preds), SrcPattern,
3579 TheInst.getResultPattern(), TheInst.getImpResults(),
3580 Complexity, Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003581 }
3582}
3583
Chris Lattnera7722b62010-02-23 06:55:24 +00003584
3585typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3586
Jim Grosbach65586fe2010-12-21 16:16:00 +00003587static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003588 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003589 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003590 if (!P->getName().empty()) {
3591 NameRecord &Rec = Names[P->getName()];
3592 // If this is the first instance of the name, remember the node.
3593 if (Rec.second++ == 0)
3594 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003595 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003596 PatternTop->error("repetition of value: $" + P->getName() +
3597 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003598 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003599
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003600 if (!P->isLeaf()) {
3601 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003602 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003603 }
3604}
3605
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003606std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3607 std::vector<Predicate> Preds;
3608 for (Init *I : L->getValues()) {
3609 if (DefInit *Pred = dyn_cast<DefInit>(I))
3610 Preds.push_back(Pred->getDef());
3611 else
3612 llvm_unreachable("Non-def on the list");
3613 }
3614
3615 // Sort so that different orders get canonicalized to the same string.
3616 std::sort(Preds.begin(), Preds.end());
3617 return Preds;
3618}
3619
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003620void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003621 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003622 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003623 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003624 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3625 PrintWarning(Pattern->getRecord()->getLoc(),
3626 Twine("Pattern can never match: ") + Reason);
3627 return;
3628 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003629
Chris Lattner1e634e32010-03-01 22:29:19 +00003630 // If the source pattern's root is a complex pattern, that complex pattern
3631 // must specify the nodes it can potentially match.
3632 if (const ComplexPattern *CP =
3633 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3634 if (CP->getRootNodes().empty())
3635 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3636 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003637
3638
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003639 // Find all of the named values in the input and output, ensure they have the
3640 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003641 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003642 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3643 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003644
3645 // Scan all of the named values in the destination pattern, rejecting them if
3646 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003647 for (const auto &Entry : DstNames) {
3648 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003649 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003650 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003651 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003652
Chris Lattnera7722b62010-02-23 06:55:24 +00003653 // Scan all of the named values in the source pattern, rejecting them if the
3654 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003655 for (const auto &Entry : SrcNames)
3656 if (DstNames[Entry.first].first == nullptr &&
3657 SrcNames[Entry.first].second == 1)
3658 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003659
Craig Topper18e6b572017-06-25 17:33:49 +00003660 PatternsToMatch.push_back(std::move(PTM));
Chris Lattner0c0baa92010-02-23 06:16:51 +00003661}
3662
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003663void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003664 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003665 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003666
3667 // First try to infer flags from the primary instruction pattern, if any.
3668 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003669 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003670 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3671 CodeGenInstruction &InstInfo =
3672 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003673
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003674 // Get the primary instruction pattern.
3675 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3676 if (!Pattern) {
3677 if (InstInfo.hasUndefFlags())
3678 Revisit.push_back(&InstInfo);
3679 continue;
3680 }
3681 InstAnalyzer PatInfo(*this);
3682 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003683 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003684 }
3685
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003686 // Second, look for single-instruction patterns defined outside the
3687 // instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003688 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003689 // We can only infer from single-instruction patterns, otherwise we won't
3690 // know which instruction should get the flags.
3691 SmallVector<Record*, 8> PatInstrs;
3692 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3693 if (PatInstrs.size() != 1)
3694 continue;
3695
3696 // Get the single instruction.
3697 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3698
3699 // Only infer properties from the first pattern. We'll verify the others.
3700 if (InstInfo.InferredFrom)
3701 continue;
3702
3703 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003704 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003705 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3706 }
3707
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003708 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003709 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003710
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003711 // Revisit instructions with undefined flags and no pattern.
3712 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003713 for (CodeGenInstruction *InstInfo : Revisit) {
3714 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003715 continue;
3716 // The mayLoad and mayStore flags default to false.
3717 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003718 if (InstInfo->hasSideEffects_Unset)
3719 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003720 }
3721 return;
3722 }
3723
3724 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003725 for (CodeGenInstruction *InstInfo : Revisit) {
3726 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003727 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003728 if (InstInfo->hasSideEffects_Unset)
3729 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003730 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003731 if (InstInfo->mayStore_Unset)
3732 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003733 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003734 if (InstInfo->mayLoad_Unset)
3735 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003736 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003737 }
3738}
3739
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003740
3741/// Verify instruction flags against pattern node properties.
3742void CodeGenDAGPatterns::VerifyInstructionFlags() {
3743 unsigned Errors = 0;
3744 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3745 const PatternToMatch &PTM = *I;
3746 SmallVector<Record*, 8> Instrs;
3747 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3748 if (Instrs.empty())
3749 continue;
3750
3751 // Count the number of instructions with each flag set.
3752 unsigned NumSideEffects = 0;
3753 unsigned NumStores = 0;
3754 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003755 for (const Record *Instr : Instrs) {
3756 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003757 NumSideEffects += InstInfo.hasSideEffects;
3758 NumStores += InstInfo.mayStore;
3759 NumLoads += InstInfo.mayLoad;
3760 }
3761
3762 // Analyze the source pattern.
3763 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003764 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003765
3766 // Collect error messages.
3767 SmallVector<std::string, 4> Msgs;
3768
3769 // Check for missing flags in the output.
3770 // Permit extra flags for now at least.
3771 if (PatInfo.hasSideEffects && !NumSideEffects)
3772 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3773
3774 // Don't verify store flags on instructions with side effects. At least for
3775 // intrinsics, side effects implies mayStore.
3776 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3777 Msgs.push_back("pattern may store, but mayStore isn't set");
3778
3779 // Similarly, mayStore implies mayLoad on intrinsics.
3780 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3781 Msgs.push_back("pattern may load, but mayLoad isn't set");
3782
3783 // Print error messages.
3784 if (Msgs.empty())
3785 continue;
3786 ++Errors;
3787
Craig Topper306cb122015-11-22 20:46:24 +00003788 for (const std::string &Msg : Msgs)
3789 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003790 (Instrs.size() == 1 ?
3791 "instruction" : "output instructions"));
3792 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003793 for (const Record *Instr : Instrs) {
3794 if (Instr != PTM.getSrcRecord())
3795 PrintError(Instr->getLoc(), "defined here");
3796 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003797 if (InstInfo.InferredFrom &&
3798 InstInfo.InferredFrom != InstInfo.TheDef &&
3799 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003800 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003801 }
3802 }
3803 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003804 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003805}
3806
Chris Lattnercabe0372010-03-15 06:00:16 +00003807/// Given a pattern result with an unresolved type, see if we can find one
3808/// instruction with an unresolved result type. Force this result type to an
3809/// arbitrary element if it's possible types to converge results.
3810static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3811 if (N->isLeaf())
3812 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003813
Chris Lattnercabe0372010-03-15 06:00:16 +00003814 // Analyze children.
3815 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3816 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3817 return true;
3818
3819 if (!N->getOperator()->isSubClassOf("Instruction"))
3820 return false;
3821
3822 // If this type is already concrete or completely unknown we can't do
3823 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003824 TypeInfer &TI = TP.getInfer();
Chris Lattnerf1447252010-03-19 21:37:09 +00003825 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003826 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003827 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003828
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003829 // Otherwise, force its type to an arbitrary choice.
3830 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003831 return true;
3832 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003833
Chris Lattnerf1447252010-03-19 21:37:09 +00003834 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003835}
3836
Chris Lattnerab3242f2008-01-06 01:10:31 +00003837void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003838 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3839
Craig Topper306cb122015-11-22 20:46:24 +00003840 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003841 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003842
3843 // If the pattern references the null_frag, there's nothing to do.
3844 if (hasNullFragReference(Tree))
3845 continue;
3846
Chris Lattner5c2182e2010-03-27 02:53:27 +00003847 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003848
3849 // Inline pattern fragments into it.
3850 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003851
David Greeneaf8ee2c2011-07-29 22:43:06 +00003852 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003853 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003854
Chris Lattner8cab0212008-01-05 22:25:12 +00003855 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003856 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003857
Chris Lattner8cab0212008-01-05 22:25:12 +00003858 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003859 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003860
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003861 if (Result.getNumTrees() != 1)
3862 Result.error("Cannot handle instructions producing instructions "
3863 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003864
Chris Lattner8cab0212008-01-05 22:25:12 +00003865 bool IterateInference;
3866 bool InferredAllPatternTypes, InferredAllResultTypes;
3867 do {
3868 // Infer as many types as possible. If we cannot infer all of them, we
3869 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003870 InferredAllPatternTypes =
3871 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003872
Chris Lattner8cab0212008-01-05 22:25:12 +00003873 // Infer as many types as possible. If we cannot infer all of them, we
3874 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003875 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003876 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003877
Chris Lattnerfdc20712010-03-18 23:15:10 +00003878 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003879
Chris Lattner8cab0212008-01-05 22:25:12 +00003880 // Apply the type of the result to the source pattern. This helps us
3881 // resolve cases where the input type is known to be a pointer type (which
3882 // is considered resolved), but the result knows it needs to be 32- or
3883 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003884 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003885 Pattern->getTree(0)->getNumTypes());
3886 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003887 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3888 i, Result.getTree(0)->getExtType(i), Result);
3889 IterateInference |= Result.getTree(0)->UpdateNodeType(
3890 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003891 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003892
Chris Lattnercabe0372010-03-15 06:00:16 +00003893 // If our iteration has converged and the input pattern's types are fully
3894 // resolved but the result pattern is not fully resolved, we may have a
3895 // situation where we have two instructions in the result pattern and
3896 // the instructions require a common register class, but don't care about
3897 // what actual MVT is used. This is actually a bug in our modelling:
3898 // output patterns should have register classes, not MVTs.
3899 //
3900 // In any case, to handle this, we just go through and disambiguate some
3901 // arbitrary types to the result pattern's nodes.
3902 if (!IterateInference && InferredAllPatternTypes &&
3903 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003904 IterateInference =
3905 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003906 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003907
Chris Lattner8cab0212008-01-05 22:25:12 +00003908 // Verify that we inferred enough types that we can do something with the
3909 // pattern and result. If these fire the user has to add type casts.
3910 if (!InferredAllPatternTypes)
3911 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003912 if (!InferredAllResultTypes) {
3913 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003914 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003915 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003916
Chris Lattner8cab0212008-01-05 22:25:12 +00003917 // Validate that the input pattern is correct.
3918 std::map<std::string, TreePatternNode*> InstInputs;
3919 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003920 std::vector<Record*> InstImpResults;
3921 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3922 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3923 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003924 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003925
3926 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003927 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003928 std::vector<TreePatternNode*> ResultNodeOperands;
3929 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3930 TreePatternNode *OpNode = DstPattern->getChild(ii);
3931 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003932 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003933 std::vector<TreePatternNode*> Children;
3934 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003935 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003936 }
3937 ResultNodeOperands.push_back(OpNode);
3938 }
David Blaikiecf195302014-11-17 22:55:41 +00003939 DstPattern = Result.getOnlyTree();
3940 if (!DstPattern->isLeaf())
3941 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3942 ResultNodeOperands,
3943 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003944
David Blaikiecf195302014-11-17 22:55:41 +00003945 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3946 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3947
3948 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003949 Temp.InferAllTypes();
3950
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003951 // A pattern may end up with an "impossible" type, i.e. a situation
3952 // where all types have been eliminated for some node in this pattern.
3953 // This could occur for intrinsics that only make sense for a specific
3954 // value type, and use a specific register class. If, for some mode,
3955 // that register class does not accept that type, the type inference
3956 // will lead to a contradiction, which is not an error however, but
3957 // a sign that this pattern will simply never match.
3958 if (Pattern->getTree(0)->hasPossibleType() &&
3959 Temp.getOnlyTree()->hasPossibleType()) {
3960 ListInit *Preds = CurPattern->getValueAsListInit("Predicates");
3961 int Complexity = CurPattern->getValueAsInt("AddedComplexity");
Daniel Sanders7e523672017-11-11 03:23:44 +00003962 if (PatternRewriter)
3963 PatternRewriter(Pattern);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003964 AddPatternToMatch(
3965 Pattern,
3966 PatternToMatch(
3967 CurPattern, makePredList(Preds), Pattern->getTree(0),
3968 Temp.getOnlyTree(), std::move(InstImpResults), Complexity,
3969 CurPattern->getID()));
3970 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003971 }
3972}
3973
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003974static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
3975 for (const TypeSetByHwMode &VTS : N->getExtTypes())
3976 for (const auto &I : VTS)
3977 Modes.insert(I.first);
3978
3979 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3980 collectModes(Modes, N->getChild(i));
3981}
3982
3983void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
3984 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3985 std::map<unsigned,std::vector<Predicate>> ModeChecks;
3986 std::vector<PatternToMatch> Copy = PatternsToMatch;
3987 PatternsToMatch.clear();
3988
3989 auto AppendPattern = [this,&ModeChecks](PatternToMatch &P, unsigned Mode) {
3990 TreePatternNode *NewSrc = P.SrcPattern->clone();
3991 TreePatternNode *NewDst = P.DstPattern->clone();
3992 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
3993 delete NewSrc;
3994 delete NewDst;
3995 return;
3996 }
3997
3998 std::vector<Predicate> Preds = P.Predicates;
3999 const std::vector<Predicate> &MC = ModeChecks[Mode];
4000 Preds.insert(Preds.end(), MC.begin(), MC.end());
4001 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, NewSrc, NewDst,
4002 P.getDstRegs(), P.getAddedComplexity(),
4003 Record::getNewUID(), Mode);
4004 };
4005
4006 for (PatternToMatch &P : Copy) {
4007 TreePatternNode *SrcP = nullptr, *DstP = nullptr;
4008 if (P.SrcPattern->hasProperTypeByHwMode())
4009 SrcP = P.SrcPattern;
4010 if (P.DstPattern->hasProperTypeByHwMode())
4011 DstP = P.DstPattern;
4012 if (!SrcP && !DstP) {
4013 PatternsToMatch.push_back(P);
4014 continue;
4015 }
4016
4017 std::set<unsigned> Modes;
4018 if (SrcP)
4019 collectModes(Modes, SrcP);
4020 if (DstP)
4021 collectModes(Modes, DstP);
4022
4023 // The predicate for the default mode needs to be constructed for each
4024 // pattern separately.
4025 // Since not all modes must be present in each pattern, if a mode m is
4026 // absent, then there is no point in constructing a check for m. If such
4027 // a check was created, it would be equivalent to checking the default
4028 // mode, except not all modes' predicates would be a part of the checking
4029 // code. The subsequently generated check for the default mode would then
4030 // have the exact same patterns, but a different predicate code. To avoid
4031 // duplicated patterns with different predicate checks, construct the
4032 // default check as a negation of all predicates that are actually present
4033 // in the source/destination patterns.
4034 std::vector<Predicate> DefaultPred;
4035
4036 for (unsigned M : Modes) {
4037 if (M == DefaultMode)
4038 continue;
4039 if (ModeChecks.find(M) != ModeChecks.end())
4040 continue;
4041
4042 // Fill the map entry for this mode.
4043 const HwMode &HM = CGH.getMode(M);
4044 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4045
4046 // Add negations of the HM's predicates to the default predicate.
4047 DefaultPred.emplace_back(Predicate(HM.Features, false));
4048 }
4049
4050 for (unsigned M : Modes) {
4051 if (M == DefaultMode)
4052 continue;
4053 AppendPattern(P, M);
4054 }
4055
4056 bool HasDefault = Modes.count(DefaultMode);
4057 if (HasDefault)
4058 AppendPattern(P, DefaultMode);
4059 }
4060}
4061
4062/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004063typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004064
4065static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4066 if (N->isLeaf()) {
Zachary Turner249dc142017-09-20 18:01:40 +00004067 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004068 DepMap[N->getName()]++;
4069 } else {
4070 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4071 FindDepVarsOf(N->getChild(i), DepMap);
4072 }
4073}
4074
4075/// Find dependent variables within child patterns
4076static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
4077 DepVarMap depcounts;
4078 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004079 for (const auto &Pair : depcounts) {
4080 if (Pair.getValue() > 1)
4081 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004082 }
4083}
4084
4085#ifndef NDEBUG
4086/// Dump the dependent variable set:
4087static void DumpDepVars(MultipleUseVarSet &DepVars) {
4088 if (DepVars.empty()) {
4089 DEBUG(errs() << "<empty set>");
4090 } else {
4091 DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004092 for (const auto &DepVar : DepVars) {
4093 DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004094 }
4095 DEBUG(errs() << "]");
4096 }
4097}
4098#endif
4099
4100
Chris Lattner8cab0212008-01-05 22:25:12 +00004101/// CombineChildVariants - Given a bunch of permutations of each child of the
4102/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004103static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00004104 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
4105 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004106 CodeGenDAGPatterns &CDP,
4107 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004108 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004109 for (const auto &Variants : ChildVariants)
4110 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004111 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004112
Chris Lattner8cab0212008-01-05 22:25:12 +00004113 // The end result is an all-pairs construction of the resultant pattern.
4114 std::vector<unsigned> Idxs;
4115 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004116 bool NotDone;
4117 do {
4118#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00004119 DEBUG(if (!Idxs.empty()) {
4120 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00004121 for (unsigned Idx : Idxs) {
4122 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00004123 }
4124 errs() << "]\n";
4125 });
Scott Michel94420742008-03-05 17:49:05 +00004126#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004127 // Create the variant and add it to the output list.
4128 std::vector<TreePatternNode*> NewChildren;
4129 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4130 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00004131 auto R = llvm::make_unique<TreePatternNode>(
4132 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004133
Chris Lattner8cab0212008-01-05 22:25:12 +00004134 // Copy over properties.
4135 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00004136 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00004137 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00004138 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4139 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004140
Scott Michel94420742008-03-05 17:49:05 +00004141 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004142 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004143 // Scan to see if this pattern has already been emitted. We can get
4144 // duplication due to things like commuting:
4145 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4146 // which are the same pattern. Ignore the dups.
4147 if (R->canPatternMatch(ErrString, CDP) &&
David Majnemer0a16c222016-08-11 21:15:00 +00004148 none_of(OutVariants, [&](TreePatternNode *Variant) {
4149 return R->isIsomorphicTo(Variant, DepVars);
4150 }))
David Blaikiefda69dd2015-11-22 20:11:21 +00004151 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004152
Scott Michel94420742008-03-05 17:49:05 +00004153 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004154 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004155 // [0, 0], [0, 1], [1, 0], [1, 1].
4156 int IdxsIdx;
4157 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4158 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4159 Idxs[IdxsIdx] = 0;
4160 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004161 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004162 }
Scott Michel94420742008-03-05 17:49:05 +00004163 NotDone = (IdxsIdx >= 0);
4164 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004165}
4166
4167/// CombineChildVariants - A helper function for binary operators.
4168///
Jim Grosbach65586fe2010-12-21 16:16:00 +00004169static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00004170 const std::vector<TreePatternNode*> &LHS,
4171 const std::vector<TreePatternNode*> &RHS,
4172 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004173 CodeGenDAGPatterns &CDP,
4174 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004175 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4176 ChildVariants.push_back(LHS);
4177 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004178 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004179}
Chris Lattner8cab0212008-01-05 22:25:12 +00004180
4181
4182static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
4183 std::vector<TreePatternNode *> &Children) {
4184 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4185 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004186
Chris Lattner8cab0212008-01-05 22:25:12 +00004187 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00004188 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004189 N->getTransformFn()) {
4190 Children.push_back(N);
4191 return;
4192 }
4193
4194 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
4195 Children.push_back(N->getChild(0));
4196 else
4197 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
4198
4199 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
4200 Children.push_back(N->getChild(1));
4201 else
4202 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
4203}
4204
4205/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4206/// the (potentially recursive) pattern by using algebraic laws.
4207///
4208static void GenerateVariantsOf(TreePatternNode *N,
4209 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004210 CodeGenDAGPatterns &CDP,
4211 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004212 // We cannot permute leaves or ComplexPattern uses.
4213 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004214 OutVariants.push_back(N);
4215 return;
4216 }
4217
4218 // Look up interesting info about the node.
4219 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4220
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004221 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004222 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004223 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00004224 std::vector<TreePatternNode*> MaximalChildren;
4225 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4226
4227 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4228 // permutations.
4229 if (MaximalChildren.size() == 3) {
4230 // Find the variants of all of our maximal children.
4231 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004232 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4233 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4234 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004235
Chris Lattner8cab0212008-01-05 22:25:12 +00004236 // There are only two ways we can permute the tree:
4237 // (A op B) op C and A op (B op C)
4238 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004239
Chris Lattner8cab0212008-01-05 22:25:12 +00004240 // Generate legal pair permutations of A/B/C.
4241 std::vector<TreePatternNode*> ABVariants;
4242 std::vector<TreePatternNode*> BAVariants;
4243 std::vector<TreePatternNode*> ACVariants;
4244 std::vector<TreePatternNode*> CAVariants;
4245 std::vector<TreePatternNode*> BCVariants;
4246 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00004247 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4248 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4249 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4250 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4251 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4252 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004253
4254 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00004255 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4256 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4257 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4258 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4259 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4260 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004261
4262 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00004263 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4264 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4265 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4266 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4267 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4268 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004269 return;
4270 }
4271 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004272
Chris Lattner8cab0212008-01-05 22:25:12 +00004273 // Compute permutations of all children.
4274 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4275 ChildVariants.resize(N->getNumChildren());
4276 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00004277 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004278
4279 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00004280 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004281
4282 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004283 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4284 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004285 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004286 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004287 // Don't count children which are actually register references.
4288 unsigned NC = 0;
4289 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4290 TreePatternNode *Child = N->getChild(i);
4291 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00004292 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004293 Record *RR = DI->getDef();
4294 if (RR->isSubClassOf("Register"))
4295 continue;
4296 }
4297 NC++;
4298 }
4299 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004300 if (isCommIntrinsic) {
4301 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4302 // operands are the commutative operands, and there might be more operands
4303 // after those.
4304 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004305 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00004306 std::vector<std::vector<TreePatternNode*> > Variants;
4307 Variants.push_back(ChildVariants[0]); // Intrinsic id.
4308 Variants.push_back(ChildVariants[2]);
4309 Variants.push_back(ChildVariants[1]);
4310 for (unsigned i = 3; i != NC; ++i)
4311 Variants.push_back(ChildVariants[i]);
4312 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004313 } else if (NC == N->getNumChildren()) {
4314 std::vector<std::vector<TreePatternNode*> > Variants;
4315 Variants.push_back(ChildVariants[1]);
4316 Variants.push_back(ChildVariants[0]);
4317 for (unsigned i = 2; i != NC; ++i)
4318 Variants.push_back(ChildVariants[i]);
4319 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4320 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004321 }
4322}
4323
4324
4325// GenerateVariants - Generate variants. For example, commutative patterns can
4326// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004327void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00004328 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004329
Chris Lattner8cab0212008-01-05 22:25:12 +00004330 // Loop over all of the patterns we've collected, checking to see if we can
4331 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004332 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004333 // the .td file having to contain tons of variants of instructions.
4334 //
4335 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4336 // intentionally do not reconsider these. Any variants of added patterns have
4337 // already been added.
4338 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00004339 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00004340 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00004341 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004342 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00004343 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00004344 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00004345 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00004346 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00004347 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004348
4349 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00004350 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004351 continue;
4352
Chris Lattner34822f62009-08-23 04:44:11 +00004353 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00004354 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00004355 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004356
4357 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4358 TreePatternNode *Variant = Variants[v];
4359
Chris Lattner34822f62009-08-23 04:44:11 +00004360 DEBUG(errs() << " VAR#" << v << ": ";
4361 Variant->dump();
4362 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004363
Chris Lattner8cab0212008-01-05 22:25:12 +00004364 // Scan to see if an instruction or explicit pattern already matches this.
4365 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004366 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004367 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004368 if (PatternsToMatch[i].getPredicates() !=
4369 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00004370 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004371 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004372 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4373 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00004374 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004375 AlreadyExists = true;
4376 break;
4377 }
4378 }
4379 // If we already have it, ignore the variant.
4380 if (AlreadyExists) continue;
4381
4382 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004383 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004384 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4385 Variant, PatternsToMatch[i].getDstPattern(),
4386 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004387 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00004388 }
4389
Chris Lattner34822f62009-08-23 04:44:11 +00004390 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004391 }
4392}