blob: d23b45aab79648b16754ee154508647e5a6384f7 [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()) {
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000888 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
889 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
890 !isAtomicOrderingAcquireRelease() &&
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000891 !isAtomicOrderingSequentiallyConsistent() &&
892 !isAtomicOrderingAcquireOrStronger() &&
893 !isAtomicOrderingReleaseOrStronger() &&
894 !isAtomicOrderingWeakerThanAcquire() &&
895 !isAtomicOrderingWeakerThanRelease())
Daniel Sanders87d196c2017-11-13 22:26:13 +0000896 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
897 "IsAtomic cannot be used by itself");
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000898 } else {
899 if (isAtomicOrderingMonotonic())
900 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
901 "IsAtomicOrderingMonotonic requires IsAtomic");
902 if (isAtomicOrderingAcquire())
903 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
904 "IsAtomicOrderingAcquire requires IsAtomic");
905 if (isAtomicOrderingRelease())
906 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
907 "IsAtomicOrderingRelease requires IsAtomic");
908 if (isAtomicOrderingAcquireRelease())
909 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
910 "IsAtomicOrderingAcquireRelease requires IsAtomic");
911 if (isAtomicOrderingSequentiallyConsistent())
912 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
913 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000914 if (isAtomicOrderingAcquireOrStronger())
915 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
916 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
917 if (isAtomicOrderingReleaseOrStronger())
918 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
919 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
920 if (isAtomicOrderingWeakerThanAcquire())
921 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
922 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
Daniel Sanders87d196c2017-11-13 22:26:13 +0000923 }
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000924
Daniel Sanders87d196c2017-11-13 22:26:13 +0000925 if (isLoad() || isStore() || isAtomic()) {
926 StringRef SDNodeName =
927 isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
928
929 Record *MemoryVT = getMemoryVT();
930
931 if (MemoryVT)
932 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
933 MemoryVT->getName() + ") return false;\n")
934 .str();
935 }
936
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000937 if (isAtomic() && isAtomicOrderingMonotonic())
938 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
939 "AtomicOrdering::Monotonic) return false;\n";
940 if (isAtomic() && isAtomicOrderingAcquire())
941 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
942 "AtomicOrdering::Acquire) return false;\n";
943 if (isAtomic() && isAtomicOrderingRelease())
944 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
945 "AtomicOrdering::Release) return false;\n";
946 if (isAtomic() && isAtomicOrderingAcquireRelease())
947 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
948 "AtomicOrdering::AcquireRelease) return false;\n";
949 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
950 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
951 "AtomicOrdering::SequentiallyConsistent) return false;\n";
952
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000953 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
954 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
955 "return false;\n";
956 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
957 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
958 "return false;\n";
959
960 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
961 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
962 "return false;\n";
963 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
964 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
965 "return false;\n";
966
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000967 if (isLoad() || isStore()) {
968 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
969
970 if (isUnindexed())
971 Code += ("if (cast<" + SDNodeName +
972 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
973 "return false;\n")
974 .str();
975
976 if (isLoad()) {
977 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
978 isZeroExtLoad()) > 1)
979 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
980 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
981 "IsZeroExtLoad are mutually exclusive");
982 if (isNonExtLoad())
983 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
984 "ISD::NON_EXTLOAD) return false;\n";
985 if (isAnyExtLoad())
986 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
987 "return false;\n";
988 if (isSignExtLoad())
989 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
990 "return false;\n";
991 if (isZeroExtLoad())
992 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
993 "return false;\n";
994 } else {
995 if ((isNonTruncStore() + isTruncStore()) > 1)
996 PrintFatalError(
997 getOrigPatFragRecord()->getRecord()->getLoc(),
998 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
999 if (isNonTruncStore())
1000 Code +=
1001 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1002 if (isTruncStore())
1003 Code +=
1004 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1005 }
1006
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001007 Record *ScalarMemoryVT = getScalarMemoryVT();
1008
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001009 if (ScalarMemoryVT)
1010 Code += ("if (cast<" + SDNodeName +
1011 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1012 ScalarMemoryVT->getName() + ") return false;\n")
1013 .str();
1014 }
1015
1016 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1017
1018 Code += PredicateCode;
1019
1020 if (PredicateCode.empty() && !Code.empty())
1021 Code += "return true;\n";
1022
1023 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +00001024}
1025
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001026bool TreePredicateFn::hasImmCode() const {
1027 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1028}
1029
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001030std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00001031 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001032}
1033
Daniel Sanders649c5852017-10-13 20:42:18 +00001034bool TreePredicateFn::immCodeUsesAPInt() const {
1035 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1036}
1037
1038bool TreePredicateFn::immCodeUsesAPFloat() const {
1039 bool Unset;
1040 // The return value will be false when IsAPFloat is unset.
1041 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1042 Unset);
1043}
1044
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001045bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1046 bool Value) const {
1047 bool Unset;
1048 bool Result =
1049 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1050 if (Unset)
1051 return false;
1052 return Result == Value;
1053}
1054bool TreePredicateFn::isLoad() const {
1055 return isPredefinedPredicateEqualTo("IsLoad", true);
1056}
1057bool TreePredicateFn::isStore() const {
1058 return isPredefinedPredicateEqualTo("IsStore", true);
1059}
Daniel Sanders87d196c2017-11-13 22:26:13 +00001060bool TreePredicateFn::isAtomic() const {
1061 return isPredefinedPredicateEqualTo("IsAtomic", true);
1062}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001063bool TreePredicateFn::isUnindexed() const {
1064 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1065}
1066bool TreePredicateFn::isNonExtLoad() const {
1067 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1068}
1069bool TreePredicateFn::isAnyExtLoad() const {
1070 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1071}
1072bool TreePredicateFn::isSignExtLoad() const {
1073 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1074}
1075bool TreePredicateFn::isZeroExtLoad() const {
1076 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1077}
1078bool TreePredicateFn::isNonTruncStore() const {
1079 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1080}
1081bool TreePredicateFn::isTruncStore() const {
1082 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1083}
Daniel Sanders6d9d30a2017-11-13 23:03:47 +00001084bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1085 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1086}
1087bool TreePredicateFn::isAtomicOrderingAcquire() const {
1088 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1089}
1090bool TreePredicateFn::isAtomicOrderingRelease() const {
1091 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1092}
1093bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1094 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1095}
1096bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1097 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1098 true);
1099}
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001100bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1101 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1102}
1103bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1104 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1105}
1106bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1107 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1108}
1109bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1110 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1111}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001112Record *TreePredicateFn::getMemoryVT() const {
1113 Record *R = getOrigPatFragRecord()->getRecord();
1114 if (R->isValueUnset("MemoryVT"))
1115 return nullptr;
1116 return R->getValueAsDef("MemoryVT");
1117}
1118Record *TreePredicateFn::getScalarMemoryVT() const {
1119 Record *R = getOrigPatFragRecord()->getRecord();
1120 if (R->isValueUnset("ScalarMemoryVT"))
1121 return nullptr;
1122 return R->getValueAsDef("ScalarMemoryVT");
1123}
1124
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001125StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001126 if (immCodeUsesAPInt())
1127 return "const APInt &";
1128 if (immCodeUsesAPFloat())
1129 return "const APFloat &";
1130 return "int64_t";
1131}
Chris Lattner514e2922011-04-17 21:38:24 +00001132
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001133StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001134 if (immCodeUsesAPInt())
1135 return "APInt";
1136 else if (immCodeUsesAPFloat())
1137 return "APFloat";
1138 return "I64";
1139}
1140
Chris Lattner514e2922011-04-17 21:38:24 +00001141/// isAlwaysTrue - Return true if this is a noop predicate.
1142bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001143 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001144}
1145
1146/// Return the name to use in the generated code to reference this, this is
1147/// "Predicate_foo" if from a pattern fragment "foo".
1148std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001149 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001150}
1151
1152/// getCodeToRunOnSDNode - Return the code for the function body that
1153/// evaluates this predicate. The argument is expected to be in "Node",
1154/// not N. This handles casting and conversion to a concrete node type as
1155/// appropriate.
1156std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001157 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001158 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001159 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001160 if (isLoad())
1161 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1162 "IsLoad cannot be used with ImmLeaf or its subclasses");
1163 if (isStore())
1164 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1165 "IsStore cannot be used with ImmLeaf or its subclasses");
1166 if (isUnindexed())
1167 PrintFatalError(
1168 getOrigPatFragRecord()->getRecord()->getLoc(),
1169 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1170 if (isNonExtLoad())
1171 PrintFatalError(
1172 getOrigPatFragRecord()->getRecord()->getLoc(),
1173 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1174 if (isAnyExtLoad())
1175 PrintFatalError(
1176 getOrigPatFragRecord()->getRecord()->getLoc(),
1177 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1178 if (isSignExtLoad())
1179 PrintFatalError(
1180 getOrigPatFragRecord()->getRecord()->getLoc(),
1181 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1182 if (isZeroExtLoad())
1183 PrintFatalError(
1184 getOrigPatFragRecord()->getRecord()->getLoc(),
1185 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1186 if (isNonTruncStore())
1187 PrintFatalError(
1188 getOrigPatFragRecord()->getRecord()->getLoc(),
1189 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1190 if (isTruncStore())
1191 PrintFatalError(
1192 getOrigPatFragRecord()->getRecord()->getLoc(),
1193 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1194 if (getMemoryVT())
1195 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1196 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1197 if (getScalarMemoryVT())
1198 PrintFatalError(
1199 getOrigPatFragRecord()->getRecord()->getLoc(),
1200 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1201
1202 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001203 if (immCodeUsesAPFloat())
1204 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1205 else if (immCodeUsesAPInt())
1206 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1207 else
1208 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001209 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001210 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001211
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001212 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001213 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001214 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +00001215 if (PatFragRec->getOnlyTree()->isLeaf())
1216 ClassName = "SDNode";
1217 else {
1218 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1219 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1220 }
1221 std::string Result;
1222 if (ClassName == "SDNode")
1223 Result = " SDNode *N = Node;\n";
1224 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001225 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001226
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001227 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +00001228}
1229
Chris Lattner8cab0212008-01-05 22:25:12 +00001230//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001231// PatternToMatch implementation
1232//
1233
Chris Lattner05925fe2010-03-29 01:40:38 +00001234/// getPatternSize - Return the 'size' of this pattern. We want to match large
1235/// patterns before small ones. This is used to determine the size of a
1236/// pattern.
1237static unsigned getPatternSize(const TreePatternNode *P,
1238 const CodeGenDAGPatterns &CGP) {
1239 unsigned Size = 3; // The node itself.
1240 // If the root node is a ConstantSDNode, increases its size.
1241 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +00001242 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001243 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001244
Simon Pilgrim40687012017-09-26 12:59:01 +00001245 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001246 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001247 // We don't want to count any children twice, so return early.
1248 return Size;
1249 }
1250
Chris Lattner05925fe2010-03-29 01:40:38 +00001251 // If this node has some predicate function that must match, it adds to the
1252 // complexity of this node.
1253 if (!P->getPredicateFns().empty())
1254 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001255
Chris Lattner05925fe2010-03-29 01:40:38 +00001256 // Count children in the count if they are also nodes.
1257 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
Simon Pilgrima932bfc2017-09-27 10:03:17 +00001258 const TreePatternNode *Child = P->getChild(i);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001259 if (!Child->isLeaf() && Child->getNumTypes()) {
1260 const TypeSetByHwMode &T0 = Child->getType(0);
1261 // At this point, all variable type sets should be simple, i.e. only
1262 // have a default mode.
1263 if (T0.getMachineValueType() != MVT::Other) {
1264 Size += getPatternSize(Child, CGP);
1265 continue;
1266 }
1267 }
1268 if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001269 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001270 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1271 else if (Child->getComplexPatternInfo(CGP))
1272 Size += getPatternSize(Child, CGP);
1273 else if (!Child->getPredicateFns().empty())
1274 ++Size;
1275 }
1276 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001277
Chris Lattner05925fe2010-03-29 01:40:38 +00001278 return Size;
1279}
1280
1281/// Compute the complexity metric for the input pattern. This roughly
1282/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001283int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001284getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1285 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1286}
1287
Dan Gohman49e19e92008-08-22 00:20:26 +00001288/// getPredicateCheck - Return a single string containing all of this
1289/// pattern's predicates concatenated with "&&" operators.
1290///
1291std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001292 SmallVector<const Predicate*,4> PredList;
1293 for (const Predicate &P : Predicates)
1294 PredList.push_back(&P);
1295 std::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +00001296
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001297 std::string Check;
1298 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1299 if (i != 0)
1300 Check += " && ";
1301 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001302 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001303 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001304}
1305
1306//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001307// SDTypeConstraint implementation
1308//
1309
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001310SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001311 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001312
Chris Lattner8cab0212008-01-05 22:25:12 +00001313 if (R->isSubClassOf("SDTCisVT")) {
1314 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001315 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1316 for (const auto &P : VVT)
1317 if (P.second == MVT::isVoid)
1318 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001319 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1320 ConstraintType = SDTCisPtrTy;
1321 } else if (R->isSubClassOf("SDTCisInt")) {
1322 ConstraintType = SDTCisInt;
1323 } else if (R->isSubClassOf("SDTCisFP")) {
1324 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001325 } else if (R->isSubClassOf("SDTCisVec")) {
1326 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001327 } else if (R->isSubClassOf("SDTCisSameAs")) {
1328 ConstraintType = SDTCisSameAs;
1329 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1330 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1331 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001332 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001333 R->getValueAsInt("OtherOperandNum");
1334 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1335 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001336 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001337 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001338 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1339 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001340 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001341 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1342 ConstraintType = SDTCisSubVecOfVec;
1343 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1344 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001345 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1346 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001347 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1348 for (const auto &P : VVT) {
1349 MVT T = P.second;
1350 if (T.isVector())
1351 PrintFatalError(R->getLoc(),
1352 "Cannot use vector type as SDTCVecEltisVT");
1353 if (!T.isInteger() && !T.isFloatingPoint())
1354 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1355 "as SDTCVecEltisVT");
1356 }
Craig Topper0be34582015-03-05 07:11:34 +00001357 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1358 ConstraintType = SDTCisSameNumEltsAs;
1359 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1360 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001361 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1362 ConstraintType = SDTCisSameSizeAs;
1363 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1364 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001365 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001366 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001367 }
1368}
1369
1370/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001371/// N, and the result number in ResNo.
1372static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1373 const SDNodeInfo &NodeInfo,
1374 unsigned &ResNo) {
1375 unsigned NumResults = NodeInfo.getNumResults();
1376 if (OpNo < NumResults) {
1377 ResNo = OpNo;
1378 return N;
1379 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001380
Chris Lattner2db7aba2010-03-19 21:56:21 +00001381 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001382
Chris Lattner2db7aba2010-03-19 21:56:21 +00001383 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001384 std::string S;
1385 raw_string_ostream OS(S);
1386 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001387 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +00001388 N->print(OS);
1389 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001390 }
1391
Chris Lattner2db7aba2010-03-19 21:56:21 +00001392 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001393}
1394
1395/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1396/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001397/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001398bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1399 const SDNodeInfo &NodeInfo,
1400 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001401 if (TP.hasError())
1402 return false;
1403
Chris Lattner2db7aba2010-03-19 21:56:21 +00001404 unsigned ResNo = 0; // The result number being referenced.
1405 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001406 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001407
Chris Lattner8cab0212008-01-05 22:25:12 +00001408 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001409 case SDTCisVT:
1410 // Operand must be a particular type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001411 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001412 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001413 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001414 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001415 case SDTCisInt:
1416 // Require it to be one of the legal integer VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001417 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001418 case SDTCisFP:
1419 // Require it to be one of the legal fp VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001420 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001421 case SDTCisVec:
1422 // Require it to be one of the legal vector VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001423 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001424 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001425 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001426 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001427 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001428 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1429 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001430 }
1431 case SDTCisVTSmallerThanOp: {
1432 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1433 // have an integer type that is smaller than the VT.
1434 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001435 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001436 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001437 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001438 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001439 return false;
1440 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001441 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1442 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1443 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1444 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001445
Chris Lattner2db7aba2010-03-19 21:56:21 +00001446 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001447 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001448 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1449 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001450
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001451 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001452 }
1453 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001454 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001455 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001456 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1457 BResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001458 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1459 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001460 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001461 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001462 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001463 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001464 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1465 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001466 // Filter vector types out of VecOperand that don't have the right element
1467 // type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001468 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1469 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001470 }
David Greene127fd1d2011-01-24 20:53:18 +00001471 case SDTCisSubVecOfVec: {
1472 unsigned VResNo = 0;
1473 TreePatternNode *BigVecOperand =
1474 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1475 VResNo);
1476
1477 // Filter vector types out of BigVecOperand that don't have the
1478 // right subvector type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001479 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1480 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001481 }
Craig Topper0be34582015-03-05 07:11:34 +00001482 case SDTCVecEltisVT: {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001483 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001484 }
1485 case SDTCisSameNumEltsAs: {
1486 unsigned OResNo = 0;
1487 TreePatternNode *OtherNode =
1488 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1489 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001490 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1491 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001492 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001493 case SDTCisSameSizeAs: {
1494 unsigned OResNo = 0;
1495 TreePatternNode *OtherNode =
1496 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1497 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001498 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1499 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001500 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001501 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001502 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001503}
1504
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001505// Update the node type to match an instruction operand or result as specified
1506// in the ins or outs lists on the instruction definition. Return true if the
1507// type was actually changed.
1508bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1509 Record *Operand,
1510 TreePattern &TP) {
1511 // The 'unknown' operand indicates that types should be inferred from the
1512 // context.
1513 if (Operand->isSubClassOf("unknown_class"))
1514 return false;
1515
1516 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001517 if (Operand->isSubClassOf("Operand")) {
1518 Record *R = Operand->getValueAsDef("Type");
1519 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1520 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1521 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001522
1523 // PointerLikeRegClass has a type that is determined at runtime.
1524 if (Operand->isSubClassOf("PointerLikeRegClass"))
1525 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1526
1527 // Both RegisterClass and RegisterOperand operands derive their types from a
1528 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001529 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001530 if (Operand->isSubClassOf("RegisterClass"))
1531 RC = Operand;
1532 else if (Operand->isSubClassOf("RegisterOperand"))
1533 RC = Operand->getValueAsDef("RegClass");
1534
1535 assert(RC && "Unknown operand type");
1536 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1537 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1538}
1539
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001540bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1541 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1542 if (!TP.getInfer().isConcrete(Types[i], true))
1543 return true;
1544 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1545 if (getChild(i)->ContainsUnresolvedType(TP))
1546 return true;
1547 return false;
1548}
1549
1550bool TreePatternNode::hasProperTypeByHwMode() const {
1551 for (const TypeSetByHwMode &S : Types)
1552 if (!S.isDefaultOnly())
1553 return true;
1554 for (TreePatternNode *C : Children)
1555 if (C->hasProperTypeByHwMode())
1556 return true;
1557 return false;
1558}
1559
1560bool TreePatternNode::hasPossibleType() const {
1561 for (const TypeSetByHwMode &S : Types)
1562 if (!S.isPossible())
1563 return false;
1564 for (TreePatternNode *C : Children)
1565 if (!C->hasPossibleType())
1566 return false;
1567 return true;
1568}
1569
1570bool TreePatternNode::setDefaultMode(unsigned Mode) {
1571 for (TypeSetByHwMode &S : Types) {
1572 S.makeSimple(Mode);
1573 // Check if the selected mode had a type conflict.
1574 if (S.get(DefaultMode).empty())
1575 return false;
1576 }
1577 for (TreePatternNode *C : Children)
1578 if (!C->setDefaultMode(Mode))
1579 return false;
1580 return true;
1581}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001582
Chris Lattner8cab0212008-01-05 22:25:12 +00001583//===----------------------------------------------------------------------===//
1584// SDNodeInfo implementation
1585//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001586SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001587 EnumName = R->getValueAsString("Opcode");
1588 SDClassName = R->getValueAsString("SDClass");
1589 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1590 NumResults = TypeProfile->getValueAsInt("NumResults");
1591 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001592
Chris Lattner8cab0212008-01-05 22:25:12 +00001593 // Parse the properties.
Matt Arsenault303327d2017-12-20 19:36:28 +00001594 Properties = parseSDPatternOperatorProperties(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001595
Chris Lattner8cab0212008-01-05 22:25:12 +00001596 // Parse the type constraints.
1597 std::vector<Record*> ConstraintList =
1598 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001599 for (Record *R : ConstraintList)
1600 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001601}
1602
Chris Lattner99e53b32010-02-28 00:22:30 +00001603/// getKnownType - If the type constraints on this node imply a fixed type
1604/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001605/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001606MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001607 unsigned NumResults = getNumResults();
1608 assert(NumResults <= 1 &&
1609 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001610 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001611
Craig Topper306cb122015-11-22 20:46:24 +00001612 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001613 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001614 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001615 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001616
Craig Topper306cb122015-11-22 20:46:24 +00001617 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001618 default: break;
1619 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001620 if (Constraint.VVT.isSimple())
1621 return Constraint.VVT.getSimple().SimpleTy;
1622 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001623 case SDTypeConstraint::SDTCisPtrTy:
1624 return MVT::iPTR;
1625 }
1626 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001627 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001628}
1629
Chris Lattner8cab0212008-01-05 22:25:12 +00001630//===----------------------------------------------------------------------===//
1631// TreePatternNode implementation
1632//
1633
1634TreePatternNode::~TreePatternNode() {
1635#if 0 // FIXME: implement refcounted tree nodes!
1636 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1637 delete getChild(i);
1638#endif
1639}
1640
Chris Lattnerf1447252010-03-19 21:37:09 +00001641static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1642 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001643 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001644 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001645
Chris Lattner2109cb42010-03-22 20:56:36 +00001646 if (Operator->isSubClassOf("Intrinsic"))
1647 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001648
Chris Lattnerf1447252010-03-19 21:37:09 +00001649 if (Operator->isSubClassOf("SDNode"))
1650 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001651
Chris Lattnerf1447252010-03-19 21:37:09 +00001652 if (Operator->isSubClassOf("PatFrag")) {
1653 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1654 // the forward reference case where one pattern fragment references another
1655 // before it is processed.
1656 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1657 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001658
Chris Lattnerf1447252010-03-19 21:37:09 +00001659 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001660 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001661 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001662 if (Tree)
1663 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1664 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001665 assert(Op && "Invalid Fragment");
1666 return GetNumNodeResults(Op, CDP);
1667 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001668
Chris Lattnerf1447252010-03-19 21:37:09 +00001669 if (Operator->isSubClassOf("Instruction")) {
1670 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001671
Craig Topper3a8eb892015-03-20 05:09:06 +00001672 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1673
1674 // Subtract any defaulted outputs.
1675 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1676 Record *OperandNode = InstInfo.Operands[i].Rec;
1677
1678 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1679 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1680 --NumDefsToAdd;
1681 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001682
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001683 // Add on one implicit def if it has a resolvable type.
1684 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1685 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001686 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001687 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001688
Chris Lattnerf1447252010-03-19 21:37:09 +00001689 if (Operator->isSubClassOf("SDNodeXForm"))
1690 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001691
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001692 if (Operator->isSubClassOf("ValueType"))
1693 return 1; // A type-cast of one result.
1694
Tim Northoverc807a172014-05-20 11:52:46 +00001695 if (Operator->isSubClassOf("ComplexPattern"))
1696 return 1;
1697
Matthias Braun8c209aa2017-01-28 02:02:38 +00001698 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001699 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001700}
1701
1702void TreePatternNode::print(raw_ostream &OS) const {
1703 if (isLeaf())
1704 OS << *getLeafValue();
1705 else
1706 OS << '(' << getOperator()->getName();
1707
Zachary Turner249dc142017-09-20 18:01:40 +00001708 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1709 OS << ':';
1710 getExtType(i).writeToStream(OS);
1711 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001712
1713 if (!isLeaf()) {
1714 if (getNumChildren() != 0) {
1715 OS << " ";
1716 getChild(0)->print(OS);
1717 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1718 OS << ", ";
1719 getChild(i)->print(OS);
1720 }
1721 }
1722 OS << ")";
1723 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001724
Craig Topper306cb122015-11-22 20:46:24 +00001725 for (const TreePredicateFn &Pred : PredicateFns)
1726 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001727 if (TransformFn)
1728 OS << "<<X:" << TransformFn->getName() << ">>";
1729 if (!getName().empty())
1730 OS << ":$" << getName();
1731
1732}
1733void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001734 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001735}
1736
Scott Michel94420742008-03-05 17:49:05 +00001737/// isIsomorphicTo - Return true if this node is recursively
1738/// isomorphic to the specified node. For this comparison, the node's
1739/// entire state is considered. The assigned name is ignored, since
1740/// nodes with differing names are considered isomorphic. However, if
1741/// the assigned name is present in the dependent variable set, then
1742/// the assigned name is considered significant and the node is
1743/// isomorphic if the names match.
1744bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1745 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001746 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001747 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001748 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001749 getTransformFn() != N->getTransformFn())
1750 return false;
1751
1752 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001753 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1754 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001755 return ((DI->getDef() == NDI->getDef())
1756 && (DepVars.find(getName()) == DepVars.end()
1757 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001758 }
1759 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001760 return getLeafValue() == N->getLeafValue();
1761 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001762
Chris Lattner8cab0212008-01-05 22:25:12 +00001763 if (N->getOperator() != getOperator() ||
1764 N->getNumChildren() != getNumChildren()) return false;
1765 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001766 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001767 return false;
1768 return true;
1769}
1770
1771/// clone - Make a copy of this tree and all of its children.
1772///
1773TreePatternNode *TreePatternNode::clone() const {
1774 TreePatternNode *New;
1775 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001776 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001777 } else {
1778 std::vector<TreePatternNode*> CChildren;
1779 CChildren.reserve(Children.size());
1780 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1781 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001782 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001783 }
1784 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001785 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001786 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001787 New->setTransformFn(getTransformFn());
1788 return New;
1789}
1790
Chris Lattner53c39ba2010-02-14 22:22:58 +00001791/// RemoveAllTypes - Recursively strip all the types of this tree.
1792void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001793 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001794 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001795 if (isLeaf()) return;
1796 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1797 getChild(i)->RemoveAllTypes();
1798}
1799
1800
Chris Lattner8cab0212008-01-05 22:25:12 +00001801/// SubstituteFormalArguments - Replace the formal arguments in this tree
1802/// with actual values specified by ArgMap.
1803void TreePatternNode::
1804SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1805 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001806
Chris Lattner8cab0212008-01-05 22:25:12 +00001807 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1808 TreePatternNode *Child = getChild(i);
1809 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001810 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001811 // Note that, when substituting into an output pattern, Val might be an
1812 // UnsetInit.
1813 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1814 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001815 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001816 TreePatternNode *NewChild = ArgMap[Child->getName()];
1817 assert(NewChild && "Couldn't find formal argument!");
1818 assert((Child->getPredicateFns().empty() ||
1819 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1820 "Non-empty child predicate clobbered!");
1821 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001822 }
1823 } else {
1824 getChild(i)->SubstituteFormalArguments(ArgMap);
1825 }
1826 }
1827}
1828
1829
1830/// InlinePatternFragments - If this pattern refers to any pattern
1831/// fragments, inline them into place, giving us a pattern without any
1832/// PatFrag references.
1833TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001834 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001835 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001836
1837 if (isLeaf())
1838 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001839 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001840
Chris Lattner8cab0212008-01-05 22:25:12 +00001841 if (!Op->isSubClassOf("PatFrag")) {
1842 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001843 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1844 TreePatternNode *Child = getChild(i);
1845 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1846
1847 assert((Child->getPredicateFns().empty() ||
1848 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1849 "Non-empty child predicate clobbered!");
1850
1851 setChild(i, NewChild);
1852 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001853 return this;
1854 }
1855
1856 // Otherwise, we found a reference to a fragment. First, look up its
1857 // TreePattern record.
1858 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001859
Chris Lattner8cab0212008-01-05 22:25:12 +00001860 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001861 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001862 TP.error("'" + Op->getName() + "' fragment requires " +
1863 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001864 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001865 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001866
1867 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1868
Chris Lattner514e2922011-04-17 21:38:24 +00001869 TreePredicateFn PredFn(Frag);
1870 if (!PredFn.isAlwaysTrue())
1871 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001872
Chris Lattner8cab0212008-01-05 22:25:12 +00001873 // Resolve formal arguments to their actual value.
1874 if (Frag->getNumArgs()) {
1875 // Compute the map of formal to actual arguments.
1876 std::map<std::string, TreePatternNode*> ArgMap;
1877 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1878 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001879
Chris Lattner8cab0212008-01-05 22:25:12 +00001880 FragTree->SubstituteFormalArguments(ArgMap);
1881 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001882
Chris Lattner8cab0212008-01-05 22:25:12 +00001883 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001884 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1885 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001886
1887 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001888 for (const TreePredicateFn &Pred : getPredicateFns())
1889 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001890
Chris Lattner8cab0212008-01-05 22:25:12 +00001891 // Get a new copy of this fragment to stitch into here.
1892 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001893
Chris Lattner2e253b42008-06-30 03:02:03 +00001894 // The fragment we inlined could have recursive inlining that is needed. See
1895 // if there are any pattern fragments in it and inline them as needed.
1896 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001897}
1898
1899/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001900/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001901/// references from the register file information, for example.
1902///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001903/// When Unnamed is set, return the type of a DAG operand with no name, such as
1904/// the F8RC register class argument in:
1905///
1906/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1907///
1908/// When Unnamed is false, return the type of a named DAG operand such as the
1909/// GPR:$src operand above.
1910///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001911static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1912 bool NotRegisters,
1913 bool Unnamed,
1914 TreePattern &TP) {
1915 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1916
Owen Andersona84be6c2011-06-27 21:06:21 +00001917 // Check to see if this is a register operand.
1918 if (R->isSubClassOf("RegisterOperand")) {
1919 assert(ResNo == 0 && "Regoperand ref only has one result!");
1920 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001921 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00001922 Record *RegClass = R->getValueAsDef("RegClass");
1923 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001924 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00001925 }
1926
Chris Lattnercabe0372010-03-15 06:00:16 +00001927 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001928 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001929 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001930 // An unnamed register class represents itself as an i32 immediate, for
1931 // example on a COPY_TO_REGCLASS instruction.
1932 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001933 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001934
1935 // In a named operand, the register class provides the possible set of
1936 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001937 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001938 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00001939 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001940 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001941 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001942
Chris Lattner6070ee22010-03-23 23:50:31 +00001943 if (R->isSubClassOf("PatFrag")) {
1944 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001945 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001946 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001947 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001948
Chris Lattner6070ee22010-03-23 23:50:31 +00001949 if (R->isSubClassOf("Register")) {
1950 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001951 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001952 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001953 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001954 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001955 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001956
1957 if (R->isSubClassOf("SubRegIndex")) {
1958 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001959 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001960 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001961
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001962 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001963 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001964 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1965 //
1966 // (sext_inreg GPR:$src, i16)
1967 // ~~~
1968 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001969 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001970 // With a name, the ValueType simply provides the type of the named
1971 // variable.
1972 //
1973 // (sext_inreg i32:$src, i16)
1974 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001975 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001976 return TypeSetByHwMode(); // Unknown.
1977 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1978 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001979 }
1980
1981 if (R->isSubClassOf("CondCode")) {
1982 assert(ResNo == 0 && "This node only has one result!");
1983 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001984 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00001985 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001986
Chris Lattner6070ee22010-03-23 23:50:31 +00001987 if (R->isSubClassOf("ComplexPattern")) {
1988 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001989 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001990 return TypeSetByHwMode(); // Unknown.
1991 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00001992 }
1993 if (R->isSubClassOf("PointerLikeRegClass")) {
1994 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001995 TypeSetByHwMode VTS(MVT::iPTR);
1996 TP.getInfer().expandOverloads(VTS);
1997 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00001998 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001999
Chris Lattner6070ee22010-03-23 23:50:31 +00002000 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2001 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002002 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002003 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002004 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002005
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002006 if (R->isSubClassOf("Operand")) {
2007 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2008 Record *T = R->getValueAsDef("Type");
2009 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2010 }
Tim Northoverc807a172014-05-20 11:52:46 +00002011
Chris Lattner8cab0212008-01-05 22:25:12 +00002012 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002013 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00002014}
2015
Chris Lattner89c65662008-01-06 05:36:50 +00002016
2017/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2018/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2019const CodeGenIntrinsic *TreePatternNode::
2020getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2021 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2022 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2023 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00002024 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002025
Sean Silva88eb8dd2012-10-10 20:24:47 +00002026 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00002027 return &CDP.getIntrinsicInfo(IID);
2028}
2029
Chris Lattner53c39ba2010-02-14 22:22:58 +00002030/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2031/// return the ComplexPattern information, otherwise return null.
2032const ComplexPattern *
2033TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00002034 Record *Rec;
2035 if (isLeaf()) {
2036 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2037 if (!DI)
2038 return nullptr;
2039 Rec = DI->getDef();
2040 } else
2041 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002042
Tim Northoverc807a172014-05-20 11:52:46 +00002043 if (!Rec->isSubClassOf("ComplexPattern"))
2044 return nullptr;
2045 return &CGP.getComplexPattern(Rec);
2046}
2047
2048unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2049 // A ComplexPattern specifically declares how many results it fills in.
2050 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2051 return CP->getNumOperands();
2052
2053 // If MIOperandInfo is specified, that gives the count.
2054 if (isLeaf()) {
2055 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2056 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2057 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2058 if (MIOps->getNumArgs())
2059 return MIOps->getNumArgs();
2060 }
2061 }
2062
2063 // Otherwise there is just one result.
2064 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00002065}
2066
2067/// NodeHasProperty - Return true if this node has the specified property.
2068bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002069 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002070 if (isLeaf()) {
2071 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2072 return CP->hasProperty(Property);
Matt Arsenault303327d2017-12-20 19:36:28 +00002073
Chris Lattner53c39ba2010-02-14 22:22:58 +00002074 return false;
2075 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002076
Matt Arsenault303327d2017-12-20 19:36:28 +00002077 if (Property != SDNPHasChain) {
2078 // The chain proprety is already present on the different intrinsic node
2079 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2080 // on the intrinsic. Anything else is specific to the individual intrinsic.
2081 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2082 return Int->hasProperty(Property);
2083 }
2084
2085 if (!Operator->isSubClassOf("SDPatternOperator"))
2086 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002087
Chris Lattner53c39ba2010-02-14 22:22:58 +00002088 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2089}
2090
2091
2092
2093
2094/// TreeHasProperty - Return true if any node in this tree has the specified
2095/// property.
2096bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002097 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002098 if (NodeHasProperty(Property, CGP))
2099 return true;
2100 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2101 if (getChild(i)->TreeHasProperty(Property, CGP))
2102 return true;
2103 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002104}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002105
Evan Cheng49bad4c2008-06-16 20:29:38 +00002106/// isCommutativeIntrinsic - Return true if the node corresponds to a
2107/// commutative intrinsic.
2108bool
2109TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2110 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2111 return Int->isCommutative;
2112 return false;
2113}
2114
Matt Arsenaulteb492162014-11-02 23:46:51 +00002115static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2116 if (!N->isLeaf())
2117 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002118
Matt Arsenaulteb492162014-11-02 23:46:51 +00002119 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
2120 if (DI && DI->getDef()->isSubClassOf(Class))
2121 return true;
2122
2123 return false;
2124}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002125
2126static void emitTooManyOperandsError(TreePattern &TP,
2127 StringRef InstName,
2128 unsigned Expected,
2129 unsigned Actual) {
2130 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2131 " operands but expected only " + Twine(Expected) + "!");
2132}
2133
2134static void emitTooFewOperandsError(TreePattern &TP,
2135 StringRef InstName,
2136 unsigned Actual) {
2137 TP.error("Instruction '" + InstName +
2138 "' expects more than the provided " + Twine(Actual) + " operands!");
2139}
2140
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002141/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002142/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002143/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002144bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002145 if (TP.hasError())
2146 return false;
2147
Chris Lattnerab3242f2008-01-06 01:10:31 +00002148 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002149 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002150 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002151 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002152 bool MadeChange = false;
2153 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2154 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002155 NotRegisters,
2156 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002157 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002158 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002159
Sean Silvafb509ed2012-10-10 20:24:43 +00002160 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002161 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002162
Chris Lattnerf1447252010-03-19 21:37:09 +00002163 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002164 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002165
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002166 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002167 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002168
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002169 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2170 for (auto &P : VVT) {
2171 MVT::SimpleValueType VT = P.second.SimpleTy;
2172 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2173 continue;
2174 unsigned Size = MVT(VT).getSizeInBits();
2175 // Make sure that the value is representable for this type.
2176 if (Size >= 32)
2177 continue;
2178 // Check that the value doesn't use more bits than we have. It must
2179 // either be a sign- or zero-extended equivalent of the original.
2180 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2181 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2182 SignBitAndAbove == 1)
2183 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002184
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002185 TP.error("Integer value '" + itostr(II->getValue()) +
2186 "' is out of range for type '" + getEnumName(VT) + "'!");
2187 break;
2188 }
2189 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002190 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002191
Chris Lattner8cab0212008-01-05 22:25:12 +00002192 return false;
2193 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002194
Chris Lattner8cab0212008-01-05 22:25:12 +00002195 // special handling for set, which isn't really an SDNode.
2196 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002197 assert(getNumTypes() == 0 && "Set doesn't produce a value");
2198 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002199 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002200
Chris Lattnerf1447252010-03-19 21:37:09 +00002201 TreePatternNode *SetVal = getChild(NC-1);
2202 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
2203
Elena Demikhovsky09954792015-03-01 08:23:41 +00002204 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002205 TreePatternNode *Child = getChild(i);
2206 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002207
Chris Lattner8cab0212008-01-05 22:25:12 +00002208 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00002209 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
2210 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002211 }
2212 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002213 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002214
Chris Lattner5c2182e2010-03-27 02:53:27 +00002215 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002216 assert(getNumTypes() == 0 && "Node doesn't produce a value");
2217
Chris Lattner8cab0212008-01-05 22:25:12 +00002218 bool MadeChange = false;
2219 for (unsigned i = 0; i < getNumChildren(); ++i)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002220 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002221 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002222 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002223
Chris Lattneree820ac2010-02-23 05:51:07 +00002224 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002225 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002226
Chris Lattner8cab0212008-01-05 22:25:12 +00002227 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002228 unsigned NumRetVTs = Int->IS.RetVTs.size();
2229 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002230
Bill Wendling91821472008-11-13 09:08:33 +00002231 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002232 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002233
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002234 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00002235 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00002236 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00002237 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002238 return false;
2239 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002240
2241 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00002242 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002243
Chris Lattnerf1447252010-03-19 21:37:09 +00002244 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
2245 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002246
Chris Lattnerf1447252010-03-19 21:37:09 +00002247 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
2248 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2249 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002250 }
2251 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002252 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002253
Chris Lattneree820ac2010-02-23 05:51:07 +00002254 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002255 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002256
Chris Lattner135091b2010-03-28 08:48:47 +00002257 // Check that the number of operands is sane. Negative operands -> varargs.
2258 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002259 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002260 TP.error(getOperator()->getName() + " node requires exactly " +
2261 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002262 return false;
2263 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002264
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002265 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002266 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2267 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002268 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002269 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002270 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002271
Chris Lattneree820ac2010-02-23 05:51:07 +00002272 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002273 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002274 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002275 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002276
Chris Lattnerd44966f2010-03-27 19:15:02 +00002277 bool MadeChange = false;
2278
2279 // Apply the result types to the node, these come from the things in the
2280 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002281 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2282 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002283 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2284 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002285
Chris Lattnerd44966f2010-03-27 19:15:02 +00002286 // If the instruction has implicit defs, we apply the first one as a result.
2287 // FIXME: This sucks, it should apply all implicit defs.
2288 if (!InstInfo.ImplicitDefs.empty()) {
2289 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002290
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002291 // FIXME: Generalize to multiple possible types and multiple possible
2292 // ImplicitDefs.
2293 MVT::SimpleValueType VT =
2294 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002295
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002296 if (VT != MVT::Other)
2297 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002298 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002299
Chris Lattnercabe0372010-03-15 06:00:16 +00002300 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2301 // be the same.
2302 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002303 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2304 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2305 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002306 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2307 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2308 // variadic.
2309
2310 unsigned NChild = getNumChildren();
2311 if (NChild < 3) {
2312 TP.error("REG_SEQUENCE requires at least 3 operands!");
2313 return false;
2314 }
2315
2316 if (NChild % 2 == 0) {
2317 TP.error("REG_SEQUENCE requires an odd number of operands!");
2318 return false;
2319 }
2320
2321 if (!isOperandClass(getChild(0), "RegisterClass")) {
2322 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2323 return false;
2324 }
2325
2326 for (unsigned I = 1; I < NChild; I += 2) {
2327 TreePatternNode *SubIdxChild = getChild(I + 1);
2328 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2329 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2330 itostr(I + 1) + "!");
2331 return false;
2332 }
2333 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002334 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002335
2336 unsigned ChildNo = 0;
2337 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2338 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002339
Chris Lattner8cab0212008-01-05 22:25:12 +00002340 // If the instruction expects a predicate or optional def operand, we
2341 // codegen this by setting the operand to it's default value if it has a
2342 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002343 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002344 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2345 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002346
Chris Lattner8cab0212008-01-05 22:25:12 +00002347 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002348 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002349 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002350 return false;
2351 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002352
Chris Lattner8cab0212008-01-05 22:25:12 +00002353 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002354 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002355
2356 // If the operand has sub-operands, they may be provided by distinct
2357 // child patterns, so attempt to match each sub-operand separately.
2358 if (OperandNode->isSubClassOf("Operand")) {
2359 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2360 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2361 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002362 // a single ComplexPattern-related Operand.
2363
2364 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002365 // Match first sub-operand against the child we already have.
2366 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2367 MadeChange |=
2368 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2369
2370 // And the remaining sub-operands against subsequent children.
2371 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2372 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002373 emitTooFewOperandsError(TP, getOperator()->getName(),
2374 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002375 return false;
2376 }
2377 Child = getChild(ChildNo++);
2378
2379 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2380 MadeChange |=
2381 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2382 }
2383 continue;
2384 }
2385 }
2386 }
2387
2388 // If we didn't match by pieces above, attempt to match the whole
2389 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002390 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002391 }
Christopher Lamba7312392008-03-11 09:33:47 +00002392
Matt Arsenaulteb492162014-11-02 23:46:51 +00002393 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002394 emitTooManyOperandsError(TP, getOperator()->getName(),
2395 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002396 return false;
2397 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002398
Ulrich Weigande618abd2013-03-19 19:51:09 +00002399 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2400 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002401 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002402 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002403
Tim Northoverc807a172014-05-20 11:52:46 +00002404 if (getOperator()->isSubClassOf("ComplexPattern")) {
2405 bool MadeChange = false;
2406
2407 for (unsigned i = 0; i < getNumChildren(); ++i)
2408 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2409
2410 return MadeChange;
2411 }
2412
Chris Lattneree820ac2010-02-23 05:51:07 +00002413 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002414
Chris Lattneree820ac2010-02-23 05:51:07 +00002415 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002416 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002417 TP.error("Node transform '" + getOperator()->getName() +
2418 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002419 return false;
2420 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002421
Chris Lattnercabe0372010-03-15 06:00:16 +00002422 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002423 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002424}
2425
2426/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2427/// RHS of a commutative operation, not the on LHS.
2428static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2429 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2430 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002431 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002432 return true;
2433 return false;
2434}
2435
2436
2437/// canPatternMatch - If it is impossible for this pattern to match on this
2438/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002439/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002440/// that can never possibly work), and to prevent the pattern permuter from
2441/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002442bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002443 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002444 if (isLeaf()) return true;
2445
2446 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2447 if (!getChild(i)->canPatternMatch(Reason, CDP))
2448 return false;
2449
2450 // If this is an intrinsic, handle cases that would make it not match. For
2451 // example, if an operand is required to be an immediate.
2452 if (getOperator()->isSubClassOf("Intrinsic")) {
2453 // TODO:
2454 return true;
2455 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002456
Tim Northoverc807a172014-05-20 11:52:46 +00002457 if (getOperator()->isSubClassOf("ComplexPattern"))
2458 return true;
2459
Chris Lattner8cab0212008-01-05 22:25:12 +00002460 // If this node is a commutative operator, check that the LHS isn't an
2461 // immediate.
2462 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002463 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2464 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002465 // Scan all of the operands of the node and make sure that only the last one
2466 // is a constant node, unless the RHS also is.
2467 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002468 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002469 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002470 if (OnlyOnRHSOfCommutative(getChild(i))) {
2471 Reason="Immediate value must be on the RHS of commutative operators!";
2472 return false;
2473 }
2474 }
2475 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002476
Chris Lattner8cab0212008-01-05 22:25:12 +00002477 return true;
2478}
2479
2480//===----------------------------------------------------------------------===//
2481// TreePattern implementation
2482//
2483
David Greeneaf8ee2c2011-07-29 22:43:06 +00002484TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002485 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002486 isInputPattern(isInput), HasError(false),
2487 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002488 for (Init *I : RawPat->getValues())
2489 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002490}
2491
David Greeneaf8ee2c2011-07-29 22:43:06 +00002492TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002493 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002494 isInputPattern(isInput), HasError(false),
2495 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002496 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002497}
2498
David Blaikiecf195302014-11-17 22:55:41 +00002499TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002500 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002501 isInputPattern(isInput), HasError(false),
2502 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002503 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002504}
2505
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002506void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002507 if (HasError)
2508 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002509 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002510 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2511 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002512}
2513
Chris Lattnercabe0372010-03-15 06:00:16 +00002514void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002515 for (TreePatternNode *Tree : Trees)
2516 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002517}
2518
2519void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2520 if (!N->getName().empty())
2521 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002522
Chris Lattnercabe0372010-03-15 06:00:16 +00002523 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2524 ComputeNamedNodes(N->getChild(i));
2525}
2526
David Blaikiecf195302014-11-17 22:55:41 +00002527
2528TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002529 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002530 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002531
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002532 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002533 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002534 /// (foo GPR, imm) -> (foo GPR, (imm))
2535 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002536 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002537 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002538 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002539 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002540
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002541 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002542 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002543 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002544 if (OpName.empty())
2545 error("'node' argument requires a name to match with operand list");
2546 Args.push_back(OpName);
2547 }
2548
2549 Res->setName(OpName);
2550 return Res;
2551 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002552
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002553 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002554 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002555 if (OpName.empty())
2556 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002557 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002558 Args.push_back(OpName);
2559 Res->setName(OpName);
2560 return Res;
2561 }
2562
Sean Silvafb509ed2012-10-10 20:24:43 +00002563 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002564 if (!OpName.empty())
2565 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002566 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002567 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002568
Sean Silvafb509ed2012-10-10 20:24:43 +00002569 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002570 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002571 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002572 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002573 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002574 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002575 }
2576
Sean Silvafb509ed2012-10-10 20:24:43 +00002577 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002578 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002579 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002580 error("Pattern has unexpected init kind!");
2581 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002582 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002583 if (!OpDef) error("Pattern has unexpected operator type!");
2584 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002585
Chris Lattner8cab0212008-01-05 22:25:12 +00002586 if (Operator->isSubClassOf("ValueType")) {
2587 // If the operator is a ValueType, then this must be "type cast" of a leaf
2588 // node.
2589 if (Dag->getNumArgs() != 1)
2590 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002591
Matthias Braunbb053162016-12-05 06:00:46 +00002592 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2593 Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002594
Chris Lattner8cab0212008-01-05 22:25:12 +00002595 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002596 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002597 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2598 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002599
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002600 if (!OpName.empty())
2601 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002602 return New;
2603 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002604
Chris Lattner8cab0212008-01-05 22:25:12 +00002605 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002606 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002607 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002608 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002609 !Operator->isSubClassOf("SDNodeXForm") &&
2610 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002611 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002612 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002613 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002614 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002615
Chris Lattner8cab0212008-01-05 22:25:12 +00002616 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002617 if (isInputPattern) {
2618 if (Operator->isSubClassOf("Instruction") ||
2619 Operator->isSubClassOf("SDNodeXForm"))
2620 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2621 } else {
2622 if (Operator->isSubClassOf("Intrinsic"))
2623 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002624
Chris Lattner2e9eae12010-03-28 06:57:56 +00002625 if (Operator->isSubClassOf("SDNode") &&
2626 Operator->getName() != "imm" &&
2627 Operator->getName() != "fpimm" &&
2628 Operator->getName() != "tglobaltlsaddr" &&
2629 Operator->getName() != "tconstpool" &&
2630 Operator->getName() != "tjumptable" &&
2631 Operator->getName() != "tframeindex" &&
2632 Operator->getName() != "texternalsym" &&
2633 Operator->getName() != "tblockaddress" &&
2634 Operator->getName() != "tglobaladdr" &&
2635 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002636 Operator->getName() != "vt" &&
2637 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002638 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2639 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002640
Chris Lattner8cab0212008-01-05 22:25:12 +00002641 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002642
2643 // Parse all the operands.
2644 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002645 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002646
Chris Lattner8cab0212008-01-05 22:25:12 +00002647 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002648 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002649 // convert the intrinsic name to a number.
2650 if (Operator->isSubClassOf("Intrinsic")) {
2651 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2652 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2653
2654 // If this intrinsic returns void, it must have side-effects and thus a
2655 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002656 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002657 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002658 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002659 // Has side-effects, requires chain.
2660 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002661 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002662 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002663
David Greenee32ebf22011-07-29 19:07:07 +00002664 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002665 Children.insert(Children.begin(), IIDNode);
2666 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002667
Tim Northoverc807a172014-05-20 11:52:46 +00002668 if (Operator->isSubClassOf("ComplexPattern")) {
2669 for (unsigned i = 0; i < Children.size(); ++i) {
2670 TreePatternNode *Child = Children[i];
2671
2672 if (Child->getName().empty())
2673 error("All arguments to a ComplexPattern must be named");
2674
2675 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2676 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2677 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2678 auto OperandId = std::make_pair(Operator, i);
2679 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2680 if (PrevOp != ComplexPatternOperands.end()) {
2681 if (PrevOp->getValue() != OperandId)
2682 error("All ComplexPattern operands must appear consistently: "
2683 "in the same order in just one ComplexPattern instance.");
2684 } else
2685 ComplexPatternOperands[Child->getName()] = OperandId;
2686 }
2687 }
2688
Chris Lattnerf1447252010-03-19 21:37:09 +00002689 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002690 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002691 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002692
Matthias Braun7cf3b112016-12-05 06:00:41 +00002693 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002694 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002695 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002696 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002697 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002698}
2699
Chris Lattnera787c9e2010-03-28 08:38:32 +00002700/// SimplifyTree - See if we can simplify this tree to eliminate something that
2701/// will never match in favor of something obvious that will. This is here
2702/// strictly as a convenience to target authors because it allows them to write
2703/// more type generic things and have useless type casts fold away.
2704///
2705/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002706static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002707 if (N->isLeaf())
2708 return false;
2709
2710 // If we have a bitconvert with a resolved type and if the source and
2711 // destination types are the same, then the bitconvert is useless, remove it.
2712 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002713 N->getExtType(0).isValueTypeByHwMode(false) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002714 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2715 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002716 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002717 SimplifyTree(N);
2718 return true;
2719 }
2720
2721 // Walk all children.
2722 bool MadeChange = false;
2723 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002724 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002725 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002726 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002727 }
2728 return MadeChange;
2729}
2730
2731
2732
Chris Lattner8cab0212008-01-05 22:25:12 +00002733/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002734/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002735/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002736bool TreePattern::
2737InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2738 if (NamedNodes.empty())
2739 ComputeNamedNodes();
2740
Chris Lattner8cab0212008-01-05 22:25:12 +00002741 bool MadeChange = true;
2742 while (MadeChange) {
2743 MadeChange = false;
Craig Topper3f7864e2017-08-30 02:05:03 +00002744 for (TreePatternNode *&Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002745 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2746 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002747 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002748
2749 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002750 for (auto &Entry : NamedNodes) {
2751 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002752
Chris Lattnercabe0372010-03-15 06:00:16 +00002753 // If we have input named node types, propagate their types to the named
2754 // values here.
2755 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002756 if (!InNamedTypes->count(Entry.getKey())) {
2757 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002758 "' in output pattern but not input pattern");
2759 return true;
2760 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002761
2762 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002763 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002764
2765 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002766 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002767 // If this node is a register class, and it is the root of the pattern
2768 // then we're mapping something onto an input register. We allow
2769 // changing the type of the input register in this case. This allows
2770 // us to match things like:
2771 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002772 if (Node == Trees[0] && Node->isLeaf()) {
2773 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002774 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2775 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002776 continue;
2777 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002778
Craig Topper306cb122015-11-22 20:46:24 +00002779 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002780 InNodes[0]->getNumTypes() == 1 &&
2781 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002782 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2783 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002784 }
2785 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002786
Chris Lattnercabe0372010-03-15 06:00:16 +00002787 // If there are multiple nodes with the same name, they must all have the
2788 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002789 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002790 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002791 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002792 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002793 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002794
Chris Lattnerf1447252010-03-19 21:37:09 +00002795 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2796 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002797 }
2798 }
2799 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002800 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002801
Chris Lattner8cab0212008-01-05 22:25:12 +00002802 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002803 for (const TreePatternNode *Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002804 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002805 return !HasUnresolvedTypes;
2806}
2807
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002808void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002809 OS << getRecord()->getName();
2810 if (!Args.empty()) {
2811 OS << "(" << Args[0];
2812 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2813 OS << ", " << Args[i];
2814 OS << ")";
2815 }
2816 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002817
Chris Lattner8cab0212008-01-05 22:25:12 +00002818 if (Trees.size() > 1)
2819 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002820 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002821 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002822 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002823 OS << "\n";
2824 }
2825
2826 if (Trees.size() > 1)
2827 OS << "]\n";
2828}
2829
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002830void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002831
2832//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002833// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002834//
2835
Daniel Sanders7e523672017-11-11 03:23:44 +00002836CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2837 PatternRewriterFn PatternRewriter)
2838 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2839 PatternRewriter(PatternRewriter) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002840
Justin Bogner92a8c612016-07-15 16:31:37 +00002841 Intrinsics = CodeGenIntrinsicTable(Records, false);
2842 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002843 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002844 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002845 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002846 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002847 ParseDefaultOperands();
2848 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002849 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002850 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002851
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002852 // Break patterns with parameterized types into a series of patterns,
2853 // where each one has a fixed type and is predicated on the conditions
2854 // of the associated HW mode.
2855 ExpandHwModeBasedTypes();
2856
Chris Lattner8cab0212008-01-05 22:25:12 +00002857 // Generate variants. For example, commutative patterns can match
2858 // multiple ways. Add them to PatternsToMatch as well.
2859 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002860
2861 // Infer instruction flags. For example, we can detect loads,
2862 // stores, and side effects in many cases by examining an
2863 // instruction's pattern.
2864 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002865
2866 // Verify that instruction flags match the patterns.
2867 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002868}
2869
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00002870Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002871 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002872 if (!N || !N->isSubClassOf("SDNode"))
2873 PrintFatalError("Error getting SDNode '" + Name + "'!");
2874
Chris Lattner8cab0212008-01-05 22:25:12 +00002875 return N;
2876}
2877
2878// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002879void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002880 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002881 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2882
Chris Lattner8cab0212008-01-05 22:25:12 +00002883 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002884 Record *R = Nodes.back();
2885 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002886 Nodes.pop_back();
2887 }
2888
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002889 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002890 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2891 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2892 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2893}
2894
2895/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2896/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002897void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002898 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2899 while (!Xforms.empty()) {
2900 Record *XFormNode = Xforms.back();
2901 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002902 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002903 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002904
2905 Xforms.pop_back();
2906 }
2907}
2908
Chris Lattnerab3242f2008-01-06 01:10:31 +00002909void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002910 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2911 while (!AMs.empty()) {
2912 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2913 AMs.pop_back();
2914 }
2915}
2916
2917
2918/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2919/// file, building up the PatternFragments map. After we've collected them all,
2920/// inline fragments together as necessary, so that there are no references left
2921/// inside a pattern fragment to a pattern fragment.
2922///
Hal Finkel2756dc12014-02-28 00:26:56 +00002923void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002924 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002925
Chris Lattnere7170df2008-01-05 22:43:57 +00002926 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002927 for (Record *Frag : Fragments) {
2928 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002929 continue;
2930
Craig Topper306cb122015-11-22 20:46:24 +00002931 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002932 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002933 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2934 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002935 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002936
Chris Lattnere7170df2008-01-05 22:43:57 +00002937 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002938 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00002939 // Copy the args so we can take StringRefs to them.
2940 auto ArgsCopy = Args;
2941 SmallDenseSet<StringRef, 4> OperandsSet;
2942 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002943
Chris Lattnere7170df2008-01-05 22:43:57 +00002944 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002945 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002946
Chris Lattner8cab0212008-01-05 22:25:12 +00002947 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002948 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002949 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002950 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002951 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002952 if (!OpsOp ||
2953 (OpsOp->getDef()->getName() != "ops" &&
2954 OpsOp->getDef()->getName() != "outs" &&
2955 OpsOp->getDef()->getName() != "ins"))
2956 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002957
2958 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002959 Args.clear();
2960 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002961 if (!isa<DefInit>(OpsList->getArg(j)) ||
2962 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002963 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00002964 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00002965 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00002966 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2967 if (!OperandsSet.count(ArgNameStr))
2968 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00002969 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00002970 OperandsSet.erase(ArgNameStr);
2971 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00002972 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002973
Chris Lattnere7170df2008-01-05 22:43:57 +00002974 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002975 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002976 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002977
Chris Lattnere7170df2008-01-05 22:43:57 +00002978 // If there is a code init for this fragment, keep track of the fact that
2979 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002980 TreePredicateFn PredFn(P);
2981 if (!PredFn.isAlwaysTrue())
2982 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002983
Chris Lattner8cab0212008-01-05 22:25:12 +00002984 // If there is a node transformation corresponding to this, keep track of
2985 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002986 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002987 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2988 P->getOnlyTree()->setTransformFn(Transform);
2989 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002990
Chris Lattner8cab0212008-01-05 22:25:12 +00002991 // Now that we've parsed all of the tree fragments, do a closure on them so
2992 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002993 for (Record *Frag : Fragments) {
2994 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002995 continue;
2996
Craig Topper306cb122015-11-22 20:46:24 +00002997 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002998 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002999
Chris Lattner8cab0212008-01-05 22:25:12 +00003000 // Infer as many types as possible. Don't worry about it if we don't infer
3001 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00003002 ThePat.InferAllTypes();
3003 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003004
Chris Lattner8cab0212008-01-05 22:25:12 +00003005 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00003006 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003007 }
3008}
3009
Chris Lattnerab3242f2008-01-06 01:10:31 +00003010void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00003011 std::vector<Record*> DefaultOps;
3012 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00003013
3014 // Find some SDNode.
3015 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00003016 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003017
Tom Stellardb7246a72012-09-06 14:15:52 +00003018 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3019 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003020
Tom Stellardb7246a72012-09-06 14:15:52 +00003021 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3022 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00003023 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00003024 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3025 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3026 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00003027 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003028
Tom Stellardb7246a72012-09-06 14:15:52 +00003029 // Create a TreePattern to parse this.
3030 TreePattern P(DefaultOps[i], DI, false, *this);
3031 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003032
Tom Stellardb7246a72012-09-06 14:15:52 +00003033 // Copy the operands over into a DAGDefaultOperand.
3034 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003035
Tom Stellardb7246a72012-09-06 14:15:52 +00003036 TreePatternNode *T = P.getTree(0);
3037 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3038 TreePatternNode *TPN = T->getChild(op);
3039 while (TPN->ApplyTypeConstraints(P, false))
3040 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003041
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003042 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00003043 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3044 DefaultOps[i]->getName() +
3045 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003046 }
Tom Stellardb7246a72012-09-06 14:15:52 +00003047 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00003048 }
Tom Stellardb7246a72012-09-06 14:15:52 +00003049
3050 // Insert it into the DefaultOperands map so we can find it later.
3051 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00003052 }
3053}
3054
3055/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3056/// instruction input. Return true if this is a real use.
3057static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00003058 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003059 // No name -> not interesting.
3060 if (Pat->getName().empty()) {
3061 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003062 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00003063 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3064 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00003065 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003066 }
3067 return false;
3068 }
3069
3070 Record *Rec;
3071 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003072 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003073 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
3074 Rec = DI->getDef();
3075 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003076 Rec = Pat->getOperator();
3077 }
3078
3079 // SRCVALUE nodes are ignored.
3080 if (Rec->getName() == "srcvalue")
3081 return false;
3082
3083 TreePatternNode *&Slot = InstInputs[Pat->getName()];
3084 if (!Slot) {
3085 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003086 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00003087 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003088 Record *SlotRec;
3089 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003090 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003091 } else {
3092 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3093 SlotRec = Slot->getOperator();
3094 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003095
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003096 // Ensure that the inputs agree if we've already seen this input.
3097 if (Rec != SlotRec)
3098 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00003099 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003100 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003101 return true;
3102}
3103
3104/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3105/// part of "I", the instruction), computing the set of inputs and outputs of
3106/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003107void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00003108FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
3109 std::map<std::string, TreePatternNode*> &InstInputs,
3110 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00003111 std::vector<Record*> &InstImpResults) {
3112 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003113 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00003114 if (!isUse && Pat->getTransformFn())
3115 I->error("Cannot specify a transform function for a non-input value!");
3116 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003117 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003118
Chris Lattnerf2d70992010-02-17 06:53:36 +00003119 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003120 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3121 TreePatternNode *Dest = Pat->getChild(i);
3122 if (!Dest->isLeaf())
3123 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003124
Sean Silvafb509ed2012-10-10 20:24:43 +00003125 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003126 if (!Val || !Val->getDef()->isSubClassOf("Register"))
3127 I->error("implicitly defined value should be a register!");
3128 InstImpResults.push_back(Val->getDef());
3129 }
3130 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003131 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003132
Chris Lattnerf2d70992010-02-17 06:53:36 +00003133 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003134 // If this is not a set, verify that the children nodes are not void typed,
3135 // and recurse.
3136 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003137 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00003138 I->error("Cannot have void nodes inside of patterns!");
3139 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003140 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003141 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003142
Chris Lattner8cab0212008-01-05 22:25:12 +00003143 // If this is a non-leaf node with no children, treat it basically as if
3144 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003145 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003146
Chris Lattner8cab0212008-01-05 22:25:12 +00003147 if (!isUse && Pat->getTransformFn())
3148 I->error("Cannot specify a transform function for a non-input value!");
3149 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003150 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003151
Chris Lattner8cab0212008-01-05 22:25:12 +00003152 // Otherwise, this is a set, validate and collect instruction results.
3153 if (Pat->getNumChildren() == 0)
3154 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003155
Chris Lattner8cab0212008-01-05 22:25:12 +00003156 if (Pat->getTransformFn())
3157 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003158
Chris Lattner8cab0212008-01-05 22:25:12 +00003159 // Check the set destinations.
3160 unsigned NumDests = Pat->getNumChildren()-1;
3161 for (unsigned i = 0; i != NumDests; ++i) {
3162 TreePatternNode *Dest = Pat->getChild(i);
3163 if (!Dest->isLeaf())
3164 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003165
Sean Silvafb509ed2012-10-10 20:24:43 +00003166 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003167 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003168 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003169 continue;
3170 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003171
3172 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003173 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003174 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003175 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003176 if (Dest->getName().empty())
3177 I->error("set destination must have a name!");
3178 if (InstResults.count(Dest->getName()))
3179 I->error("cannot set '" + Dest->getName() +"' multiple times");
3180 InstResults[Dest->getName()] = Dest;
3181 } else if (Val->getDef()->isSubClassOf("Register")) {
3182 InstImpResults.push_back(Val->getDef());
3183 } else {
3184 I->error("set destination should be a register!");
3185 }
3186 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003187
Chris Lattner8cab0212008-01-05 22:25:12 +00003188 // Verify and collect info from the computation.
3189 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00003190 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003191}
3192
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003193//===----------------------------------------------------------------------===//
3194// Instruction Analysis
3195//===----------------------------------------------------------------------===//
3196
3197class InstAnalyzer {
3198 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003199public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003200 bool hasSideEffects;
3201 bool mayStore;
3202 bool mayLoad;
3203 bool isBitcast;
3204 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003205
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003206 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3207 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3208 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003209
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003210 void Analyze(const TreePattern *Pat) {
3211 // Assume only the first tree is the pattern. The others are clobber nodes.
3212 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003213 }
3214
Craig Topper2a053a92017-06-20 16:34:37 +00003215 void Analyze(const PatternToMatch &Pat) {
3216 AnalyzeNode(Pat.getSrcPattern());
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003217 }
3218
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003219private:
Evan Cheng880e299d2011-03-15 05:09:26 +00003220 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003221 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003222 return false;
3223
3224 if (N->getNumChildren() != 2)
3225 return false;
3226
3227 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00003228 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00003229 return false;
3230
3231 const TreePatternNode *N1 = N->getChild(1);
3232 if (N1->isLeaf())
3233 return false;
3234 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
3235 return false;
3236
3237 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
3238 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3239 return false;
3240 return OpInfo.getEnumName() == "ISD::BITCAST";
3241 }
3242
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003243public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003244 void AnalyzeNode(const TreePatternNode *N) {
3245 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003246 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003247 Record *LeafRec = DI->getDef();
3248 // Handle ComplexPattern leaves.
3249 if (LeafRec->isSubClassOf("ComplexPattern")) {
3250 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3251 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3252 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003253 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003254 }
3255 }
3256 return;
3257 }
3258
3259 // Analyze children.
3260 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3261 AnalyzeNode(N->getChild(i));
3262
3263 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00003264 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003265 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003266 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00003267 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003268
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003269 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00003270 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3271 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3272 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3273 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003274
3275 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3276 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003277 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003278 mayLoad = true;// These may load memory.
3279
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003280 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003281 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3282
Matt Arsenault868af922017-04-28 21:01:46 +00003283 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3284 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003285 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003286 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003287 }
3288 }
3289
3290};
3291
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003292static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003293 const InstAnalyzer &PatInfo,
3294 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003295 bool Error = false;
3296
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003297 // Remember where InstInfo got its flags.
3298 if (InstInfo.hasUndefFlags())
3299 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003300
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003301 // Check explicitly set flags for consistency.
3302 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3303 !InstInfo.hasSideEffects_Unset) {
3304 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3305 // the pattern has no side effects. That could be useful for div/rem
3306 // instructions that may trap.
3307 if (!InstInfo.hasSideEffects) {
3308 Error = true;
3309 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3310 Twine(InstInfo.hasSideEffects));
3311 }
3312 }
3313
3314 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3315 Error = true;
3316 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3317 Twine(InstInfo.mayStore));
3318 }
3319
3320 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3321 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003322 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003323 if (!InstInfo.mayLoad) {
3324 Error = true;
3325 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3326 Twine(InstInfo.mayLoad));
3327 }
3328 }
3329
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003330 // Transfer inferred flags.
3331 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3332 InstInfo.mayStore |= PatInfo.mayStore;
3333 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003334
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003335 // These flags are silently added without any verification.
3336 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003337
3338 // Don't infer isVariadic. This flag means something different on SDNodes and
3339 // instructions. For example, a CALL SDNode is variadic because it has the
3340 // call arguments as operands, but a CALL instruction is not variadic - it
3341 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003342
3343 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003344}
3345
Jim Grosbach514410b2012-07-17 00:47:06 +00003346/// hasNullFragReference - Return true if the DAG has any reference to the
3347/// null_frag operator.
3348static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003349 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003350 if (!OpDef) return false;
3351 Record *Operator = OpDef->getDef();
3352
3353 // If this is the null fragment, return true.
3354 if (Operator->getName() == "null_frag") return true;
3355 // If any of the arguments reference the null fragment, return true.
3356 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003357 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003358 if (Arg && hasNullFragReference(Arg))
3359 return true;
3360 }
3361
3362 return false;
3363}
3364
3365/// hasNullFragReference - Return true if any DAG in the list references
3366/// the null_frag operator.
3367static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003368 for (Init *I : LI->getValues()) {
3369 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003370 assert(DI && "non-dag in an instruction Pattern list?!");
3371 if (hasNullFragReference(DI))
3372 return true;
3373 }
3374 return false;
3375}
3376
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003377/// Get all the instructions in a tree.
3378static void
3379getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3380 if (Tree->isLeaf())
3381 return;
3382 if (Tree->getOperator()->isSubClassOf("Instruction"))
3383 Instrs.push_back(Tree->getOperator());
3384 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3385 getInstructionsInTree(Tree->getChild(i), Instrs);
3386}
3387
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003388/// Check the class of a pattern leaf node against the instruction operand it
3389/// represents.
3390static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3391 Record *Leaf) {
3392 if (OI.Rec == Leaf)
3393 return true;
3394
3395 // Allow direct value types to be used in instruction set patterns.
3396 // The type will be checked later.
3397 if (Leaf->isSubClassOf("ValueType"))
3398 return true;
3399
3400 // Patterns can also be ComplexPattern instances.
3401 if (Leaf->isSubClassOf("ComplexPattern"))
3402 return true;
3403
3404 return false;
3405}
3406
Ahmed Bougacha14107512013-10-28 18:07:21 +00003407const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
3408 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003409
Craig Topper0d1fb902015-03-10 03:25:04 +00003410 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003411
Craig Topper0d1fb902015-03-10 03:25:04 +00003412 // Parse the instruction.
3413 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
3414 // Inline pattern fragments into it.
3415 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003416
Craig Topper0d1fb902015-03-10 03:25:04 +00003417 // Infer as many types as possible. If we cannot infer all of them, we can
3418 // never do anything with this instruction pattern: report it to the user.
3419 if (!I->InferAllTypes())
3420 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003421
Craig Topper0d1fb902015-03-10 03:25:04 +00003422 // InstInputs - Keep track of all of the inputs of the instruction, along
3423 // with the record they are declared as.
3424 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003425
Craig Topper0d1fb902015-03-10 03:25:04 +00003426 // InstResults - Keep track of all the virtual registers that are 'set'
3427 // in the instruction, including what reg class they are.
3428 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003429
Craig Topper0d1fb902015-03-10 03:25:04 +00003430 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003431
Craig Topper0d1fb902015-03-10 03:25:04 +00003432 // Verify that the top-level forms in the instruction are of void type, and
3433 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003434 SmallString<32> TypesString;
Craig Topper0d1fb902015-03-10 03:25:04 +00003435 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003436 TypesString.clear();
Craig Topper0d1fb902015-03-10 03:25:04 +00003437 TreePatternNode *Pat = I->getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003438 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003439 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003440 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3441 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003442 OS << ", ";
3443 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003444 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003445 I->error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003446 " void types, has types " +
3447 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003448 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003449
Craig Topper0d1fb902015-03-10 03:25:04 +00003450 // Find inputs and outputs, and verify the structure of the uses/defs.
3451 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3452 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003453 }
3454
Craig Topper0d1fb902015-03-10 03:25:04 +00003455 // Now that we have inputs and outputs of the pattern, inspect the operands
3456 // list for the instruction. This determines the order that operands are
3457 // added to the machine instruction the node corresponds to.
3458 unsigned NumResults = InstResults.size();
3459
3460 // Parse the operands list from the (ops) list, validating it.
3461 assert(I->getArgList().empty() && "Args list should still be empty here!");
3462
3463 // Check that all of the results occur first in the list.
3464 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00003465 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003466 for (unsigned i = 0; i != NumResults; ++i) {
3467 if (i == CGI.Operands.size())
3468 I->error("'" + InstResults.begin()->first +
3469 "' set but does not appear in operand list!");
3470 const std::string &OpName = CGI.Operands[i].Name;
3471
3472 // Check that it exists in InstResults.
3473 TreePatternNode *RNode = InstResults[OpName];
3474 if (!RNode)
3475 I->error("Operand $" + OpName + " does not exist in operand list!");
3476
Craig Topper3a8eb892015-03-20 05:09:06 +00003477 ResNodes.push_back(RNode);
3478
Craig Topper0d1fb902015-03-10 03:25:04 +00003479 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3480 if (!R)
3481 I->error("Operand $" + OpName + " should be a set destination: all "
3482 "outputs must occur before inputs in operand list!");
3483
3484 if (!checkOperandClass(CGI.Operands[i], R))
3485 I->error("Operand $" + OpName + " class mismatch!");
3486
3487 // Remember the return type.
3488 Results.push_back(CGI.Operands[i].Rec);
3489
3490 // Okay, this one checks out.
3491 InstResults.erase(OpName);
3492 }
3493
3494 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3495 // the copy while we're checking the inputs.
3496 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3497
3498 std::vector<TreePatternNode*> ResultNodeOperands;
3499 std::vector<Record*> Operands;
3500 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3501 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3502 const std::string &OpName = Op.Name;
3503 if (OpName.empty())
3504 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3505
3506 if (!InstInputsCheck.count(OpName)) {
3507 // If this is an operand with a DefaultOps set filled in, we can ignore
3508 // this. When we codegen it, we will do so as always executed.
3509 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3510 // Does it have a non-empty DefaultOps field? If so, ignore this
3511 // operand.
3512 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3513 continue;
3514 }
3515 I->error("Operand $" + OpName +
3516 " does not appear in the instruction pattern");
3517 }
3518 TreePatternNode *InVal = InstInputsCheck[OpName];
3519 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3520
3521 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3522 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3523 if (!checkOperandClass(Op, InRec))
3524 I->error("Operand $" + OpName + "'s register class disagrees"
3525 " between the operand and pattern");
3526 }
3527 Operands.push_back(Op.Rec);
3528
3529 // Construct the result for the dest-pattern operand list.
3530 TreePatternNode *OpNode = InVal->clone();
3531
3532 // No predicate is useful on the result.
3533 OpNode->clearPredicateFns();
3534
3535 // Promote the xform function to be an explicit node if set.
3536 if (Record *Xform = OpNode->getTransformFn()) {
3537 OpNode->setTransformFn(nullptr);
3538 std::vector<TreePatternNode*> Children;
3539 Children.push_back(OpNode);
3540 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3541 }
3542
3543 ResultNodeOperands.push_back(OpNode);
3544 }
3545
3546 if (!InstInputsCheck.empty())
3547 I->error("Input operand $" + InstInputsCheck.begin()->first +
3548 " occurs in pattern but not in operands list!");
3549
3550 TreePatternNode *ResultPattern =
3551 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3552 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003553 // Copy fully inferred output node types to instruction result pattern.
3554 for (unsigned i = 0; i != NumResults; ++i) {
3555 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3556 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3557 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003558
3559 // Create and insert the instruction.
3560 // FIXME: InstImpResults should not be part of DAGInstruction.
3561 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3562 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3563
3564 // Use a temporary tree pattern to infer all types and make sure that the
3565 // constructed result is correct. This depends on the instruction already
3566 // being inserted into the DAGInsts map.
3567 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3568 Temp.InferAllTypes(&I->getNamedNodesMap());
3569
3570 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3571 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3572
3573 return TheInsertedInst;
3574}
3575
Ahmed Bougacha14107512013-10-28 18:07:21 +00003576/// ParseInstructions - Parse all of the instructions, inlining and resolving
3577/// any fragments involved. This populates the Instructions list with fully
3578/// resolved instructions.
3579void CodeGenDAGPatterns::ParseInstructions() {
3580 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3581
Craig Topper306cb122015-11-22 20:46:24 +00003582 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003583 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003584
Craig Topper306cb122015-11-22 20:46:24 +00003585 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3586 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003587
3588 // If there is no pattern, only collect minimal information about the
3589 // instruction for its operand list. We have to assume that there is one
3590 // result, as we have no detailed info. A pattern which references the
3591 // null_frag operator is as-if no pattern were specified. Normally this
3592 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3593 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003594 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003595 std::vector<Record*> Results;
3596 std::vector<Record*> Operands;
3597
Craig Topper306cb122015-11-22 20:46:24 +00003598 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003599
3600 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003601 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3602 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003603
Craig Topper3a8eb892015-03-20 05:09:06 +00003604 // The rest are inputs.
3605 for (unsigned j = InstInfo.Operands.NumDefs,
3606 e = InstInfo.Operands.size(); j < e; ++j)
3607 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003608 }
3609
3610 // Create and insert the instruction.
3611 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003612 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003613 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003614 continue; // no pattern.
3615 }
3616
Craig Topper306cb122015-11-22 20:46:24 +00003617 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003618 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3619
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003620 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003621 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003622 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003623
Chris Lattner8cab0212008-01-05 22:25:12 +00003624 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003625 for (auto &Entry : Instructions) {
3626 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003627 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003628 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003629
Daniel Sanders7e523672017-11-11 03:23:44 +00003630 if (PatternRewriter)
3631 PatternRewriter(I);
Chris Lattner8cab0212008-01-05 22:25:12 +00003632 // FIXME: Assume only the first tree is the pattern. The others are clobber
3633 // nodes.
3634 TreePatternNode *Pattern = I->getTree(0);
3635 TreePatternNode *SrcPattern;
3636 if (Pattern->getOperator()->getName() == "set") {
3637 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3638 } else{
3639 // Not a set (store or something?)
3640 SrcPattern = Pattern;
3641 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003642
Craig Topper306cb122015-11-22 20:46:24 +00003643 Record *Instr = Entry.first;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003644 ListInit *Preds = Instr->getValueAsListInit("Predicates");
3645 int Complexity = Instr->getValueAsInt("AddedComplexity");
3646 AddPatternToMatch(
3647 I,
3648 PatternToMatch(Instr, makePredList(Preds), SrcPattern,
3649 TheInst.getResultPattern(), TheInst.getImpResults(),
3650 Complexity, Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003651 }
3652}
3653
Chris Lattnera7722b62010-02-23 06:55:24 +00003654
3655typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3656
Jim Grosbach65586fe2010-12-21 16:16:00 +00003657static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003658 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003659 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003660 if (!P->getName().empty()) {
3661 NameRecord &Rec = Names[P->getName()];
3662 // If this is the first instance of the name, remember the node.
3663 if (Rec.second++ == 0)
3664 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003665 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003666 PatternTop->error("repetition of value: $" + P->getName() +
3667 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003668 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003669
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003670 if (!P->isLeaf()) {
3671 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003672 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003673 }
3674}
3675
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003676std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3677 std::vector<Predicate> Preds;
3678 for (Init *I : L->getValues()) {
3679 if (DefInit *Pred = dyn_cast<DefInit>(I))
3680 Preds.push_back(Pred->getDef());
3681 else
3682 llvm_unreachable("Non-def on the list");
3683 }
3684
3685 // Sort so that different orders get canonicalized to the same string.
3686 std::sort(Preds.begin(), Preds.end());
3687 return Preds;
3688}
3689
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003690void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003691 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003692 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003693 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003694 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3695 PrintWarning(Pattern->getRecord()->getLoc(),
3696 Twine("Pattern can never match: ") + Reason);
3697 return;
3698 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003699
Chris Lattner1e634e32010-03-01 22:29:19 +00003700 // If the source pattern's root is a complex pattern, that complex pattern
3701 // must specify the nodes it can potentially match.
3702 if (const ComplexPattern *CP =
3703 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3704 if (CP->getRootNodes().empty())
3705 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3706 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003707
3708
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003709 // Find all of the named values in the input and output, ensure they have the
3710 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003711 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003712 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3713 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003714
3715 // Scan all of the named values in the destination pattern, rejecting them if
3716 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003717 for (const auto &Entry : DstNames) {
3718 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003719 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003720 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003721 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003722
Chris Lattnera7722b62010-02-23 06:55:24 +00003723 // Scan all of the named values in the source pattern, rejecting them if the
3724 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003725 for (const auto &Entry : SrcNames)
3726 if (DstNames[Entry.first].first == nullptr &&
3727 SrcNames[Entry.first].second == 1)
3728 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003729
Craig Topper18e6b572017-06-25 17:33:49 +00003730 PatternsToMatch.push_back(std::move(PTM));
Chris Lattner0c0baa92010-02-23 06:16:51 +00003731}
3732
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003733void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003734 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003735 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003736
3737 // First try to infer flags from the primary instruction pattern, if any.
3738 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003739 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003740 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3741 CodeGenInstruction &InstInfo =
3742 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003743
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003744 // Get the primary instruction pattern.
3745 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3746 if (!Pattern) {
3747 if (InstInfo.hasUndefFlags())
3748 Revisit.push_back(&InstInfo);
3749 continue;
3750 }
3751 InstAnalyzer PatInfo(*this);
3752 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003753 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003754 }
3755
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003756 // Second, look for single-instruction patterns defined outside the
3757 // instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003758 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003759 // We can only infer from single-instruction patterns, otherwise we won't
3760 // know which instruction should get the flags.
3761 SmallVector<Record*, 8> PatInstrs;
3762 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3763 if (PatInstrs.size() != 1)
3764 continue;
3765
3766 // Get the single instruction.
3767 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3768
3769 // Only infer properties from the first pattern. We'll verify the others.
3770 if (InstInfo.InferredFrom)
3771 continue;
3772
3773 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003774 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003775 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3776 }
3777
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003778 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003779 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003780
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003781 // Revisit instructions with undefined flags and no pattern.
3782 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003783 for (CodeGenInstruction *InstInfo : Revisit) {
3784 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003785 continue;
3786 // The mayLoad and mayStore flags default to false.
3787 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003788 if (InstInfo->hasSideEffects_Unset)
3789 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003790 }
3791 return;
3792 }
3793
3794 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003795 for (CodeGenInstruction *InstInfo : Revisit) {
3796 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003797 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003798 if (InstInfo->hasSideEffects_Unset)
3799 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003800 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003801 if (InstInfo->mayStore_Unset)
3802 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003803 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003804 if (InstInfo->mayLoad_Unset)
3805 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003806 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003807 }
3808}
3809
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003810
3811/// Verify instruction flags against pattern node properties.
3812void CodeGenDAGPatterns::VerifyInstructionFlags() {
3813 unsigned Errors = 0;
3814 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3815 const PatternToMatch &PTM = *I;
3816 SmallVector<Record*, 8> Instrs;
3817 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3818 if (Instrs.empty())
3819 continue;
3820
3821 // Count the number of instructions with each flag set.
3822 unsigned NumSideEffects = 0;
3823 unsigned NumStores = 0;
3824 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003825 for (const Record *Instr : Instrs) {
3826 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003827 NumSideEffects += InstInfo.hasSideEffects;
3828 NumStores += InstInfo.mayStore;
3829 NumLoads += InstInfo.mayLoad;
3830 }
3831
3832 // Analyze the source pattern.
3833 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003834 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003835
3836 // Collect error messages.
3837 SmallVector<std::string, 4> Msgs;
3838
3839 // Check for missing flags in the output.
3840 // Permit extra flags for now at least.
3841 if (PatInfo.hasSideEffects && !NumSideEffects)
3842 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3843
3844 // Don't verify store flags on instructions with side effects. At least for
3845 // intrinsics, side effects implies mayStore.
3846 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3847 Msgs.push_back("pattern may store, but mayStore isn't set");
3848
3849 // Similarly, mayStore implies mayLoad on intrinsics.
3850 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3851 Msgs.push_back("pattern may load, but mayLoad isn't set");
3852
3853 // Print error messages.
3854 if (Msgs.empty())
3855 continue;
3856 ++Errors;
3857
Craig Topper306cb122015-11-22 20:46:24 +00003858 for (const std::string &Msg : Msgs)
3859 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003860 (Instrs.size() == 1 ?
3861 "instruction" : "output instructions"));
3862 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003863 for (const Record *Instr : Instrs) {
3864 if (Instr != PTM.getSrcRecord())
3865 PrintError(Instr->getLoc(), "defined here");
3866 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003867 if (InstInfo.InferredFrom &&
3868 InstInfo.InferredFrom != InstInfo.TheDef &&
3869 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003870 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003871 }
3872 }
3873 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003874 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003875}
3876
Chris Lattnercabe0372010-03-15 06:00:16 +00003877/// Given a pattern result with an unresolved type, see if we can find one
3878/// instruction with an unresolved result type. Force this result type to an
3879/// arbitrary element if it's possible types to converge results.
3880static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3881 if (N->isLeaf())
3882 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003883
Chris Lattnercabe0372010-03-15 06:00:16 +00003884 // Analyze children.
3885 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3886 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3887 return true;
3888
3889 if (!N->getOperator()->isSubClassOf("Instruction"))
3890 return false;
3891
3892 // If this type is already concrete or completely unknown we can't do
3893 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003894 TypeInfer &TI = TP.getInfer();
Chris Lattnerf1447252010-03-19 21:37:09 +00003895 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003896 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003897 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003898
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003899 // Otherwise, force its type to an arbitrary choice.
3900 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003901 return true;
3902 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003903
Chris Lattnerf1447252010-03-19 21:37:09 +00003904 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003905}
3906
Chris Lattnerab3242f2008-01-06 01:10:31 +00003907void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003908 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3909
Craig Topper306cb122015-11-22 20:46:24 +00003910 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003911 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003912
3913 // If the pattern references the null_frag, there's nothing to do.
3914 if (hasNullFragReference(Tree))
3915 continue;
3916
Chris Lattner5c2182e2010-03-27 02:53:27 +00003917 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003918
3919 // Inline pattern fragments into it.
3920 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003921
David Greeneaf8ee2c2011-07-29 22:43:06 +00003922 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003923 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003924
Chris Lattner8cab0212008-01-05 22:25:12 +00003925 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003926 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003927
Chris Lattner8cab0212008-01-05 22:25:12 +00003928 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003929 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003930
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003931 if (Result.getNumTrees() != 1)
3932 Result.error("Cannot handle instructions producing instructions "
3933 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003934
Chris Lattner8cab0212008-01-05 22:25:12 +00003935 bool IterateInference;
3936 bool InferredAllPatternTypes, InferredAllResultTypes;
3937 do {
3938 // Infer as many types as possible. If we cannot infer all of them, we
3939 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003940 InferredAllPatternTypes =
3941 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003942
Chris Lattner8cab0212008-01-05 22:25:12 +00003943 // Infer as many types as possible. If we cannot infer all of them, we
3944 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003945 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003946 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003947
Chris Lattnerfdc20712010-03-18 23:15:10 +00003948 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003949
Chris Lattner8cab0212008-01-05 22:25:12 +00003950 // Apply the type of the result to the source pattern. This helps us
3951 // resolve cases where the input type is known to be a pointer type (which
3952 // is considered resolved), but the result knows it needs to be 32- or
3953 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003954 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003955 Pattern->getTree(0)->getNumTypes());
3956 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003957 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3958 i, Result.getTree(0)->getExtType(i), Result);
3959 IterateInference |= Result.getTree(0)->UpdateNodeType(
3960 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003961 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003962
Chris Lattnercabe0372010-03-15 06:00:16 +00003963 // If our iteration has converged and the input pattern's types are fully
3964 // resolved but the result pattern is not fully resolved, we may have a
3965 // situation where we have two instructions in the result pattern and
3966 // the instructions require a common register class, but don't care about
3967 // what actual MVT is used. This is actually a bug in our modelling:
3968 // output patterns should have register classes, not MVTs.
3969 //
3970 // In any case, to handle this, we just go through and disambiguate some
3971 // arbitrary types to the result pattern's nodes.
3972 if (!IterateInference && InferredAllPatternTypes &&
3973 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003974 IterateInference =
3975 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003976 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003977
Chris Lattner8cab0212008-01-05 22:25:12 +00003978 // Verify that we inferred enough types that we can do something with the
3979 // pattern and result. If these fire the user has to add type casts.
3980 if (!InferredAllPatternTypes)
3981 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003982 if (!InferredAllResultTypes) {
3983 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003984 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003985 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003986
Chris Lattner8cab0212008-01-05 22:25:12 +00003987 // Validate that the input pattern is correct.
3988 std::map<std::string, TreePatternNode*> InstInputs;
3989 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003990 std::vector<Record*> InstImpResults;
3991 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3992 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3993 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003994 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003995
3996 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003997 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003998 std::vector<TreePatternNode*> ResultNodeOperands;
3999 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
4000 TreePatternNode *OpNode = DstPattern->getChild(ii);
4001 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00004002 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00004003 std::vector<TreePatternNode*> Children;
4004 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00004005 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00004006 }
4007 ResultNodeOperands.push_back(OpNode);
4008 }
David Blaikiecf195302014-11-17 22:55:41 +00004009 DstPattern = Result.getOnlyTree();
4010 if (!DstPattern->isLeaf())
4011 DstPattern = new TreePatternNode(DstPattern->getOperator(),
4012 ResultNodeOperands,
4013 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004014
David Blaikiecf195302014-11-17 22:55:41 +00004015 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
4016 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
4017
4018 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00004019 Temp.InferAllTypes();
4020
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004021 // A pattern may end up with an "impossible" type, i.e. a situation
4022 // where all types have been eliminated for some node in this pattern.
4023 // This could occur for intrinsics that only make sense for a specific
4024 // value type, and use a specific register class. If, for some mode,
4025 // that register class does not accept that type, the type inference
4026 // will lead to a contradiction, which is not an error however, but
4027 // a sign that this pattern will simply never match.
4028 if (Pattern->getTree(0)->hasPossibleType() &&
4029 Temp.getOnlyTree()->hasPossibleType()) {
4030 ListInit *Preds = CurPattern->getValueAsListInit("Predicates");
4031 int Complexity = CurPattern->getValueAsInt("AddedComplexity");
Daniel Sanders7e523672017-11-11 03:23:44 +00004032 if (PatternRewriter)
4033 PatternRewriter(Pattern);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004034 AddPatternToMatch(
4035 Pattern,
4036 PatternToMatch(
4037 CurPattern, makePredList(Preds), Pattern->getTree(0),
4038 Temp.getOnlyTree(), std::move(InstImpResults), Complexity,
4039 CurPattern->getID()));
4040 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004041 }
4042}
4043
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004044static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
4045 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4046 for (const auto &I : VTS)
4047 Modes.insert(I.first);
4048
4049 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4050 collectModes(Modes, N->getChild(i));
4051}
4052
4053void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4054 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4055 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4056 std::vector<PatternToMatch> Copy = PatternsToMatch;
4057 PatternsToMatch.clear();
4058
4059 auto AppendPattern = [this,&ModeChecks](PatternToMatch &P, unsigned Mode) {
4060 TreePatternNode *NewSrc = P.SrcPattern->clone();
4061 TreePatternNode *NewDst = P.DstPattern->clone();
4062 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4063 delete NewSrc;
4064 delete NewDst;
4065 return;
4066 }
4067
4068 std::vector<Predicate> Preds = P.Predicates;
4069 const std::vector<Predicate> &MC = ModeChecks[Mode];
4070 Preds.insert(Preds.end(), MC.begin(), MC.end());
4071 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, NewSrc, NewDst,
4072 P.getDstRegs(), P.getAddedComplexity(),
4073 Record::getNewUID(), Mode);
4074 };
4075
4076 for (PatternToMatch &P : Copy) {
4077 TreePatternNode *SrcP = nullptr, *DstP = nullptr;
4078 if (P.SrcPattern->hasProperTypeByHwMode())
4079 SrcP = P.SrcPattern;
4080 if (P.DstPattern->hasProperTypeByHwMode())
4081 DstP = P.DstPattern;
4082 if (!SrcP && !DstP) {
4083 PatternsToMatch.push_back(P);
4084 continue;
4085 }
4086
4087 std::set<unsigned> Modes;
4088 if (SrcP)
4089 collectModes(Modes, SrcP);
4090 if (DstP)
4091 collectModes(Modes, DstP);
4092
4093 // The predicate for the default mode needs to be constructed for each
4094 // pattern separately.
4095 // Since not all modes must be present in each pattern, if a mode m is
4096 // absent, then there is no point in constructing a check for m. If such
4097 // a check was created, it would be equivalent to checking the default
4098 // mode, except not all modes' predicates would be a part of the checking
4099 // code. The subsequently generated check for the default mode would then
4100 // have the exact same patterns, but a different predicate code. To avoid
4101 // duplicated patterns with different predicate checks, construct the
4102 // default check as a negation of all predicates that are actually present
4103 // in the source/destination patterns.
4104 std::vector<Predicate> DefaultPred;
4105
4106 for (unsigned M : Modes) {
4107 if (M == DefaultMode)
4108 continue;
4109 if (ModeChecks.find(M) != ModeChecks.end())
4110 continue;
4111
4112 // Fill the map entry for this mode.
4113 const HwMode &HM = CGH.getMode(M);
4114 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4115
4116 // Add negations of the HM's predicates to the default predicate.
4117 DefaultPred.emplace_back(Predicate(HM.Features, false));
4118 }
4119
4120 for (unsigned M : Modes) {
4121 if (M == DefaultMode)
4122 continue;
4123 AppendPattern(P, M);
4124 }
4125
4126 bool HasDefault = Modes.count(DefaultMode);
4127 if (HasDefault)
4128 AppendPattern(P, DefaultMode);
4129 }
4130}
4131
4132/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004133typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004134
4135static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4136 if (N->isLeaf()) {
Zachary Turner249dc142017-09-20 18:01:40 +00004137 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004138 DepMap[N->getName()]++;
4139 } else {
4140 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4141 FindDepVarsOf(N->getChild(i), DepMap);
4142 }
4143}
4144
4145/// Find dependent variables within child patterns
4146static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
4147 DepVarMap depcounts;
4148 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004149 for (const auto &Pair : depcounts) {
4150 if (Pair.getValue() > 1)
4151 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004152 }
4153}
4154
4155#ifndef NDEBUG
4156/// Dump the dependent variable set:
4157static void DumpDepVars(MultipleUseVarSet &DepVars) {
4158 if (DepVars.empty()) {
4159 DEBUG(errs() << "<empty set>");
4160 } else {
4161 DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004162 for (const auto &DepVar : DepVars) {
4163 DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004164 }
4165 DEBUG(errs() << "]");
4166 }
4167}
4168#endif
4169
4170
Chris Lattner8cab0212008-01-05 22:25:12 +00004171/// CombineChildVariants - Given a bunch of permutations of each child of the
4172/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004173static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00004174 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
4175 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004176 CodeGenDAGPatterns &CDP,
4177 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004178 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004179 for (const auto &Variants : ChildVariants)
4180 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004181 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004182
Chris Lattner8cab0212008-01-05 22:25:12 +00004183 // The end result is an all-pairs construction of the resultant pattern.
4184 std::vector<unsigned> Idxs;
4185 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004186 bool NotDone;
4187 do {
4188#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00004189 DEBUG(if (!Idxs.empty()) {
4190 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00004191 for (unsigned Idx : Idxs) {
4192 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00004193 }
4194 errs() << "]\n";
4195 });
Scott Michel94420742008-03-05 17:49:05 +00004196#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004197 // Create the variant and add it to the output list.
4198 std::vector<TreePatternNode*> NewChildren;
4199 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4200 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00004201 auto R = llvm::make_unique<TreePatternNode>(
4202 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004203
Chris Lattner8cab0212008-01-05 22:25:12 +00004204 // Copy over properties.
4205 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00004206 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00004207 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00004208 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4209 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004210
Scott Michel94420742008-03-05 17:49:05 +00004211 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004212 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004213 // Scan to see if this pattern has already been emitted. We can get
4214 // duplication due to things like commuting:
4215 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4216 // which are the same pattern. Ignore the dups.
4217 if (R->canPatternMatch(ErrString, CDP) &&
David Majnemer0a16c222016-08-11 21:15:00 +00004218 none_of(OutVariants, [&](TreePatternNode *Variant) {
4219 return R->isIsomorphicTo(Variant, DepVars);
4220 }))
David Blaikiefda69dd2015-11-22 20:11:21 +00004221 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004222
Scott Michel94420742008-03-05 17:49:05 +00004223 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004224 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004225 // [0, 0], [0, 1], [1, 0], [1, 1].
4226 int IdxsIdx;
4227 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4228 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4229 Idxs[IdxsIdx] = 0;
4230 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004231 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004232 }
Scott Michel94420742008-03-05 17:49:05 +00004233 NotDone = (IdxsIdx >= 0);
4234 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004235}
4236
4237/// CombineChildVariants - A helper function for binary operators.
4238///
Jim Grosbach65586fe2010-12-21 16:16:00 +00004239static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00004240 const std::vector<TreePatternNode*> &LHS,
4241 const std::vector<TreePatternNode*> &RHS,
4242 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004243 CodeGenDAGPatterns &CDP,
4244 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004245 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4246 ChildVariants.push_back(LHS);
4247 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004248 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004249}
Chris Lattner8cab0212008-01-05 22:25:12 +00004250
4251
4252static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
4253 std::vector<TreePatternNode *> &Children) {
4254 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4255 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004256
Chris Lattner8cab0212008-01-05 22:25:12 +00004257 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00004258 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004259 N->getTransformFn()) {
4260 Children.push_back(N);
4261 return;
4262 }
4263
4264 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
4265 Children.push_back(N->getChild(0));
4266 else
4267 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
4268
4269 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
4270 Children.push_back(N->getChild(1));
4271 else
4272 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
4273}
4274
4275/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4276/// the (potentially recursive) pattern by using algebraic laws.
4277///
4278static void GenerateVariantsOf(TreePatternNode *N,
4279 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004280 CodeGenDAGPatterns &CDP,
4281 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004282 // We cannot permute leaves or ComplexPattern uses.
4283 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004284 OutVariants.push_back(N);
4285 return;
4286 }
4287
4288 // Look up interesting info about the node.
4289 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4290
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004291 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004292 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004293 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00004294 std::vector<TreePatternNode*> MaximalChildren;
4295 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4296
4297 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4298 // permutations.
4299 if (MaximalChildren.size() == 3) {
4300 // Find the variants of all of our maximal children.
4301 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004302 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4303 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4304 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004305
Chris Lattner8cab0212008-01-05 22:25:12 +00004306 // There are only two ways we can permute the tree:
4307 // (A op B) op C and A op (B op C)
4308 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004309
Chris Lattner8cab0212008-01-05 22:25:12 +00004310 // Generate legal pair permutations of A/B/C.
4311 std::vector<TreePatternNode*> ABVariants;
4312 std::vector<TreePatternNode*> BAVariants;
4313 std::vector<TreePatternNode*> ACVariants;
4314 std::vector<TreePatternNode*> CAVariants;
4315 std::vector<TreePatternNode*> BCVariants;
4316 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00004317 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4318 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4319 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4320 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4321 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4322 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004323
4324 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00004325 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4326 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4327 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4328 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4329 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4330 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004331
4332 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00004333 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4334 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4335 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4336 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4337 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4338 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004339 return;
4340 }
4341 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004342
Chris Lattner8cab0212008-01-05 22:25:12 +00004343 // Compute permutations of all children.
4344 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4345 ChildVariants.resize(N->getNumChildren());
4346 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00004347 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004348
4349 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00004350 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004351
4352 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004353 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4354 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004355 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004356 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004357 // Don't count children which are actually register references.
4358 unsigned NC = 0;
4359 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4360 TreePatternNode *Child = N->getChild(i);
4361 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00004362 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004363 Record *RR = DI->getDef();
4364 if (RR->isSubClassOf("Register"))
4365 continue;
4366 }
4367 NC++;
4368 }
4369 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004370 if (isCommIntrinsic) {
4371 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4372 // operands are the commutative operands, and there might be more operands
4373 // after those.
4374 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004375 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00004376 std::vector<std::vector<TreePatternNode*> > Variants;
4377 Variants.push_back(ChildVariants[0]); // Intrinsic id.
4378 Variants.push_back(ChildVariants[2]);
4379 Variants.push_back(ChildVariants[1]);
4380 for (unsigned i = 3; i != NC; ++i)
4381 Variants.push_back(ChildVariants[i]);
4382 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004383 } else if (NC == N->getNumChildren()) {
4384 std::vector<std::vector<TreePatternNode*> > Variants;
4385 Variants.push_back(ChildVariants[1]);
4386 Variants.push_back(ChildVariants[0]);
4387 for (unsigned i = 2; i != NC; ++i)
4388 Variants.push_back(ChildVariants[i]);
4389 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4390 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004391 }
4392}
4393
4394
4395// GenerateVariants - Generate variants. For example, commutative patterns can
4396// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004397void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00004398 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004399
Chris Lattner8cab0212008-01-05 22:25:12 +00004400 // Loop over all of the patterns we've collected, checking to see if we can
4401 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004402 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004403 // the .td file having to contain tons of variants of instructions.
4404 //
4405 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4406 // intentionally do not reconsider these. Any variants of added patterns have
4407 // already been added.
4408 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00004409 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00004410 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00004411 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004412 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00004413 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00004414 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00004415 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00004416 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00004417 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004418
4419 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00004420 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004421 continue;
4422
Chris Lattner34822f62009-08-23 04:44:11 +00004423 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00004424 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00004425 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004426
4427 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4428 TreePatternNode *Variant = Variants[v];
4429
Chris Lattner34822f62009-08-23 04:44:11 +00004430 DEBUG(errs() << " VAR#" << v << ": ";
4431 Variant->dump();
4432 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004433
Chris Lattner8cab0212008-01-05 22:25:12 +00004434 // Scan to see if an instruction or explicit pattern already matches this.
4435 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004436 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004437 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004438 if (PatternsToMatch[i].getPredicates() !=
4439 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00004440 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004441 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004442 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4443 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00004444 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004445 AlreadyExists = true;
4446 break;
4447 }
4448 }
4449 // If we already have it, ignore the variant.
4450 if (AlreadyExists) continue;
4451
4452 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004453 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004454 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4455 Variant, PatternsToMatch[i].getDstPattern(),
4456 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004457 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00004458 }
4459
Chris Lattner34822f62009-08-23 04:44:11 +00004460 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004461 }
4462}