blob: 3b400c1262ecf82de6940fe57767c5e10a10a2d5 [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 {
821 return isLoad() || isStore() ||
822 !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
828 if (!isLoad() && !isStore()) {
829 if (isUnindexed())
830 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
831 "IsUnindexed requires IsLoad or IsStore");
832
833 Record *MemoryVT = getMemoryVT();
834 Record *ScalarMemoryVT = getScalarMemoryVT();
835
836 if (MemoryVT)
837 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
838 "MemoryVT requires IsLoad or IsStore");
839 if (ScalarMemoryVT)
840 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
841 "ScalarMemoryVT requires IsLoad or IsStore");
842 }
843
844 if (isLoad() && isStore())
845 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
846 "IsLoad and IsStore are mutually exclusive");
847
848 if (isLoad()) {
849 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
850 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
851 getScalarMemoryVT() == nullptr)
852 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
853 "IsLoad cannot be used by itself");
854 } else {
855 if (isNonExtLoad())
856 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
857 "IsNonExtLoad requires IsLoad");
858 if (isAnyExtLoad())
859 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
860 "IsAnyExtLoad requires IsLoad");
861 if (isSignExtLoad())
862 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
863 "IsSignExtLoad requires IsLoad");
864 if (isZeroExtLoad())
865 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
866 "IsZeroExtLoad requires IsLoad");
867 }
868
869 if (isStore()) {
870 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
871 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
872 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
873 "IsStore cannot be used by itself");
874 } else {
875 if (isNonTruncStore())
876 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
877 "IsNonTruncStore requires IsStore");
878 if (isTruncStore())
879 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
880 "IsTruncStore requires IsStore");
881 }
882
883 if (isLoad() || isStore()) {
884 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
885
886 if (isUnindexed())
887 Code += ("if (cast<" + SDNodeName +
888 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
889 "return false;\n")
890 .str();
891
892 if (isLoad()) {
893 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
894 isZeroExtLoad()) > 1)
895 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
896 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
897 "IsZeroExtLoad are mutually exclusive");
898 if (isNonExtLoad())
899 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
900 "ISD::NON_EXTLOAD) return false;\n";
901 if (isAnyExtLoad())
902 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
903 "return false;\n";
904 if (isSignExtLoad())
905 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
906 "return false;\n";
907 if (isZeroExtLoad())
908 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
909 "return false;\n";
910 } else {
911 if ((isNonTruncStore() + isTruncStore()) > 1)
912 PrintFatalError(
913 getOrigPatFragRecord()->getRecord()->getLoc(),
914 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
915 if (isNonTruncStore())
916 Code +=
917 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
918 if (isTruncStore())
919 Code +=
920 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
921 }
922
923 Record *MemoryVT = getMemoryVT();
924 Record *ScalarMemoryVT = getScalarMemoryVT();
925
926 if (MemoryVT)
927 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
928 MemoryVT->getName() + ") return false;\n")
929 .str();
930 if (ScalarMemoryVT)
931 Code += ("if (cast<" + SDNodeName +
932 ">(N)->getMemoryVT().getScalarType() != MVT::" +
933 ScalarMemoryVT->getName() + ") return false;\n")
934 .str();
935 }
936
937 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
938
939 Code += PredicateCode;
940
941 if (PredicateCode.empty() && !Code.empty())
942 Code += "return true;\n";
943
944 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +0000945}
946
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000947bool TreePredicateFn::hasImmCode() const {
948 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
949}
950
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000951std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000952 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000953}
954
Daniel Sanders649c5852017-10-13 20:42:18 +0000955bool TreePredicateFn::immCodeUsesAPInt() const {
956 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
957}
958
959bool TreePredicateFn::immCodeUsesAPFloat() const {
960 bool Unset;
961 // The return value will be false when IsAPFloat is unset.
962 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
963 Unset);
964}
965
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000966bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
967 bool Value) const {
968 bool Unset;
969 bool Result =
970 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
971 if (Unset)
972 return false;
973 return Result == Value;
974}
975bool TreePredicateFn::isLoad() const {
976 return isPredefinedPredicateEqualTo("IsLoad", true);
977}
978bool TreePredicateFn::isStore() const {
979 return isPredefinedPredicateEqualTo("IsStore", true);
980}
981bool TreePredicateFn::isUnindexed() const {
982 return isPredefinedPredicateEqualTo("IsUnindexed", true);
983}
984bool TreePredicateFn::isNonExtLoad() const {
985 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
986}
987bool TreePredicateFn::isAnyExtLoad() const {
988 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
989}
990bool TreePredicateFn::isSignExtLoad() const {
991 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
992}
993bool TreePredicateFn::isZeroExtLoad() const {
994 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
995}
996bool TreePredicateFn::isNonTruncStore() const {
997 return isPredefinedPredicateEqualTo("IsTruncStore", false);
998}
999bool TreePredicateFn::isTruncStore() const {
1000 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1001}
1002Record *TreePredicateFn::getMemoryVT() const {
1003 Record *R = getOrigPatFragRecord()->getRecord();
1004 if (R->isValueUnset("MemoryVT"))
1005 return nullptr;
1006 return R->getValueAsDef("MemoryVT");
1007}
1008Record *TreePredicateFn::getScalarMemoryVT() const {
1009 Record *R = getOrigPatFragRecord()->getRecord();
1010 if (R->isValueUnset("ScalarMemoryVT"))
1011 return nullptr;
1012 return R->getValueAsDef("ScalarMemoryVT");
1013}
1014
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001015StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001016 if (immCodeUsesAPInt())
1017 return "const APInt &";
1018 if (immCodeUsesAPFloat())
1019 return "const APFloat &";
1020 return "int64_t";
1021}
Chris Lattner514e2922011-04-17 21:38:24 +00001022
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001023StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001024 if (immCodeUsesAPInt())
1025 return "APInt";
1026 else if (immCodeUsesAPFloat())
1027 return "APFloat";
1028 return "I64";
1029}
1030
Chris Lattner514e2922011-04-17 21:38:24 +00001031/// isAlwaysTrue - Return true if this is a noop predicate.
1032bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001033 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001034}
1035
1036/// Return the name to use in the generated code to reference this, this is
1037/// "Predicate_foo" if from a pattern fragment "foo".
1038std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001039 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001040}
1041
1042/// getCodeToRunOnSDNode - Return the code for the function body that
1043/// evaluates this predicate. The argument is expected to be in "Node",
1044/// not N. This handles casting and conversion to a concrete node type as
1045/// appropriate.
1046std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001047 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001048 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001049 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001050 if (isLoad())
1051 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1052 "IsLoad cannot be used with ImmLeaf or its subclasses");
1053 if (isStore())
1054 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1055 "IsStore cannot be used with ImmLeaf or its subclasses");
1056 if (isUnindexed())
1057 PrintFatalError(
1058 getOrigPatFragRecord()->getRecord()->getLoc(),
1059 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1060 if (isNonExtLoad())
1061 PrintFatalError(
1062 getOrigPatFragRecord()->getRecord()->getLoc(),
1063 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1064 if (isAnyExtLoad())
1065 PrintFatalError(
1066 getOrigPatFragRecord()->getRecord()->getLoc(),
1067 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1068 if (isSignExtLoad())
1069 PrintFatalError(
1070 getOrigPatFragRecord()->getRecord()->getLoc(),
1071 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1072 if (isZeroExtLoad())
1073 PrintFatalError(
1074 getOrigPatFragRecord()->getRecord()->getLoc(),
1075 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1076 if (isNonTruncStore())
1077 PrintFatalError(
1078 getOrigPatFragRecord()->getRecord()->getLoc(),
1079 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1080 if (isTruncStore())
1081 PrintFatalError(
1082 getOrigPatFragRecord()->getRecord()->getLoc(),
1083 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1084 if (getMemoryVT())
1085 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1086 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1087 if (getScalarMemoryVT())
1088 PrintFatalError(
1089 getOrigPatFragRecord()->getRecord()->getLoc(),
1090 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1091
1092 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001093 if (immCodeUsesAPFloat())
1094 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1095 else if (immCodeUsesAPInt())
1096 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1097 else
1098 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001099 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001100 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001101
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001102 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001103 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001104 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +00001105 if (PatFragRec->getOnlyTree()->isLeaf())
1106 ClassName = "SDNode";
1107 else {
1108 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1109 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1110 }
1111 std::string Result;
1112 if (ClassName == "SDNode")
1113 Result = " SDNode *N = Node;\n";
1114 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001115 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001116
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001117 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +00001118}
1119
Chris Lattner8cab0212008-01-05 22:25:12 +00001120//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001121// PatternToMatch implementation
1122//
1123
Chris Lattner05925fe2010-03-29 01:40:38 +00001124/// getPatternSize - Return the 'size' of this pattern. We want to match large
1125/// patterns before small ones. This is used to determine the size of a
1126/// pattern.
1127static unsigned getPatternSize(const TreePatternNode *P,
1128 const CodeGenDAGPatterns &CGP) {
1129 unsigned Size = 3; // The node itself.
1130 // If the root node is a ConstantSDNode, increases its size.
1131 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +00001132 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001133 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001134
Simon Pilgrim40687012017-09-26 12:59:01 +00001135 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001136 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001137 // We don't want to count any children twice, so return early.
1138 return Size;
1139 }
1140
Chris Lattner05925fe2010-03-29 01:40:38 +00001141 // If this node has some predicate function that must match, it adds to the
1142 // complexity of this node.
1143 if (!P->getPredicateFns().empty())
1144 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001145
Chris Lattner05925fe2010-03-29 01:40:38 +00001146 // Count children in the count if they are also nodes.
1147 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
Simon Pilgrima932bfc2017-09-27 10:03:17 +00001148 const TreePatternNode *Child = P->getChild(i);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001149 if (!Child->isLeaf() && Child->getNumTypes()) {
1150 const TypeSetByHwMode &T0 = Child->getType(0);
1151 // At this point, all variable type sets should be simple, i.e. only
1152 // have a default mode.
1153 if (T0.getMachineValueType() != MVT::Other) {
1154 Size += getPatternSize(Child, CGP);
1155 continue;
1156 }
1157 }
1158 if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001159 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001160 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1161 else if (Child->getComplexPatternInfo(CGP))
1162 Size += getPatternSize(Child, CGP);
1163 else if (!Child->getPredicateFns().empty())
1164 ++Size;
1165 }
1166 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001167
Chris Lattner05925fe2010-03-29 01:40:38 +00001168 return Size;
1169}
1170
1171/// Compute the complexity metric for the input pattern. This roughly
1172/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001173int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001174getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1175 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1176}
1177
Dan Gohman49e19e92008-08-22 00:20:26 +00001178/// getPredicateCheck - Return a single string containing all of this
1179/// pattern's predicates concatenated with "&&" operators.
1180///
1181std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001182 SmallVector<const Predicate*,4> PredList;
1183 for (const Predicate &P : Predicates)
1184 PredList.push_back(&P);
1185 std::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +00001186
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001187 std::string Check;
1188 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1189 if (i != 0)
1190 Check += " && ";
1191 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001192 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001193 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001194}
1195
1196//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001197// SDTypeConstraint implementation
1198//
1199
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001200SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001201 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001202
Chris Lattner8cab0212008-01-05 22:25:12 +00001203 if (R->isSubClassOf("SDTCisVT")) {
1204 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001205 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1206 for (const auto &P : VVT)
1207 if (P.second == MVT::isVoid)
1208 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001209 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1210 ConstraintType = SDTCisPtrTy;
1211 } else if (R->isSubClassOf("SDTCisInt")) {
1212 ConstraintType = SDTCisInt;
1213 } else if (R->isSubClassOf("SDTCisFP")) {
1214 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001215 } else if (R->isSubClassOf("SDTCisVec")) {
1216 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001217 } else if (R->isSubClassOf("SDTCisSameAs")) {
1218 ConstraintType = SDTCisSameAs;
1219 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1220 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1221 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001222 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001223 R->getValueAsInt("OtherOperandNum");
1224 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1225 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001226 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001227 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001228 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1229 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001230 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001231 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1232 ConstraintType = SDTCisSubVecOfVec;
1233 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1234 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001235 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1236 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001237 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1238 for (const auto &P : VVT) {
1239 MVT T = P.second;
1240 if (T.isVector())
1241 PrintFatalError(R->getLoc(),
1242 "Cannot use vector type as SDTCVecEltisVT");
1243 if (!T.isInteger() && !T.isFloatingPoint())
1244 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1245 "as SDTCVecEltisVT");
1246 }
Craig Topper0be34582015-03-05 07:11:34 +00001247 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1248 ConstraintType = SDTCisSameNumEltsAs;
1249 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1250 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001251 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1252 ConstraintType = SDTCisSameSizeAs;
1253 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1254 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001255 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001256 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001257 }
1258}
1259
1260/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001261/// N, and the result number in ResNo.
1262static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1263 const SDNodeInfo &NodeInfo,
1264 unsigned &ResNo) {
1265 unsigned NumResults = NodeInfo.getNumResults();
1266 if (OpNo < NumResults) {
1267 ResNo = OpNo;
1268 return N;
1269 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001270
Chris Lattner2db7aba2010-03-19 21:56:21 +00001271 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001272
Chris Lattner2db7aba2010-03-19 21:56:21 +00001273 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001274 std::string S;
1275 raw_string_ostream OS(S);
1276 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001277 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +00001278 N->print(OS);
1279 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001280 }
1281
Chris Lattner2db7aba2010-03-19 21:56:21 +00001282 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001283}
1284
1285/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1286/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001287/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001288bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1289 const SDNodeInfo &NodeInfo,
1290 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001291 if (TP.hasError())
1292 return false;
1293
Chris Lattner2db7aba2010-03-19 21:56:21 +00001294 unsigned ResNo = 0; // The result number being referenced.
1295 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001296 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001297
Chris Lattner8cab0212008-01-05 22:25:12 +00001298 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001299 case SDTCisVT:
1300 // Operand must be a particular type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001301 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001302 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001303 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001304 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001305 case SDTCisInt:
1306 // Require it to be one of the legal integer VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001307 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001308 case SDTCisFP:
1309 // Require it to be one of the legal fp VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001310 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001311 case SDTCisVec:
1312 // Require it to be one of the legal vector VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001313 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001314 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001315 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001316 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001317 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001318 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1319 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001320 }
1321 case SDTCisVTSmallerThanOp: {
1322 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1323 // have an integer type that is smaller than the VT.
1324 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001325 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001326 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001327 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001328 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001329 return false;
1330 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001331 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1332 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1333 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1334 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001335
Chris Lattner2db7aba2010-03-19 21:56:21 +00001336 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001337 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001338 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1339 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001340
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001341 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001342 }
1343 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001344 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001345 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001346 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1347 BResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001348 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1349 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001350 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001351 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001352 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001353 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001354 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1355 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001356 // Filter vector types out of VecOperand that don't have the right element
1357 // type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001358 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1359 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001360 }
David Greene127fd1d2011-01-24 20:53:18 +00001361 case SDTCisSubVecOfVec: {
1362 unsigned VResNo = 0;
1363 TreePatternNode *BigVecOperand =
1364 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1365 VResNo);
1366
1367 // Filter vector types out of BigVecOperand that don't have the
1368 // right subvector type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001369 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1370 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001371 }
Craig Topper0be34582015-03-05 07:11:34 +00001372 case SDTCVecEltisVT: {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001373 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001374 }
1375 case SDTCisSameNumEltsAs: {
1376 unsigned OResNo = 0;
1377 TreePatternNode *OtherNode =
1378 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1379 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001380 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1381 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001382 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001383 case SDTCisSameSizeAs: {
1384 unsigned OResNo = 0;
1385 TreePatternNode *OtherNode =
1386 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1387 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001388 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1389 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001390 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001391 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001392 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001393}
1394
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001395// Update the node type to match an instruction operand or result as specified
1396// in the ins or outs lists on the instruction definition. Return true if the
1397// type was actually changed.
1398bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1399 Record *Operand,
1400 TreePattern &TP) {
1401 // The 'unknown' operand indicates that types should be inferred from the
1402 // context.
1403 if (Operand->isSubClassOf("unknown_class"))
1404 return false;
1405
1406 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001407 if (Operand->isSubClassOf("Operand")) {
1408 Record *R = Operand->getValueAsDef("Type");
1409 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1410 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1411 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001412
1413 // PointerLikeRegClass has a type that is determined at runtime.
1414 if (Operand->isSubClassOf("PointerLikeRegClass"))
1415 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1416
1417 // Both RegisterClass and RegisterOperand operands derive their types from a
1418 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001419 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001420 if (Operand->isSubClassOf("RegisterClass"))
1421 RC = Operand;
1422 else if (Operand->isSubClassOf("RegisterOperand"))
1423 RC = Operand->getValueAsDef("RegClass");
1424
1425 assert(RC && "Unknown operand type");
1426 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1427 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1428}
1429
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001430bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1431 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1432 if (!TP.getInfer().isConcrete(Types[i], true))
1433 return true;
1434 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1435 if (getChild(i)->ContainsUnresolvedType(TP))
1436 return true;
1437 return false;
1438}
1439
1440bool TreePatternNode::hasProperTypeByHwMode() const {
1441 for (const TypeSetByHwMode &S : Types)
1442 if (!S.isDefaultOnly())
1443 return true;
1444 for (TreePatternNode *C : Children)
1445 if (C->hasProperTypeByHwMode())
1446 return true;
1447 return false;
1448}
1449
1450bool TreePatternNode::hasPossibleType() const {
1451 for (const TypeSetByHwMode &S : Types)
1452 if (!S.isPossible())
1453 return false;
1454 for (TreePatternNode *C : Children)
1455 if (!C->hasPossibleType())
1456 return false;
1457 return true;
1458}
1459
1460bool TreePatternNode::setDefaultMode(unsigned Mode) {
1461 for (TypeSetByHwMode &S : Types) {
1462 S.makeSimple(Mode);
1463 // Check if the selected mode had a type conflict.
1464 if (S.get(DefaultMode).empty())
1465 return false;
1466 }
1467 for (TreePatternNode *C : Children)
1468 if (!C->setDefaultMode(Mode))
1469 return false;
1470 return true;
1471}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001472
Chris Lattner8cab0212008-01-05 22:25:12 +00001473//===----------------------------------------------------------------------===//
1474// SDNodeInfo implementation
1475//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001476SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001477 EnumName = R->getValueAsString("Opcode");
1478 SDClassName = R->getValueAsString("SDClass");
1479 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1480 NumResults = TypeProfile->getValueAsInt("NumResults");
1481 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001482
Chris Lattner8cab0212008-01-05 22:25:12 +00001483 // Parse the properties.
1484 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001485 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1486 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001487 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001488 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001489 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001490 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001491 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001492 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001493 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001494 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001495 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001496 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001497 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001498 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001499 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001500 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001501 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001502 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001503 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001504 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001505 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001506 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001507 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001508 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001509 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001510 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001511 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001512 }
1513 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001514
1515
Chris Lattner8cab0212008-01-05 22:25:12 +00001516 // Parse the type constraints.
1517 std::vector<Record*> ConstraintList =
1518 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001519 for (Record *R : ConstraintList)
1520 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001521}
1522
Chris Lattner99e53b32010-02-28 00:22:30 +00001523/// getKnownType - If the type constraints on this node imply a fixed type
1524/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001525/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001526MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001527 unsigned NumResults = getNumResults();
1528 assert(NumResults <= 1 &&
1529 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001530 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001531
Craig Topper306cb122015-11-22 20:46:24 +00001532 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001533 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001534 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001535 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001536
Craig Topper306cb122015-11-22 20:46:24 +00001537 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001538 default: break;
1539 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001540 if (Constraint.VVT.isSimple())
1541 return Constraint.VVT.getSimple().SimpleTy;
1542 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001543 case SDTypeConstraint::SDTCisPtrTy:
1544 return MVT::iPTR;
1545 }
1546 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001547 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001548}
1549
Chris Lattner8cab0212008-01-05 22:25:12 +00001550//===----------------------------------------------------------------------===//
1551// TreePatternNode implementation
1552//
1553
1554TreePatternNode::~TreePatternNode() {
1555#if 0 // FIXME: implement refcounted tree nodes!
1556 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1557 delete getChild(i);
1558#endif
1559}
1560
Chris Lattnerf1447252010-03-19 21:37:09 +00001561static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1562 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001563 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001564 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001565
Chris Lattner2109cb42010-03-22 20:56:36 +00001566 if (Operator->isSubClassOf("Intrinsic"))
1567 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001568
Chris Lattnerf1447252010-03-19 21:37:09 +00001569 if (Operator->isSubClassOf("SDNode"))
1570 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001571
Chris Lattnerf1447252010-03-19 21:37:09 +00001572 if (Operator->isSubClassOf("PatFrag")) {
1573 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1574 // the forward reference case where one pattern fragment references another
1575 // before it is processed.
1576 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1577 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001578
Chris Lattnerf1447252010-03-19 21:37:09 +00001579 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001580 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001581 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001582 if (Tree)
1583 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1584 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001585 assert(Op && "Invalid Fragment");
1586 return GetNumNodeResults(Op, CDP);
1587 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001588
Chris Lattnerf1447252010-03-19 21:37:09 +00001589 if (Operator->isSubClassOf("Instruction")) {
1590 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001591
Craig Topper3a8eb892015-03-20 05:09:06 +00001592 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1593
1594 // Subtract any defaulted outputs.
1595 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1596 Record *OperandNode = InstInfo.Operands[i].Rec;
1597
1598 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1599 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1600 --NumDefsToAdd;
1601 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001602
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001603 // Add on one implicit def if it has a resolvable type.
1604 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1605 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001606 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001607 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001608
Chris Lattnerf1447252010-03-19 21:37:09 +00001609 if (Operator->isSubClassOf("SDNodeXForm"))
1610 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001611
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001612 if (Operator->isSubClassOf("ValueType"))
1613 return 1; // A type-cast of one result.
1614
Tim Northoverc807a172014-05-20 11:52:46 +00001615 if (Operator->isSubClassOf("ComplexPattern"))
1616 return 1;
1617
Matthias Braun8c209aa2017-01-28 02:02:38 +00001618 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001619 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001620}
1621
1622void TreePatternNode::print(raw_ostream &OS) const {
1623 if (isLeaf())
1624 OS << *getLeafValue();
1625 else
1626 OS << '(' << getOperator()->getName();
1627
Zachary Turner249dc142017-09-20 18:01:40 +00001628 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1629 OS << ':';
1630 getExtType(i).writeToStream(OS);
1631 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001632
1633 if (!isLeaf()) {
1634 if (getNumChildren() != 0) {
1635 OS << " ";
1636 getChild(0)->print(OS);
1637 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1638 OS << ", ";
1639 getChild(i)->print(OS);
1640 }
1641 }
1642 OS << ")";
1643 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001644
Craig Topper306cb122015-11-22 20:46:24 +00001645 for (const TreePredicateFn &Pred : PredicateFns)
1646 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001647 if (TransformFn)
1648 OS << "<<X:" << TransformFn->getName() << ">>";
1649 if (!getName().empty())
1650 OS << ":$" << getName();
1651
1652}
1653void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001654 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001655}
1656
Scott Michel94420742008-03-05 17:49:05 +00001657/// isIsomorphicTo - Return true if this node is recursively
1658/// isomorphic to the specified node. For this comparison, the node's
1659/// entire state is considered. The assigned name is ignored, since
1660/// nodes with differing names are considered isomorphic. However, if
1661/// the assigned name is present in the dependent variable set, then
1662/// the assigned name is considered significant and the node is
1663/// isomorphic if the names match.
1664bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1665 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001666 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001667 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001668 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001669 getTransformFn() != N->getTransformFn())
1670 return false;
1671
1672 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001673 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1674 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001675 return ((DI->getDef() == NDI->getDef())
1676 && (DepVars.find(getName()) == DepVars.end()
1677 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001678 }
1679 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001680 return getLeafValue() == N->getLeafValue();
1681 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001682
Chris Lattner8cab0212008-01-05 22:25:12 +00001683 if (N->getOperator() != getOperator() ||
1684 N->getNumChildren() != getNumChildren()) return false;
1685 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001686 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001687 return false;
1688 return true;
1689}
1690
1691/// clone - Make a copy of this tree and all of its children.
1692///
1693TreePatternNode *TreePatternNode::clone() const {
1694 TreePatternNode *New;
1695 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001696 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001697 } else {
1698 std::vector<TreePatternNode*> CChildren;
1699 CChildren.reserve(Children.size());
1700 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1701 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001702 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001703 }
1704 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001705 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001706 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001707 New->setTransformFn(getTransformFn());
1708 return New;
1709}
1710
Chris Lattner53c39ba2010-02-14 22:22:58 +00001711/// RemoveAllTypes - Recursively strip all the types of this tree.
1712void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001713 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001714 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001715 if (isLeaf()) return;
1716 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1717 getChild(i)->RemoveAllTypes();
1718}
1719
1720
Chris Lattner8cab0212008-01-05 22:25:12 +00001721/// SubstituteFormalArguments - Replace the formal arguments in this tree
1722/// with actual values specified by ArgMap.
1723void TreePatternNode::
1724SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1725 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001726
Chris Lattner8cab0212008-01-05 22:25:12 +00001727 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1728 TreePatternNode *Child = getChild(i);
1729 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001730 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001731 // Note that, when substituting into an output pattern, Val might be an
1732 // UnsetInit.
1733 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1734 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001735 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001736 TreePatternNode *NewChild = ArgMap[Child->getName()];
1737 assert(NewChild && "Couldn't find formal argument!");
1738 assert((Child->getPredicateFns().empty() ||
1739 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1740 "Non-empty child predicate clobbered!");
1741 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001742 }
1743 } else {
1744 getChild(i)->SubstituteFormalArguments(ArgMap);
1745 }
1746 }
1747}
1748
1749
1750/// InlinePatternFragments - If this pattern refers to any pattern
1751/// fragments, inline them into place, giving us a pattern without any
1752/// PatFrag references.
1753TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001754 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001755 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001756
1757 if (isLeaf())
1758 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001759 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001760
Chris Lattner8cab0212008-01-05 22:25:12 +00001761 if (!Op->isSubClassOf("PatFrag")) {
1762 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001763 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1764 TreePatternNode *Child = getChild(i);
1765 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1766
1767 assert((Child->getPredicateFns().empty() ||
1768 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1769 "Non-empty child predicate clobbered!");
1770
1771 setChild(i, NewChild);
1772 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001773 return this;
1774 }
1775
1776 // Otherwise, we found a reference to a fragment. First, look up its
1777 // TreePattern record.
1778 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001779
Chris Lattner8cab0212008-01-05 22:25:12 +00001780 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001781 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001782 TP.error("'" + Op->getName() + "' fragment requires " +
1783 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001784 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001785 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001786
1787 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1788
Chris Lattner514e2922011-04-17 21:38:24 +00001789 TreePredicateFn PredFn(Frag);
1790 if (!PredFn.isAlwaysTrue())
1791 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001792
Chris Lattner8cab0212008-01-05 22:25:12 +00001793 // Resolve formal arguments to their actual value.
1794 if (Frag->getNumArgs()) {
1795 // Compute the map of formal to actual arguments.
1796 std::map<std::string, TreePatternNode*> ArgMap;
1797 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1798 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001799
Chris Lattner8cab0212008-01-05 22:25:12 +00001800 FragTree->SubstituteFormalArguments(ArgMap);
1801 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001802
Chris Lattner8cab0212008-01-05 22:25:12 +00001803 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001804 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1805 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001806
1807 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001808 for (const TreePredicateFn &Pred : getPredicateFns())
1809 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001810
Chris Lattner8cab0212008-01-05 22:25:12 +00001811 // Get a new copy of this fragment to stitch into here.
1812 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001813
Chris Lattner2e253b42008-06-30 03:02:03 +00001814 // The fragment we inlined could have recursive inlining that is needed. See
1815 // if there are any pattern fragments in it and inline them as needed.
1816 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001817}
1818
1819/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001820/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001821/// references from the register file information, for example.
1822///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001823/// When Unnamed is set, return the type of a DAG operand with no name, such as
1824/// the F8RC register class argument in:
1825///
1826/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1827///
1828/// When Unnamed is false, return the type of a named DAG operand such as the
1829/// GPR:$src operand above.
1830///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001831static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1832 bool NotRegisters,
1833 bool Unnamed,
1834 TreePattern &TP) {
1835 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1836
Owen Andersona84be6c2011-06-27 21:06:21 +00001837 // Check to see if this is a register operand.
1838 if (R->isSubClassOf("RegisterOperand")) {
1839 assert(ResNo == 0 && "Regoperand ref only has one result!");
1840 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001841 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00001842 Record *RegClass = R->getValueAsDef("RegClass");
1843 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001844 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00001845 }
1846
Chris Lattnercabe0372010-03-15 06:00:16 +00001847 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001848 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001849 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001850 // An unnamed register class represents itself as an i32 immediate, for
1851 // example on a COPY_TO_REGCLASS instruction.
1852 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001853 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001854
1855 // In a named operand, the register class provides the possible set of
1856 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001857 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001858 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00001859 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001860 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001861 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001862
Chris Lattner6070ee22010-03-23 23:50:31 +00001863 if (R->isSubClassOf("PatFrag")) {
1864 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001865 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001866 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001867 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001868
Chris Lattner6070ee22010-03-23 23:50:31 +00001869 if (R->isSubClassOf("Register")) {
1870 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001871 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001872 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001873 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001874 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001875 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001876
1877 if (R->isSubClassOf("SubRegIndex")) {
1878 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001879 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001880 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001881
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001882 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001883 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001884 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1885 //
1886 // (sext_inreg GPR:$src, i16)
1887 // ~~~
1888 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001889 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001890 // With a name, the ValueType simply provides the type of the named
1891 // variable.
1892 //
1893 // (sext_inreg i32:$src, i16)
1894 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001895 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001896 return TypeSetByHwMode(); // Unknown.
1897 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1898 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001899 }
1900
1901 if (R->isSubClassOf("CondCode")) {
1902 assert(ResNo == 0 && "This node only has one result!");
1903 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001904 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00001905 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001906
Chris Lattner6070ee22010-03-23 23:50:31 +00001907 if (R->isSubClassOf("ComplexPattern")) {
1908 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001909 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001910 return TypeSetByHwMode(); // Unknown.
1911 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00001912 }
1913 if (R->isSubClassOf("PointerLikeRegClass")) {
1914 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001915 TypeSetByHwMode VTS(MVT::iPTR);
1916 TP.getInfer().expandOverloads(VTS);
1917 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00001918 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001919
Chris Lattner6070ee22010-03-23 23:50:31 +00001920 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1921 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001922 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001923 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001924 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001925
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001926 if (R->isSubClassOf("Operand")) {
1927 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1928 Record *T = R->getValueAsDef("Type");
1929 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
1930 }
Tim Northoverc807a172014-05-20 11:52:46 +00001931
Chris Lattner8cab0212008-01-05 22:25:12 +00001932 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001933 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00001934}
1935
Chris Lattner89c65662008-01-06 05:36:50 +00001936
1937/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1938/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1939const CodeGenIntrinsic *TreePatternNode::
1940getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1941 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1942 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1943 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001944 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001945
Sean Silva88eb8dd2012-10-10 20:24:47 +00001946 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001947 return &CDP.getIntrinsicInfo(IID);
1948}
1949
Chris Lattner53c39ba2010-02-14 22:22:58 +00001950/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1951/// return the ComplexPattern information, otherwise return null.
1952const ComplexPattern *
1953TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001954 Record *Rec;
1955 if (isLeaf()) {
1956 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1957 if (!DI)
1958 return nullptr;
1959 Rec = DI->getDef();
1960 } else
1961 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001962
Tim Northoverc807a172014-05-20 11:52:46 +00001963 if (!Rec->isSubClassOf("ComplexPattern"))
1964 return nullptr;
1965 return &CGP.getComplexPattern(Rec);
1966}
1967
1968unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1969 // A ComplexPattern specifically declares how many results it fills in.
1970 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1971 return CP->getNumOperands();
1972
1973 // If MIOperandInfo is specified, that gives the count.
1974 if (isLeaf()) {
1975 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1976 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1977 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1978 if (MIOps->getNumArgs())
1979 return MIOps->getNumArgs();
1980 }
1981 }
1982
1983 // Otherwise there is just one result.
1984 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001985}
1986
1987/// NodeHasProperty - Return true if this node has the specified property.
1988bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001989 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001990 if (isLeaf()) {
1991 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1992 return CP->hasProperty(Property);
1993 return false;
1994 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001995
Chris Lattner53c39ba2010-02-14 22:22:58 +00001996 Record *Operator = getOperator();
1997 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001998
Chris Lattner53c39ba2010-02-14 22:22:58 +00001999 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2000}
2001
2002
2003
2004
2005/// TreeHasProperty - Return true if any node in this tree has the specified
2006/// property.
2007bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002008 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002009 if (NodeHasProperty(Property, CGP))
2010 return true;
2011 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2012 if (getChild(i)->TreeHasProperty(Property, CGP))
2013 return true;
2014 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002015}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002016
Evan Cheng49bad4c2008-06-16 20:29:38 +00002017/// isCommutativeIntrinsic - Return true if the node corresponds to a
2018/// commutative intrinsic.
2019bool
2020TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2021 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2022 return Int->isCommutative;
2023 return false;
2024}
2025
Matt Arsenaulteb492162014-11-02 23:46:51 +00002026static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2027 if (!N->isLeaf())
2028 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002029
Matt Arsenaulteb492162014-11-02 23:46:51 +00002030 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
2031 if (DI && DI->getDef()->isSubClassOf(Class))
2032 return true;
2033
2034 return false;
2035}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002036
2037static void emitTooManyOperandsError(TreePattern &TP,
2038 StringRef InstName,
2039 unsigned Expected,
2040 unsigned Actual) {
2041 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2042 " operands but expected only " + Twine(Expected) + "!");
2043}
2044
2045static void emitTooFewOperandsError(TreePattern &TP,
2046 StringRef InstName,
2047 unsigned Actual) {
2048 TP.error("Instruction '" + InstName +
2049 "' expects more than the provided " + Twine(Actual) + " operands!");
2050}
2051
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002052/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002053/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002054/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002055bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002056 if (TP.hasError())
2057 return false;
2058
Chris Lattnerab3242f2008-01-06 01:10:31 +00002059 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002060 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002061 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002062 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002063 bool MadeChange = false;
2064 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2065 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002066 NotRegisters,
2067 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002068 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002069 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002070
Sean Silvafb509ed2012-10-10 20:24:43 +00002071 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002072 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002073
Chris Lattnerf1447252010-03-19 21:37:09 +00002074 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002075 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002076
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002077 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002078 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002079
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002080 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2081 for (auto &P : VVT) {
2082 MVT::SimpleValueType VT = P.second.SimpleTy;
2083 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2084 continue;
2085 unsigned Size = MVT(VT).getSizeInBits();
2086 // Make sure that the value is representable for this type.
2087 if (Size >= 32)
2088 continue;
2089 // Check that the value doesn't use more bits than we have. It must
2090 // either be a sign- or zero-extended equivalent of the original.
2091 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2092 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2093 SignBitAndAbove == 1)
2094 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002095
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002096 TP.error("Integer value '" + itostr(II->getValue()) +
2097 "' is out of range for type '" + getEnumName(VT) + "'!");
2098 break;
2099 }
2100 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002101 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002102
Chris Lattner8cab0212008-01-05 22:25:12 +00002103 return false;
2104 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002105
Chris Lattner8cab0212008-01-05 22:25:12 +00002106 // special handling for set, which isn't really an SDNode.
2107 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002108 assert(getNumTypes() == 0 && "Set doesn't produce a value");
2109 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002110 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002111
Chris Lattnerf1447252010-03-19 21:37:09 +00002112 TreePatternNode *SetVal = getChild(NC-1);
2113 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
2114
Elena Demikhovsky09954792015-03-01 08:23:41 +00002115 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002116 TreePatternNode *Child = getChild(i);
2117 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002118
Chris Lattner8cab0212008-01-05 22:25:12 +00002119 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00002120 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
2121 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002122 }
2123 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002124 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002125
Chris Lattner5c2182e2010-03-27 02:53:27 +00002126 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002127 assert(getNumTypes() == 0 && "Node doesn't produce a value");
2128
Chris Lattner8cab0212008-01-05 22:25:12 +00002129 bool MadeChange = false;
2130 for (unsigned i = 0; i < getNumChildren(); ++i)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002131 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002132 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002133 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002134
Chris Lattneree820ac2010-02-23 05:51:07 +00002135 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002136 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002137
Chris Lattner8cab0212008-01-05 22:25:12 +00002138 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002139 unsigned NumRetVTs = Int->IS.RetVTs.size();
2140 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002141
Bill Wendling91821472008-11-13 09:08:33 +00002142 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002143 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002144
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002145 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00002146 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00002147 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00002148 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002149 return false;
2150 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002151
2152 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00002153 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002154
Chris Lattnerf1447252010-03-19 21:37:09 +00002155 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
2156 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002157
Chris Lattnerf1447252010-03-19 21:37:09 +00002158 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
2159 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2160 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002161 }
2162 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002163 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002164
Chris Lattneree820ac2010-02-23 05:51:07 +00002165 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002166 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002167
Chris Lattner135091b2010-03-28 08:48:47 +00002168 // Check that the number of operands is sane. Negative operands -> varargs.
2169 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002170 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002171 TP.error(getOperator()->getName() + " node requires exactly " +
2172 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002173 return false;
2174 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002175
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002176 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002177 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2178 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002179 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002180 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002181 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002182
Chris Lattneree820ac2010-02-23 05:51:07 +00002183 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002184 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002185 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002186 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002187
Chris Lattnerd44966f2010-03-27 19:15:02 +00002188 bool MadeChange = false;
2189
2190 // Apply the result types to the node, these come from the things in the
2191 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002192 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2193 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002194 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2195 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002196
Chris Lattnerd44966f2010-03-27 19:15:02 +00002197 // If the instruction has implicit defs, we apply the first one as a result.
2198 // FIXME: This sucks, it should apply all implicit defs.
2199 if (!InstInfo.ImplicitDefs.empty()) {
2200 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002201
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002202 // FIXME: Generalize to multiple possible types and multiple possible
2203 // ImplicitDefs.
2204 MVT::SimpleValueType VT =
2205 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002206
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002207 if (VT != MVT::Other)
2208 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002209 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002210
Chris Lattnercabe0372010-03-15 06:00:16 +00002211 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2212 // be the same.
2213 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002214 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2215 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2216 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002217 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2218 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2219 // variadic.
2220
2221 unsigned NChild = getNumChildren();
2222 if (NChild < 3) {
2223 TP.error("REG_SEQUENCE requires at least 3 operands!");
2224 return false;
2225 }
2226
2227 if (NChild % 2 == 0) {
2228 TP.error("REG_SEQUENCE requires an odd number of operands!");
2229 return false;
2230 }
2231
2232 if (!isOperandClass(getChild(0), "RegisterClass")) {
2233 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2234 return false;
2235 }
2236
2237 for (unsigned I = 1; I < NChild; I += 2) {
2238 TreePatternNode *SubIdxChild = getChild(I + 1);
2239 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2240 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2241 itostr(I + 1) + "!");
2242 return false;
2243 }
2244 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002245 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002246
2247 unsigned ChildNo = 0;
2248 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2249 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002250
Chris Lattner8cab0212008-01-05 22:25:12 +00002251 // If the instruction expects a predicate or optional def operand, we
2252 // codegen this by setting the operand to it's default value if it has a
2253 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002254 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002255 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2256 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002257
Chris Lattner8cab0212008-01-05 22:25:12 +00002258 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002259 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002260 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002261 return false;
2262 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002263
Chris Lattner8cab0212008-01-05 22:25:12 +00002264 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002265 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002266
2267 // If the operand has sub-operands, they may be provided by distinct
2268 // child patterns, so attempt to match each sub-operand separately.
2269 if (OperandNode->isSubClassOf("Operand")) {
2270 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2271 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2272 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002273 // a single ComplexPattern-related Operand.
2274
2275 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002276 // Match first sub-operand against the child we already have.
2277 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2278 MadeChange |=
2279 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2280
2281 // And the remaining sub-operands against subsequent children.
2282 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2283 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002284 emitTooFewOperandsError(TP, getOperator()->getName(),
2285 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002286 return false;
2287 }
2288 Child = getChild(ChildNo++);
2289
2290 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2291 MadeChange |=
2292 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2293 }
2294 continue;
2295 }
2296 }
2297 }
2298
2299 // If we didn't match by pieces above, attempt to match the whole
2300 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002301 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002302 }
Christopher Lamba7312392008-03-11 09:33:47 +00002303
Matt Arsenaulteb492162014-11-02 23:46:51 +00002304 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002305 emitTooManyOperandsError(TP, getOperator()->getName(),
2306 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002307 return false;
2308 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002309
Ulrich Weigande618abd2013-03-19 19:51:09 +00002310 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2311 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002312 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002313 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002314
Tim Northoverc807a172014-05-20 11:52:46 +00002315 if (getOperator()->isSubClassOf("ComplexPattern")) {
2316 bool MadeChange = false;
2317
2318 for (unsigned i = 0; i < getNumChildren(); ++i)
2319 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2320
2321 return MadeChange;
2322 }
2323
Chris Lattneree820ac2010-02-23 05:51:07 +00002324 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002325
Chris Lattneree820ac2010-02-23 05:51:07 +00002326 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002327 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002328 TP.error("Node transform '" + getOperator()->getName() +
2329 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002330 return false;
2331 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002332
Chris Lattnercabe0372010-03-15 06:00:16 +00002333 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002334 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002335}
2336
2337/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2338/// RHS of a commutative operation, not the on LHS.
2339static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2340 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2341 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002342 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002343 return true;
2344 return false;
2345}
2346
2347
2348/// canPatternMatch - If it is impossible for this pattern to match on this
2349/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002350/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002351/// that can never possibly work), and to prevent the pattern permuter from
2352/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002353bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002354 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002355 if (isLeaf()) return true;
2356
2357 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2358 if (!getChild(i)->canPatternMatch(Reason, CDP))
2359 return false;
2360
2361 // If this is an intrinsic, handle cases that would make it not match. For
2362 // example, if an operand is required to be an immediate.
2363 if (getOperator()->isSubClassOf("Intrinsic")) {
2364 // TODO:
2365 return true;
2366 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002367
Tim Northoverc807a172014-05-20 11:52:46 +00002368 if (getOperator()->isSubClassOf("ComplexPattern"))
2369 return true;
2370
Chris Lattner8cab0212008-01-05 22:25:12 +00002371 // If this node is a commutative operator, check that the LHS isn't an
2372 // immediate.
2373 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002374 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2375 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002376 // Scan all of the operands of the node and make sure that only the last one
2377 // is a constant node, unless the RHS also is.
2378 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002379 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002380 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002381 if (OnlyOnRHSOfCommutative(getChild(i))) {
2382 Reason="Immediate value must be on the RHS of commutative operators!";
2383 return false;
2384 }
2385 }
2386 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002387
Chris Lattner8cab0212008-01-05 22:25:12 +00002388 return true;
2389}
2390
2391//===----------------------------------------------------------------------===//
2392// TreePattern implementation
2393//
2394
David Greeneaf8ee2c2011-07-29 22:43:06 +00002395TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002396 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002397 isInputPattern(isInput), HasError(false),
2398 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002399 for (Init *I : RawPat->getValues())
2400 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002401}
2402
David Greeneaf8ee2c2011-07-29 22:43:06 +00002403TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002404 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002405 isInputPattern(isInput), HasError(false),
2406 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002407 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002408}
2409
David Blaikiecf195302014-11-17 22:55:41 +00002410TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002411 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002412 isInputPattern(isInput), HasError(false),
2413 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002414 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002415}
2416
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002417void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002418 if (HasError)
2419 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002420 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002421 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2422 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002423}
2424
Chris Lattnercabe0372010-03-15 06:00:16 +00002425void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002426 for (TreePatternNode *Tree : Trees)
2427 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002428}
2429
2430void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2431 if (!N->getName().empty())
2432 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002433
Chris Lattnercabe0372010-03-15 06:00:16 +00002434 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2435 ComputeNamedNodes(N->getChild(i));
2436}
2437
David Blaikiecf195302014-11-17 22:55:41 +00002438
2439TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002440 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002441 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002442
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002443 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002444 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002445 /// (foo GPR, imm) -> (foo GPR, (imm))
2446 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002447 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002448 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002449 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002450 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002451
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002452 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002453 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002454 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002455 if (OpName.empty())
2456 error("'node' argument requires a name to match with operand list");
2457 Args.push_back(OpName);
2458 }
2459
2460 Res->setName(OpName);
2461 return Res;
2462 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002463
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002464 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002465 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002466 if (OpName.empty())
2467 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002468 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002469 Args.push_back(OpName);
2470 Res->setName(OpName);
2471 return Res;
2472 }
2473
Sean Silvafb509ed2012-10-10 20:24:43 +00002474 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002475 if (!OpName.empty())
2476 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002477 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002478 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002479
Sean Silvafb509ed2012-10-10 20:24:43 +00002480 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002481 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002482 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002483 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002484 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002485 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002486 }
2487
Sean Silvafb509ed2012-10-10 20:24:43 +00002488 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002489 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002490 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002491 error("Pattern has unexpected init kind!");
2492 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002493 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002494 if (!OpDef) error("Pattern has unexpected operator type!");
2495 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002496
Chris Lattner8cab0212008-01-05 22:25:12 +00002497 if (Operator->isSubClassOf("ValueType")) {
2498 // If the operator is a ValueType, then this must be "type cast" of a leaf
2499 // node.
2500 if (Dag->getNumArgs() != 1)
2501 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002502
Matthias Braunbb053162016-12-05 06:00:46 +00002503 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2504 Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002505
Chris Lattner8cab0212008-01-05 22:25:12 +00002506 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002507 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002508 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2509 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002510
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002511 if (!OpName.empty())
2512 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002513 return New;
2514 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002515
Chris Lattner8cab0212008-01-05 22:25:12 +00002516 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002517 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002518 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002519 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002520 !Operator->isSubClassOf("SDNodeXForm") &&
2521 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002522 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002523 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002524 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002525 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002526
Chris Lattner8cab0212008-01-05 22:25:12 +00002527 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002528 if (isInputPattern) {
2529 if (Operator->isSubClassOf("Instruction") ||
2530 Operator->isSubClassOf("SDNodeXForm"))
2531 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2532 } else {
2533 if (Operator->isSubClassOf("Intrinsic"))
2534 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002535
Chris Lattner2e9eae12010-03-28 06:57:56 +00002536 if (Operator->isSubClassOf("SDNode") &&
2537 Operator->getName() != "imm" &&
2538 Operator->getName() != "fpimm" &&
2539 Operator->getName() != "tglobaltlsaddr" &&
2540 Operator->getName() != "tconstpool" &&
2541 Operator->getName() != "tjumptable" &&
2542 Operator->getName() != "tframeindex" &&
2543 Operator->getName() != "texternalsym" &&
2544 Operator->getName() != "tblockaddress" &&
2545 Operator->getName() != "tglobaladdr" &&
2546 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002547 Operator->getName() != "vt" &&
2548 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002549 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2550 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002551
Chris Lattner8cab0212008-01-05 22:25:12 +00002552 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002553
2554 // Parse all the operands.
2555 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002556 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002557
Chris Lattner8cab0212008-01-05 22:25:12 +00002558 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002559 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002560 // convert the intrinsic name to a number.
2561 if (Operator->isSubClassOf("Intrinsic")) {
2562 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2563 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2564
2565 // If this intrinsic returns void, it must have side-effects and thus a
2566 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002567 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002568 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002569 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002570 // Has side-effects, requires chain.
2571 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002572 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002573 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002574
David Greenee32ebf22011-07-29 19:07:07 +00002575 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002576 Children.insert(Children.begin(), IIDNode);
2577 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002578
Tim Northoverc807a172014-05-20 11:52:46 +00002579 if (Operator->isSubClassOf("ComplexPattern")) {
2580 for (unsigned i = 0; i < Children.size(); ++i) {
2581 TreePatternNode *Child = Children[i];
2582
2583 if (Child->getName().empty())
2584 error("All arguments to a ComplexPattern must be named");
2585
2586 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2587 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2588 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2589 auto OperandId = std::make_pair(Operator, i);
2590 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2591 if (PrevOp != ComplexPatternOperands.end()) {
2592 if (PrevOp->getValue() != OperandId)
2593 error("All ComplexPattern operands must appear consistently: "
2594 "in the same order in just one ComplexPattern instance.");
2595 } else
2596 ComplexPatternOperands[Child->getName()] = OperandId;
2597 }
2598 }
2599
Chris Lattnerf1447252010-03-19 21:37:09 +00002600 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002601 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002602 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002603
Matthias Braun7cf3b112016-12-05 06:00:41 +00002604 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002605 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002606 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002607 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002608 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002609}
2610
Chris Lattnera787c9e2010-03-28 08:38:32 +00002611/// SimplifyTree - See if we can simplify this tree to eliminate something that
2612/// will never match in favor of something obvious that will. This is here
2613/// strictly as a convenience to target authors because it allows them to write
2614/// more type generic things and have useless type casts fold away.
2615///
2616/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002617static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002618 if (N->isLeaf())
2619 return false;
2620
2621 // If we have a bitconvert with a resolved type and if the source and
2622 // destination types are the same, then the bitconvert is useless, remove it.
2623 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002624 N->getExtType(0).isValueTypeByHwMode(false) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002625 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2626 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002627 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002628 SimplifyTree(N);
2629 return true;
2630 }
2631
2632 // Walk all children.
2633 bool MadeChange = false;
2634 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002635 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002636 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002637 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002638 }
2639 return MadeChange;
2640}
2641
2642
2643
Chris Lattner8cab0212008-01-05 22:25:12 +00002644/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002645/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002646/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002647bool TreePattern::
2648InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2649 if (NamedNodes.empty())
2650 ComputeNamedNodes();
2651
Chris Lattner8cab0212008-01-05 22:25:12 +00002652 bool MadeChange = true;
2653 while (MadeChange) {
2654 MadeChange = false;
Craig Topper3f7864e2017-08-30 02:05:03 +00002655 for (TreePatternNode *&Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002656 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2657 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002658 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002659
2660 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002661 for (auto &Entry : NamedNodes) {
2662 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002663
Chris Lattnercabe0372010-03-15 06:00:16 +00002664 // If we have input named node types, propagate their types to the named
2665 // values here.
2666 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002667 if (!InNamedTypes->count(Entry.getKey())) {
2668 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002669 "' in output pattern but not input pattern");
2670 return true;
2671 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002672
2673 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002674 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002675
2676 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002677 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002678 // If this node is a register class, and it is the root of the pattern
2679 // then we're mapping something onto an input register. We allow
2680 // changing the type of the input register in this case. This allows
2681 // us to match things like:
2682 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002683 if (Node == Trees[0] && Node->isLeaf()) {
2684 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002685 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2686 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002687 continue;
2688 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002689
Craig Topper306cb122015-11-22 20:46:24 +00002690 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002691 InNodes[0]->getNumTypes() == 1 &&
2692 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002693 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2694 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002695 }
2696 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002697
Chris Lattnercabe0372010-03-15 06:00:16 +00002698 // If there are multiple nodes with the same name, they must all have the
2699 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002700 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002701 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002702 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002703 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002704 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002705
Chris Lattnerf1447252010-03-19 21:37:09 +00002706 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2707 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002708 }
2709 }
2710 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002711 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002712
Chris Lattner8cab0212008-01-05 22:25:12 +00002713 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002714 for (const TreePatternNode *Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002715 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002716 return !HasUnresolvedTypes;
2717}
2718
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002719void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002720 OS << getRecord()->getName();
2721 if (!Args.empty()) {
2722 OS << "(" << Args[0];
2723 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2724 OS << ", " << Args[i];
2725 OS << ")";
2726 }
2727 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002728
Chris Lattner8cab0212008-01-05 22:25:12 +00002729 if (Trees.size() > 1)
2730 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002731 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002732 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002733 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002734 OS << "\n";
2735 }
2736
2737 if (Trees.size() > 1)
2738 OS << "]\n";
2739}
2740
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002741void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002742
2743//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002744// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002745//
2746
Jim Grosbach65586fe2010-12-21 16:16:00 +00002747CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002748 Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002749
Justin Bogner92a8c612016-07-15 16:31:37 +00002750 Intrinsics = CodeGenIntrinsicTable(Records, false);
2751 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002752 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002753 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002754 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002755 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002756 ParseDefaultOperands();
2757 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002758 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002759 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002760
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002761 // Break patterns with parameterized types into a series of patterns,
2762 // where each one has a fixed type and is predicated on the conditions
2763 // of the associated HW mode.
2764 ExpandHwModeBasedTypes();
2765
Chris Lattner8cab0212008-01-05 22:25:12 +00002766 // Generate variants. For example, commutative patterns can match
2767 // multiple ways. Add them to PatternsToMatch as well.
2768 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002769
2770 // Infer instruction flags. For example, we can detect loads,
2771 // stores, and side effects in many cases by examining an
2772 // instruction's pattern.
2773 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002774
2775 // Verify that instruction flags match the patterns.
2776 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002777}
2778
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00002779Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002780 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002781 if (!N || !N->isSubClassOf("SDNode"))
2782 PrintFatalError("Error getting SDNode '" + Name + "'!");
2783
Chris Lattner8cab0212008-01-05 22:25:12 +00002784 return N;
2785}
2786
2787// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002788void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002789 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002790 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2791
Chris Lattner8cab0212008-01-05 22:25:12 +00002792 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002793 Record *R = Nodes.back();
2794 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002795 Nodes.pop_back();
2796 }
2797
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002798 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002799 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2800 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2801 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2802}
2803
2804/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2805/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002806void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002807 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2808 while (!Xforms.empty()) {
2809 Record *XFormNode = Xforms.back();
2810 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002811 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002812 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002813
2814 Xforms.pop_back();
2815 }
2816}
2817
Chris Lattnerab3242f2008-01-06 01:10:31 +00002818void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002819 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2820 while (!AMs.empty()) {
2821 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2822 AMs.pop_back();
2823 }
2824}
2825
2826
2827/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2828/// file, building up the PatternFragments map. After we've collected them all,
2829/// inline fragments together as necessary, so that there are no references left
2830/// inside a pattern fragment to a pattern fragment.
2831///
Hal Finkel2756dc12014-02-28 00:26:56 +00002832void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002833 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002834
Chris Lattnere7170df2008-01-05 22:43:57 +00002835 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002836 for (Record *Frag : Fragments) {
2837 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002838 continue;
2839
Craig Topper306cb122015-11-22 20:46:24 +00002840 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002841 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002842 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2843 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002844 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002845
Chris Lattnere7170df2008-01-05 22:43:57 +00002846 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002847 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00002848 // Copy the args so we can take StringRefs to them.
2849 auto ArgsCopy = Args;
2850 SmallDenseSet<StringRef, 4> OperandsSet;
2851 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002852
Chris Lattnere7170df2008-01-05 22:43:57 +00002853 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002854 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002855
Chris Lattner8cab0212008-01-05 22:25:12 +00002856 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002857 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002858 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002859 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002860 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002861 if (!OpsOp ||
2862 (OpsOp->getDef()->getName() != "ops" &&
2863 OpsOp->getDef()->getName() != "outs" &&
2864 OpsOp->getDef()->getName() != "ins"))
2865 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002866
2867 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002868 Args.clear();
2869 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002870 if (!isa<DefInit>(OpsList->getArg(j)) ||
2871 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002872 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00002873 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00002874 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00002875 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2876 if (!OperandsSet.count(ArgNameStr))
2877 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00002878 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00002879 OperandsSet.erase(ArgNameStr);
2880 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00002881 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002882
Chris Lattnere7170df2008-01-05 22:43:57 +00002883 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002884 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002885 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002886
Chris Lattnere7170df2008-01-05 22:43:57 +00002887 // If there is a code init for this fragment, keep track of the fact that
2888 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002889 TreePredicateFn PredFn(P);
2890 if (!PredFn.isAlwaysTrue())
2891 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002892
Chris Lattner8cab0212008-01-05 22:25:12 +00002893 // If there is a node transformation corresponding to this, keep track of
2894 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002895 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002896 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2897 P->getOnlyTree()->setTransformFn(Transform);
2898 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002899
Chris Lattner8cab0212008-01-05 22:25:12 +00002900 // Now that we've parsed all of the tree fragments, do a closure on them so
2901 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002902 for (Record *Frag : Fragments) {
2903 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002904 continue;
2905
Craig Topper306cb122015-11-22 20:46:24 +00002906 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002907 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002908
Chris Lattner8cab0212008-01-05 22:25:12 +00002909 // Infer as many types as possible. Don't worry about it if we don't infer
2910 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002911 ThePat.InferAllTypes();
2912 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002913
Chris Lattner8cab0212008-01-05 22:25:12 +00002914 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002915 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002916 }
2917}
2918
Chris Lattnerab3242f2008-01-06 01:10:31 +00002919void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002920 std::vector<Record*> DefaultOps;
2921 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002922
2923 // Find some SDNode.
2924 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002925 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002926
Tom Stellardb7246a72012-09-06 14:15:52 +00002927 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2928 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002929
Tom Stellardb7246a72012-09-06 14:15:52 +00002930 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2931 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00002932 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00002933 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2934 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2935 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00002936 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002937
Tom Stellardb7246a72012-09-06 14:15:52 +00002938 // Create a TreePattern to parse this.
2939 TreePattern P(DefaultOps[i], DI, false, *this);
2940 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002941
Tom Stellardb7246a72012-09-06 14:15:52 +00002942 // Copy the operands over into a DAGDefaultOperand.
2943 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002944
Tom Stellardb7246a72012-09-06 14:15:52 +00002945 TreePatternNode *T = P.getTree(0);
2946 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2947 TreePatternNode *TPN = T->getChild(op);
2948 while (TPN->ApplyTypeConstraints(P, false))
2949 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002950
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002951 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002952 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2953 DefaultOps[i]->getName() +
2954 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002955 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002956 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002957 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002958
2959 // Insert it into the DefaultOperands map so we can find it later.
2960 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002961 }
2962}
2963
2964/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2965/// instruction input. Return true if this is a real use.
2966static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002967 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002968 // No name -> not interesting.
2969 if (Pat->getName().empty()) {
2970 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002971 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002972 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2973 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002974 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002975 }
2976 return false;
2977 }
2978
2979 Record *Rec;
2980 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002981 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002982 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2983 Rec = DI->getDef();
2984 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002985 Rec = Pat->getOperator();
2986 }
2987
2988 // SRCVALUE nodes are ignored.
2989 if (Rec->getName() == "srcvalue")
2990 return false;
2991
2992 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2993 if (!Slot) {
2994 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002995 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002996 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002997 Record *SlotRec;
2998 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002999 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003000 } else {
3001 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3002 SlotRec = Slot->getOperator();
3003 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003004
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003005 // Ensure that the inputs agree if we've already seen this input.
3006 if (Rec != SlotRec)
3007 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00003008 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003009 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003010 return true;
3011}
3012
3013/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3014/// part of "I", the instruction), computing the set of inputs and outputs of
3015/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003016void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00003017FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
3018 std::map<std::string, TreePatternNode*> &InstInputs,
3019 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00003020 std::vector<Record*> &InstImpResults) {
3021 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003022 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00003023 if (!isUse && Pat->getTransformFn())
3024 I->error("Cannot specify a transform function for a non-input value!");
3025 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003026 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003027
Chris Lattnerf2d70992010-02-17 06:53:36 +00003028 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003029 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3030 TreePatternNode *Dest = Pat->getChild(i);
3031 if (!Dest->isLeaf())
3032 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003033
Sean Silvafb509ed2012-10-10 20:24:43 +00003034 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003035 if (!Val || !Val->getDef()->isSubClassOf("Register"))
3036 I->error("implicitly defined value should be a register!");
3037 InstImpResults.push_back(Val->getDef());
3038 }
3039 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003040 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003041
Chris Lattnerf2d70992010-02-17 06:53:36 +00003042 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003043 // If this is not a set, verify that the children nodes are not void typed,
3044 // and recurse.
3045 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003046 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00003047 I->error("Cannot have void nodes inside of patterns!");
3048 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003049 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003050 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003051
Chris Lattner8cab0212008-01-05 22:25:12 +00003052 // If this is a non-leaf node with no children, treat it basically as if
3053 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003054 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003055
Chris Lattner8cab0212008-01-05 22:25:12 +00003056 if (!isUse && Pat->getTransformFn())
3057 I->error("Cannot specify a transform function for a non-input value!");
3058 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003059 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003060
Chris Lattner8cab0212008-01-05 22:25:12 +00003061 // Otherwise, this is a set, validate and collect instruction results.
3062 if (Pat->getNumChildren() == 0)
3063 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003064
Chris Lattner8cab0212008-01-05 22:25:12 +00003065 if (Pat->getTransformFn())
3066 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003067
Chris Lattner8cab0212008-01-05 22:25:12 +00003068 // Check the set destinations.
3069 unsigned NumDests = Pat->getNumChildren()-1;
3070 for (unsigned i = 0; i != NumDests; ++i) {
3071 TreePatternNode *Dest = Pat->getChild(i);
3072 if (!Dest->isLeaf())
3073 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003074
Sean Silvafb509ed2012-10-10 20:24:43 +00003075 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003076 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003077 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003078 continue;
3079 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003080
3081 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003082 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003083 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003084 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003085 if (Dest->getName().empty())
3086 I->error("set destination must have a name!");
3087 if (InstResults.count(Dest->getName()))
3088 I->error("cannot set '" + Dest->getName() +"' multiple times");
3089 InstResults[Dest->getName()] = Dest;
3090 } else if (Val->getDef()->isSubClassOf("Register")) {
3091 InstImpResults.push_back(Val->getDef());
3092 } else {
3093 I->error("set destination should be a register!");
3094 }
3095 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003096
Chris Lattner8cab0212008-01-05 22:25:12 +00003097 // Verify and collect info from the computation.
3098 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00003099 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003100}
3101
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003102//===----------------------------------------------------------------------===//
3103// Instruction Analysis
3104//===----------------------------------------------------------------------===//
3105
3106class InstAnalyzer {
3107 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003108public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003109 bool hasSideEffects;
3110 bool mayStore;
3111 bool mayLoad;
3112 bool isBitcast;
3113 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003114
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003115 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3116 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3117 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003118
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003119 void Analyze(const TreePattern *Pat) {
3120 // Assume only the first tree is the pattern. The others are clobber nodes.
3121 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003122 }
3123
Craig Topper2a053a92017-06-20 16:34:37 +00003124 void Analyze(const PatternToMatch &Pat) {
3125 AnalyzeNode(Pat.getSrcPattern());
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003126 }
3127
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003128private:
Evan Cheng880e299d2011-03-15 05:09:26 +00003129 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003130 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003131 return false;
3132
3133 if (N->getNumChildren() != 2)
3134 return false;
3135
3136 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00003137 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00003138 return false;
3139
3140 const TreePatternNode *N1 = N->getChild(1);
3141 if (N1->isLeaf())
3142 return false;
3143 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
3144 return false;
3145
3146 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
3147 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3148 return false;
3149 return OpInfo.getEnumName() == "ISD::BITCAST";
3150 }
3151
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003152public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003153 void AnalyzeNode(const TreePatternNode *N) {
3154 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003155 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003156 Record *LeafRec = DI->getDef();
3157 // Handle ComplexPattern leaves.
3158 if (LeafRec->isSubClassOf("ComplexPattern")) {
3159 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3160 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3161 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003162 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003163 }
3164 }
3165 return;
3166 }
3167
3168 // Analyze children.
3169 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3170 AnalyzeNode(N->getChild(i));
3171
3172 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00003173 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003174 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003175 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00003176 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003177
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003178 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00003179 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3180 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3181 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3182 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003183
3184 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3185 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003186 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003187 mayLoad = true;// These may load memory.
3188
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003189 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003190 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3191
Matt Arsenault868af922017-04-28 21:01:46 +00003192 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3193 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003194 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003195 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003196 }
3197 }
3198
3199};
3200
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003201static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003202 const InstAnalyzer &PatInfo,
3203 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003204 bool Error = false;
3205
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003206 // Remember where InstInfo got its flags.
3207 if (InstInfo.hasUndefFlags())
3208 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003209
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003210 // Check explicitly set flags for consistency.
3211 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3212 !InstInfo.hasSideEffects_Unset) {
3213 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3214 // the pattern has no side effects. That could be useful for div/rem
3215 // instructions that may trap.
3216 if (!InstInfo.hasSideEffects) {
3217 Error = true;
3218 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3219 Twine(InstInfo.hasSideEffects));
3220 }
3221 }
3222
3223 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3224 Error = true;
3225 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3226 Twine(InstInfo.mayStore));
3227 }
3228
3229 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3230 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003231 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003232 if (!InstInfo.mayLoad) {
3233 Error = true;
3234 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3235 Twine(InstInfo.mayLoad));
3236 }
3237 }
3238
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003239 // Transfer inferred flags.
3240 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3241 InstInfo.mayStore |= PatInfo.mayStore;
3242 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003243
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003244 // These flags are silently added without any verification.
3245 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003246
3247 // Don't infer isVariadic. This flag means something different on SDNodes and
3248 // instructions. For example, a CALL SDNode is variadic because it has the
3249 // call arguments as operands, but a CALL instruction is not variadic - it
3250 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003251
3252 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003253}
3254
Jim Grosbach514410b2012-07-17 00:47:06 +00003255/// hasNullFragReference - Return true if the DAG has any reference to the
3256/// null_frag operator.
3257static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003258 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003259 if (!OpDef) return false;
3260 Record *Operator = OpDef->getDef();
3261
3262 // If this is the null fragment, return true.
3263 if (Operator->getName() == "null_frag") return true;
3264 // If any of the arguments reference the null fragment, return true.
3265 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003266 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003267 if (Arg && hasNullFragReference(Arg))
3268 return true;
3269 }
3270
3271 return false;
3272}
3273
3274/// hasNullFragReference - Return true if any DAG in the list references
3275/// the null_frag operator.
3276static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003277 for (Init *I : LI->getValues()) {
3278 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003279 assert(DI && "non-dag in an instruction Pattern list?!");
3280 if (hasNullFragReference(DI))
3281 return true;
3282 }
3283 return false;
3284}
3285
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003286/// Get all the instructions in a tree.
3287static void
3288getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3289 if (Tree->isLeaf())
3290 return;
3291 if (Tree->getOperator()->isSubClassOf("Instruction"))
3292 Instrs.push_back(Tree->getOperator());
3293 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3294 getInstructionsInTree(Tree->getChild(i), Instrs);
3295}
3296
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003297/// Check the class of a pattern leaf node against the instruction operand it
3298/// represents.
3299static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3300 Record *Leaf) {
3301 if (OI.Rec == Leaf)
3302 return true;
3303
3304 // Allow direct value types to be used in instruction set patterns.
3305 // The type will be checked later.
3306 if (Leaf->isSubClassOf("ValueType"))
3307 return true;
3308
3309 // Patterns can also be ComplexPattern instances.
3310 if (Leaf->isSubClassOf("ComplexPattern"))
3311 return true;
3312
3313 return false;
3314}
3315
Ahmed Bougacha14107512013-10-28 18:07:21 +00003316const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
3317 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003318
Craig Topper0d1fb902015-03-10 03:25:04 +00003319 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003320
Craig Topper0d1fb902015-03-10 03:25:04 +00003321 // Parse the instruction.
3322 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
3323 // Inline pattern fragments into it.
3324 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003325
Craig Topper0d1fb902015-03-10 03:25:04 +00003326 // Infer as many types as possible. If we cannot infer all of them, we can
3327 // never do anything with this instruction pattern: report it to the user.
3328 if (!I->InferAllTypes())
3329 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003330
Craig Topper0d1fb902015-03-10 03:25:04 +00003331 // InstInputs - Keep track of all of the inputs of the instruction, along
3332 // with the record they are declared as.
3333 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003334
Craig Topper0d1fb902015-03-10 03:25:04 +00003335 // InstResults - Keep track of all the virtual registers that are 'set'
3336 // in the instruction, including what reg class they are.
3337 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003338
Craig Topper0d1fb902015-03-10 03:25:04 +00003339 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003340
Craig Topper0d1fb902015-03-10 03:25:04 +00003341 // Verify that the top-level forms in the instruction are of void type, and
3342 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003343 SmallString<32> TypesString;
Craig Topper0d1fb902015-03-10 03:25:04 +00003344 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003345 TypesString.clear();
Craig Topper0d1fb902015-03-10 03:25:04 +00003346 TreePatternNode *Pat = I->getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003347 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003348 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003349 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3350 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003351 OS << ", ";
3352 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003353 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003354 I->error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003355 " void types, has types " +
3356 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003357 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003358
Craig Topper0d1fb902015-03-10 03:25:04 +00003359 // Find inputs and outputs, and verify the structure of the uses/defs.
3360 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3361 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003362 }
3363
Craig Topper0d1fb902015-03-10 03:25:04 +00003364 // Now that we have inputs and outputs of the pattern, inspect the operands
3365 // list for the instruction. This determines the order that operands are
3366 // added to the machine instruction the node corresponds to.
3367 unsigned NumResults = InstResults.size();
3368
3369 // Parse the operands list from the (ops) list, validating it.
3370 assert(I->getArgList().empty() && "Args list should still be empty here!");
3371
3372 // Check that all of the results occur first in the list.
3373 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00003374 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003375 for (unsigned i = 0; i != NumResults; ++i) {
3376 if (i == CGI.Operands.size())
3377 I->error("'" + InstResults.begin()->first +
3378 "' set but does not appear in operand list!");
3379 const std::string &OpName = CGI.Operands[i].Name;
3380
3381 // Check that it exists in InstResults.
3382 TreePatternNode *RNode = InstResults[OpName];
3383 if (!RNode)
3384 I->error("Operand $" + OpName + " does not exist in operand list!");
3385
Craig Topper3a8eb892015-03-20 05:09:06 +00003386 ResNodes.push_back(RNode);
3387
Craig Topper0d1fb902015-03-10 03:25:04 +00003388 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3389 if (!R)
3390 I->error("Operand $" + OpName + " should be a set destination: all "
3391 "outputs must occur before inputs in operand list!");
3392
3393 if (!checkOperandClass(CGI.Operands[i], R))
3394 I->error("Operand $" + OpName + " class mismatch!");
3395
3396 // Remember the return type.
3397 Results.push_back(CGI.Operands[i].Rec);
3398
3399 // Okay, this one checks out.
3400 InstResults.erase(OpName);
3401 }
3402
3403 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3404 // the copy while we're checking the inputs.
3405 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3406
3407 std::vector<TreePatternNode*> ResultNodeOperands;
3408 std::vector<Record*> Operands;
3409 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3410 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3411 const std::string &OpName = Op.Name;
3412 if (OpName.empty())
3413 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3414
3415 if (!InstInputsCheck.count(OpName)) {
3416 // If this is an operand with a DefaultOps set filled in, we can ignore
3417 // this. When we codegen it, we will do so as always executed.
3418 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3419 // Does it have a non-empty DefaultOps field? If so, ignore this
3420 // operand.
3421 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3422 continue;
3423 }
3424 I->error("Operand $" + OpName +
3425 " does not appear in the instruction pattern");
3426 }
3427 TreePatternNode *InVal = InstInputsCheck[OpName];
3428 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3429
3430 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3431 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3432 if (!checkOperandClass(Op, InRec))
3433 I->error("Operand $" + OpName + "'s register class disagrees"
3434 " between the operand and pattern");
3435 }
3436 Operands.push_back(Op.Rec);
3437
3438 // Construct the result for the dest-pattern operand list.
3439 TreePatternNode *OpNode = InVal->clone();
3440
3441 // No predicate is useful on the result.
3442 OpNode->clearPredicateFns();
3443
3444 // Promote the xform function to be an explicit node if set.
3445 if (Record *Xform = OpNode->getTransformFn()) {
3446 OpNode->setTransformFn(nullptr);
3447 std::vector<TreePatternNode*> Children;
3448 Children.push_back(OpNode);
3449 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3450 }
3451
3452 ResultNodeOperands.push_back(OpNode);
3453 }
3454
3455 if (!InstInputsCheck.empty())
3456 I->error("Input operand $" + InstInputsCheck.begin()->first +
3457 " occurs in pattern but not in operands list!");
3458
3459 TreePatternNode *ResultPattern =
3460 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3461 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003462 // Copy fully inferred output node types to instruction result pattern.
3463 for (unsigned i = 0; i != NumResults; ++i) {
3464 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3465 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3466 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003467
3468 // Create and insert the instruction.
3469 // FIXME: InstImpResults should not be part of DAGInstruction.
3470 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3471 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3472
3473 // Use a temporary tree pattern to infer all types and make sure that the
3474 // constructed result is correct. This depends on the instruction already
3475 // being inserted into the DAGInsts map.
3476 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3477 Temp.InferAllTypes(&I->getNamedNodesMap());
3478
3479 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3480 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3481
3482 return TheInsertedInst;
3483}
3484
Ahmed Bougacha14107512013-10-28 18:07:21 +00003485/// ParseInstructions - Parse all of the instructions, inlining and resolving
3486/// any fragments involved. This populates the Instructions list with fully
3487/// resolved instructions.
3488void CodeGenDAGPatterns::ParseInstructions() {
3489 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3490
Craig Topper306cb122015-11-22 20:46:24 +00003491 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003492 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003493
Craig Topper306cb122015-11-22 20:46:24 +00003494 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3495 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003496
3497 // If there is no pattern, only collect minimal information about the
3498 // instruction for its operand list. We have to assume that there is one
3499 // result, as we have no detailed info. A pattern which references the
3500 // null_frag operator is as-if no pattern were specified. Normally this
3501 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3502 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003503 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003504 std::vector<Record*> Results;
3505 std::vector<Record*> Operands;
3506
Craig Topper306cb122015-11-22 20:46:24 +00003507 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003508
3509 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003510 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3511 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003512
Craig Topper3a8eb892015-03-20 05:09:06 +00003513 // The rest are inputs.
3514 for (unsigned j = InstInfo.Operands.NumDefs,
3515 e = InstInfo.Operands.size(); j < e; ++j)
3516 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003517 }
3518
3519 // Create and insert the instruction.
3520 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003521 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003522 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003523 continue; // no pattern.
3524 }
3525
Craig Topper306cb122015-11-22 20:46:24 +00003526 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003527 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3528
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003529 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003530 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003531 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003532
Chris Lattner8cab0212008-01-05 22:25:12 +00003533 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003534 for (auto &Entry : Instructions) {
3535 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003536 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003537 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003538
3539 // FIXME: Assume only the first tree is the pattern. The others are clobber
3540 // nodes.
3541 TreePatternNode *Pattern = I->getTree(0);
3542 TreePatternNode *SrcPattern;
3543 if (Pattern->getOperator()->getName() == "set") {
3544 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3545 } else{
3546 // Not a set (store or something?)
3547 SrcPattern = Pattern;
3548 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003549
Craig Topper306cb122015-11-22 20:46:24 +00003550 Record *Instr = Entry.first;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003551 ListInit *Preds = Instr->getValueAsListInit("Predicates");
3552 int Complexity = Instr->getValueAsInt("AddedComplexity");
3553 AddPatternToMatch(
3554 I,
3555 PatternToMatch(Instr, makePredList(Preds), SrcPattern,
3556 TheInst.getResultPattern(), TheInst.getImpResults(),
3557 Complexity, Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003558 }
3559}
3560
Chris Lattnera7722b62010-02-23 06:55:24 +00003561
3562typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3563
Jim Grosbach65586fe2010-12-21 16:16:00 +00003564static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003565 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003566 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003567 if (!P->getName().empty()) {
3568 NameRecord &Rec = Names[P->getName()];
3569 // If this is the first instance of the name, remember the node.
3570 if (Rec.second++ == 0)
3571 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003572 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003573 PatternTop->error("repetition of value: $" + P->getName() +
3574 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003575 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003576
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003577 if (!P->isLeaf()) {
3578 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003579 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003580 }
3581}
3582
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003583std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3584 std::vector<Predicate> Preds;
3585 for (Init *I : L->getValues()) {
3586 if (DefInit *Pred = dyn_cast<DefInit>(I))
3587 Preds.push_back(Pred->getDef());
3588 else
3589 llvm_unreachable("Non-def on the list");
3590 }
3591
3592 // Sort so that different orders get canonicalized to the same string.
3593 std::sort(Preds.begin(), Preds.end());
3594 return Preds;
3595}
3596
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003597void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003598 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003599 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003600 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003601 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3602 PrintWarning(Pattern->getRecord()->getLoc(),
3603 Twine("Pattern can never match: ") + Reason);
3604 return;
3605 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003606
Chris Lattner1e634e32010-03-01 22:29:19 +00003607 // If the source pattern's root is a complex pattern, that complex pattern
3608 // must specify the nodes it can potentially match.
3609 if (const ComplexPattern *CP =
3610 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3611 if (CP->getRootNodes().empty())
3612 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3613 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003614
3615
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003616 // Find all of the named values in the input and output, ensure they have the
3617 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003618 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003619 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3620 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003621
3622 // Scan all of the named values in the destination pattern, rejecting them if
3623 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003624 for (const auto &Entry : DstNames) {
3625 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003626 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003627 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003628 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003629
Chris Lattnera7722b62010-02-23 06:55:24 +00003630 // Scan all of the named values in the source pattern, rejecting them if the
3631 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003632 for (const auto &Entry : SrcNames)
3633 if (DstNames[Entry.first].first == nullptr &&
3634 SrcNames[Entry.first].second == 1)
3635 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003636
Craig Topper18e6b572017-06-25 17:33:49 +00003637 PatternsToMatch.push_back(std::move(PTM));
Chris Lattner0c0baa92010-02-23 06:16:51 +00003638}
3639
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003640void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003641 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003642 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003643
3644 // First try to infer flags from the primary instruction pattern, if any.
3645 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003646 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003647 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3648 CodeGenInstruction &InstInfo =
3649 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003650
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003651 // Get the primary instruction pattern.
3652 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3653 if (!Pattern) {
3654 if (InstInfo.hasUndefFlags())
3655 Revisit.push_back(&InstInfo);
3656 continue;
3657 }
3658 InstAnalyzer PatInfo(*this);
3659 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003660 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003661 }
3662
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003663 // Second, look for single-instruction patterns defined outside the
3664 // instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003665 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003666 // We can only infer from single-instruction patterns, otherwise we won't
3667 // know which instruction should get the flags.
3668 SmallVector<Record*, 8> PatInstrs;
3669 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3670 if (PatInstrs.size() != 1)
3671 continue;
3672
3673 // Get the single instruction.
3674 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3675
3676 // Only infer properties from the first pattern. We'll verify the others.
3677 if (InstInfo.InferredFrom)
3678 continue;
3679
3680 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003681 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003682 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3683 }
3684
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003685 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003686 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003687
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003688 // Revisit instructions with undefined flags and no pattern.
3689 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003690 for (CodeGenInstruction *InstInfo : Revisit) {
3691 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003692 continue;
3693 // The mayLoad and mayStore flags default to false.
3694 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003695 if (InstInfo->hasSideEffects_Unset)
3696 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003697 }
3698 return;
3699 }
3700
3701 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003702 for (CodeGenInstruction *InstInfo : Revisit) {
3703 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003704 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003705 if (InstInfo->hasSideEffects_Unset)
3706 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003707 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003708 if (InstInfo->mayStore_Unset)
3709 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003710 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003711 if (InstInfo->mayLoad_Unset)
3712 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003713 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003714 }
3715}
3716
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003717
3718/// Verify instruction flags against pattern node properties.
3719void CodeGenDAGPatterns::VerifyInstructionFlags() {
3720 unsigned Errors = 0;
3721 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3722 const PatternToMatch &PTM = *I;
3723 SmallVector<Record*, 8> Instrs;
3724 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3725 if (Instrs.empty())
3726 continue;
3727
3728 // Count the number of instructions with each flag set.
3729 unsigned NumSideEffects = 0;
3730 unsigned NumStores = 0;
3731 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003732 for (const Record *Instr : Instrs) {
3733 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003734 NumSideEffects += InstInfo.hasSideEffects;
3735 NumStores += InstInfo.mayStore;
3736 NumLoads += InstInfo.mayLoad;
3737 }
3738
3739 // Analyze the source pattern.
3740 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003741 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003742
3743 // Collect error messages.
3744 SmallVector<std::string, 4> Msgs;
3745
3746 // Check for missing flags in the output.
3747 // Permit extra flags for now at least.
3748 if (PatInfo.hasSideEffects && !NumSideEffects)
3749 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3750
3751 // Don't verify store flags on instructions with side effects. At least for
3752 // intrinsics, side effects implies mayStore.
3753 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3754 Msgs.push_back("pattern may store, but mayStore isn't set");
3755
3756 // Similarly, mayStore implies mayLoad on intrinsics.
3757 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3758 Msgs.push_back("pattern may load, but mayLoad isn't set");
3759
3760 // Print error messages.
3761 if (Msgs.empty())
3762 continue;
3763 ++Errors;
3764
Craig Topper306cb122015-11-22 20:46:24 +00003765 for (const std::string &Msg : Msgs)
3766 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003767 (Instrs.size() == 1 ?
3768 "instruction" : "output instructions"));
3769 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003770 for (const Record *Instr : Instrs) {
3771 if (Instr != PTM.getSrcRecord())
3772 PrintError(Instr->getLoc(), "defined here");
3773 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003774 if (InstInfo.InferredFrom &&
3775 InstInfo.InferredFrom != InstInfo.TheDef &&
3776 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003777 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003778 }
3779 }
3780 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003781 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003782}
3783
Chris Lattnercabe0372010-03-15 06:00:16 +00003784/// Given a pattern result with an unresolved type, see if we can find one
3785/// instruction with an unresolved result type. Force this result type to an
3786/// arbitrary element if it's possible types to converge results.
3787static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3788 if (N->isLeaf())
3789 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003790
Chris Lattnercabe0372010-03-15 06:00:16 +00003791 // Analyze children.
3792 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3793 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3794 return true;
3795
3796 if (!N->getOperator()->isSubClassOf("Instruction"))
3797 return false;
3798
3799 // If this type is already concrete or completely unknown we can't do
3800 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003801 TypeInfer &TI = TP.getInfer();
Chris Lattnerf1447252010-03-19 21:37:09 +00003802 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003803 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003804 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003805
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003806 // Otherwise, force its type to an arbitrary choice.
3807 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003808 return true;
3809 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003810
Chris Lattnerf1447252010-03-19 21:37:09 +00003811 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003812}
3813
Chris Lattnerab3242f2008-01-06 01:10:31 +00003814void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003815 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3816
Craig Topper306cb122015-11-22 20:46:24 +00003817 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003818 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003819
3820 // If the pattern references the null_frag, there's nothing to do.
3821 if (hasNullFragReference(Tree))
3822 continue;
3823
Chris Lattner5c2182e2010-03-27 02:53:27 +00003824 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003825
3826 // Inline pattern fragments into it.
3827 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003828
David Greeneaf8ee2c2011-07-29 22:43:06 +00003829 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003830 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003831
Chris Lattner8cab0212008-01-05 22:25:12 +00003832 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003833 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003834
Chris Lattner8cab0212008-01-05 22:25:12 +00003835 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003836 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003837
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003838 if (Result.getNumTrees() != 1)
3839 Result.error("Cannot handle instructions producing instructions "
3840 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003841
Chris Lattner8cab0212008-01-05 22:25:12 +00003842 bool IterateInference;
3843 bool InferredAllPatternTypes, InferredAllResultTypes;
3844 do {
3845 // Infer as many types as possible. If we cannot infer all of them, we
3846 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003847 InferredAllPatternTypes =
3848 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003849
Chris Lattner8cab0212008-01-05 22:25:12 +00003850 // Infer as many types as possible. If we cannot infer all of them, we
3851 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003852 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003853 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003854
Chris Lattnerfdc20712010-03-18 23:15:10 +00003855 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003856
Chris Lattner8cab0212008-01-05 22:25:12 +00003857 // Apply the type of the result to the source pattern. This helps us
3858 // resolve cases where the input type is known to be a pointer type (which
3859 // is considered resolved), but the result knows it needs to be 32- or
3860 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003861 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003862 Pattern->getTree(0)->getNumTypes());
3863 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003864 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3865 i, Result.getTree(0)->getExtType(i), Result);
3866 IterateInference |= Result.getTree(0)->UpdateNodeType(
3867 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003868 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003869
Chris Lattnercabe0372010-03-15 06:00:16 +00003870 // If our iteration has converged and the input pattern's types are fully
3871 // resolved but the result pattern is not fully resolved, we may have a
3872 // situation where we have two instructions in the result pattern and
3873 // the instructions require a common register class, but don't care about
3874 // what actual MVT is used. This is actually a bug in our modelling:
3875 // output patterns should have register classes, not MVTs.
3876 //
3877 // In any case, to handle this, we just go through and disambiguate some
3878 // arbitrary types to the result pattern's nodes.
3879 if (!IterateInference && InferredAllPatternTypes &&
3880 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003881 IterateInference =
3882 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003883 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003884
Chris Lattner8cab0212008-01-05 22:25:12 +00003885 // Verify that we inferred enough types that we can do something with the
3886 // pattern and result. If these fire the user has to add type casts.
3887 if (!InferredAllPatternTypes)
3888 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003889 if (!InferredAllResultTypes) {
3890 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003891 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003892 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003893
Chris Lattner8cab0212008-01-05 22:25:12 +00003894 // Validate that the input pattern is correct.
3895 std::map<std::string, TreePatternNode*> InstInputs;
3896 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003897 std::vector<Record*> InstImpResults;
3898 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3899 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3900 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003901 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003902
3903 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003904 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003905 std::vector<TreePatternNode*> ResultNodeOperands;
3906 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3907 TreePatternNode *OpNode = DstPattern->getChild(ii);
3908 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003909 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003910 std::vector<TreePatternNode*> Children;
3911 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003912 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003913 }
3914 ResultNodeOperands.push_back(OpNode);
3915 }
David Blaikiecf195302014-11-17 22:55:41 +00003916 DstPattern = Result.getOnlyTree();
3917 if (!DstPattern->isLeaf())
3918 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3919 ResultNodeOperands,
3920 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003921
David Blaikiecf195302014-11-17 22:55:41 +00003922 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3923 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3924
3925 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003926 Temp.InferAllTypes();
3927
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003928 // A pattern may end up with an "impossible" type, i.e. a situation
3929 // where all types have been eliminated for some node in this pattern.
3930 // This could occur for intrinsics that only make sense for a specific
3931 // value type, and use a specific register class. If, for some mode,
3932 // that register class does not accept that type, the type inference
3933 // will lead to a contradiction, which is not an error however, but
3934 // a sign that this pattern will simply never match.
3935 if (Pattern->getTree(0)->hasPossibleType() &&
3936 Temp.getOnlyTree()->hasPossibleType()) {
3937 ListInit *Preds = CurPattern->getValueAsListInit("Predicates");
3938 int Complexity = CurPattern->getValueAsInt("AddedComplexity");
3939 AddPatternToMatch(
3940 Pattern,
3941 PatternToMatch(
3942 CurPattern, makePredList(Preds), Pattern->getTree(0),
3943 Temp.getOnlyTree(), std::move(InstImpResults), Complexity,
3944 CurPattern->getID()));
3945 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003946 }
3947}
3948
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003949static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
3950 for (const TypeSetByHwMode &VTS : N->getExtTypes())
3951 for (const auto &I : VTS)
3952 Modes.insert(I.first);
3953
3954 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3955 collectModes(Modes, N->getChild(i));
3956}
3957
3958void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
3959 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3960 std::map<unsigned,std::vector<Predicate>> ModeChecks;
3961 std::vector<PatternToMatch> Copy = PatternsToMatch;
3962 PatternsToMatch.clear();
3963
3964 auto AppendPattern = [this,&ModeChecks](PatternToMatch &P, unsigned Mode) {
3965 TreePatternNode *NewSrc = P.SrcPattern->clone();
3966 TreePatternNode *NewDst = P.DstPattern->clone();
3967 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
3968 delete NewSrc;
3969 delete NewDst;
3970 return;
3971 }
3972
3973 std::vector<Predicate> Preds = P.Predicates;
3974 const std::vector<Predicate> &MC = ModeChecks[Mode];
3975 Preds.insert(Preds.end(), MC.begin(), MC.end());
3976 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, NewSrc, NewDst,
3977 P.getDstRegs(), P.getAddedComplexity(),
3978 Record::getNewUID(), Mode);
3979 };
3980
3981 for (PatternToMatch &P : Copy) {
3982 TreePatternNode *SrcP = nullptr, *DstP = nullptr;
3983 if (P.SrcPattern->hasProperTypeByHwMode())
3984 SrcP = P.SrcPattern;
3985 if (P.DstPattern->hasProperTypeByHwMode())
3986 DstP = P.DstPattern;
3987 if (!SrcP && !DstP) {
3988 PatternsToMatch.push_back(P);
3989 continue;
3990 }
3991
3992 std::set<unsigned> Modes;
3993 if (SrcP)
3994 collectModes(Modes, SrcP);
3995 if (DstP)
3996 collectModes(Modes, DstP);
3997
3998 // The predicate for the default mode needs to be constructed for each
3999 // pattern separately.
4000 // Since not all modes must be present in each pattern, if a mode m is
4001 // absent, then there is no point in constructing a check for m. If such
4002 // a check was created, it would be equivalent to checking the default
4003 // mode, except not all modes' predicates would be a part of the checking
4004 // code. The subsequently generated check for the default mode would then
4005 // have the exact same patterns, but a different predicate code. To avoid
4006 // duplicated patterns with different predicate checks, construct the
4007 // default check as a negation of all predicates that are actually present
4008 // in the source/destination patterns.
4009 std::vector<Predicate> DefaultPred;
4010
4011 for (unsigned M : Modes) {
4012 if (M == DefaultMode)
4013 continue;
4014 if (ModeChecks.find(M) != ModeChecks.end())
4015 continue;
4016
4017 // Fill the map entry for this mode.
4018 const HwMode &HM = CGH.getMode(M);
4019 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4020
4021 // Add negations of the HM's predicates to the default predicate.
4022 DefaultPred.emplace_back(Predicate(HM.Features, false));
4023 }
4024
4025 for (unsigned M : Modes) {
4026 if (M == DefaultMode)
4027 continue;
4028 AppendPattern(P, M);
4029 }
4030
4031 bool HasDefault = Modes.count(DefaultMode);
4032 if (HasDefault)
4033 AppendPattern(P, DefaultMode);
4034 }
4035}
4036
4037/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004038typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004039
4040static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4041 if (N->isLeaf()) {
Zachary Turner249dc142017-09-20 18:01:40 +00004042 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004043 DepMap[N->getName()]++;
4044 } else {
4045 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4046 FindDepVarsOf(N->getChild(i), DepMap);
4047 }
4048}
4049
4050/// Find dependent variables within child patterns
4051static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
4052 DepVarMap depcounts;
4053 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004054 for (const auto &Pair : depcounts) {
4055 if (Pair.getValue() > 1)
4056 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004057 }
4058}
4059
4060#ifndef NDEBUG
4061/// Dump the dependent variable set:
4062static void DumpDepVars(MultipleUseVarSet &DepVars) {
4063 if (DepVars.empty()) {
4064 DEBUG(errs() << "<empty set>");
4065 } else {
4066 DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004067 for (const auto &DepVar : DepVars) {
4068 DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004069 }
4070 DEBUG(errs() << "]");
4071 }
4072}
4073#endif
4074
4075
Chris Lattner8cab0212008-01-05 22:25:12 +00004076/// CombineChildVariants - Given a bunch of permutations of each child of the
4077/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004078static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00004079 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
4080 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004081 CodeGenDAGPatterns &CDP,
4082 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004083 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004084 for (const auto &Variants : ChildVariants)
4085 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004086 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004087
Chris Lattner8cab0212008-01-05 22:25:12 +00004088 // The end result is an all-pairs construction of the resultant pattern.
4089 std::vector<unsigned> Idxs;
4090 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004091 bool NotDone;
4092 do {
4093#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00004094 DEBUG(if (!Idxs.empty()) {
4095 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00004096 for (unsigned Idx : Idxs) {
4097 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00004098 }
4099 errs() << "]\n";
4100 });
Scott Michel94420742008-03-05 17:49:05 +00004101#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004102 // Create the variant and add it to the output list.
4103 std::vector<TreePatternNode*> NewChildren;
4104 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4105 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00004106 auto R = llvm::make_unique<TreePatternNode>(
4107 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004108
Chris Lattner8cab0212008-01-05 22:25:12 +00004109 // Copy over properties.
4110 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00004111 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00004112 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00004113 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4114 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004115
Scott Michel94420742008-03-05 17:49:05 +00004116 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004117 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004118 // Scan to see if this pattern has already been emitted. We can get
4119 // duplication due to things like commuting:
4120 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4121 // which are the same pattern. Ignore the dups.
4122 if (R->canPatternMatch(ErrString, CDP) &&
David Majnemer0a16c222016-08-11 21:15:00 +00004123 none_of(OutVariants, [&](TreePatternNode *Variant) {
4124 return R->isIsomorphicTo(Variant, DepVars);
4125 }))
David Blaikiefda69dd2015-11-22 20:11:21 +00004126 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004127
Scott Michel94420742008-03-05 17:49:05 +00004128 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004129 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004130 // [0, 0], [0, 1], [1, 0], [1, 1].
4131 int IdxsIdx;
4132 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4133 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4134 Idxs[IdxsIdx] = 0;
4135 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004136 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004137 }
Scott Michel94420742008-03-05 17:49:05 +00004138 NotDone = (IdxsIdx >= 0);
4139 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004140}
4141
4142/// CombineChildVariants - A helper function for binary operators.
4143///
Jim Grosbach65586fe2010-12-21 16:16:00 +00004144static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00004145 const std::vector<TreePatternNode*> &LHS,
4146 const std::vector<TreePatternNode*> &RHS,
4147 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004148 CodeGenDAGPatterns &CDP,
4149 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004150 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4151 ChildVariants.push_back(LHS);
4152 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004153 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004154}
Chris Lattner8cab0212008-01-05 22:25:12 +00004155
4156
4157static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
4158 std::vector<TreePatternNode *> &Children) {
4159 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4160 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004161
Chris Lattner8cab0212008-01-05 22:25:12 +00004162 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00004163 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004164 N->getTransformFn()) {
4165 Children.push_back(N);
4166 return;
4167 }
4168
4169 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
4170 Children.push_back(N->getChild(0));
4171 else
4172 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
4173
4174 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
4175 Children.push_back(N->getChild(1));
4176 else
4177 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
4178}
4179
4180/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4181/// the (potentially recursive) pattern by using algebraic laws.
4182///
4183static void GenerateVariantsOf(TreePatternNode *N,
4184 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004185 CodeGenDAGPatterns &CDP,
4186 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004187 // We cannot permute leaves or ComplexPattern uses.
4188 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004189 OutVariants.push_back(N);
4190 return;
4191 }
4192
4193 // Look up interesting info about the node.
4194 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4195
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004196 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004197 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004198 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00004199 std::vector<TreePatternNode*> MaximalChildren;
4200 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4201
4202 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4203 // permutations.
4204 if (MaximalChildren.size() == 3) {
4205 // Find the variants of all of our maximal children.
4206 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004207 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4208 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4209 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004210
Chris Lattner8cab0212008-01-05 22:25:12 +00004211 // There are only two ways we can permute the tree:
4212 // (A op B) op C and A op (B op C)
4213 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004214
Chris Lattner8cab0212008-01-05 22:25:12 +00004215 // Generate legal pair permutations of A/B/C.
4216 std::vector<TreePatternNode*> ABVariants;
4217 std::vector<TreePatternNode*> BAVariants;
4218 std::vector<TreePatternNode*> ACVariants;
4219 std::vector<TreePatternNode*> CAVariants;
4220 std::vector<TreePatternNode*> BCVariants;
4221 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00004222 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4223 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4224 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4225 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4226 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4227 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004228
4229 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00004230 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4231 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4232 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4233 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4234 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4235 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004236
4237 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00004238 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4239 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4240 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4241 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4242 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4243 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004244 return;
4245 }
4246 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004247
Chris Lattner8cab0212008-01-05 22:25:12 +00004248 // Compute permutations of all children.
4249 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4250 ChildVariants.resize(N->getNumChildren());
4251 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00004252 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004253
4254 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00004255 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004256
4257 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004258 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4259 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004260 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004261 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004262 // Don't count children which are actually register references.
4263 unsigned NC = 0;
4264 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4265 TreePatternNode *Child = N->getChild(i);
4266 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00004267 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004268 Record *RR = DI->getDef();
4269 if (RR->isSubClassOf("Register"))
4270 continue;
4271 }
4272 NC++;
4273 }
4274 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004275 if (isCommIntrinsic) {
4276 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4277 // operands are the commutative operands, and there might be more operands
4278 // after those.
4279 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004280 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00004281 std::vector<std::vector<TreePatternNode*> > Variants;
4282 Variants.push_back(ChildVariants[0]); // Intrinsic id.
4283 Variants.push_back(ChildVariants[2]);
4284 Variants.push_back(ChildVariants[1]);
4285 for (unsigned i = 3; i != NC; ++i)
4286 Variants.push_back(ChildVariants[i]);
4287 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004288 } else if (NC == N->getNumChildren()) {
4289 std::vector<std::vector<TreePatternNode*> > Variants;
4290 Variants.push_back(ChildVariants[1]);
4291 Variants.push_back(ChildVariants[0]);
4292 for (unsigned i = 2; i != NC; ++i)
4293 Variants.push_back(ChildVariants[i]);
4294 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4295 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004296 }
4297}
4298
4299
4300// GenerateVariants - Generate variants. For example, commutative patterns can
4301// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004302void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00004303 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004304
Chris Lattner8cab0212008-01-05 22:25:12 +00004305 // Loop over all of the patterns we've collected, checking to see if we can
4306 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004307 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004308 // the .td file having to contain tons of variants of instructions.
4309 //
4310 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4311 // intentionally do not reconsider these. Any variants of added patterns have
4312 // already been added.
4313 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00004314 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00004315 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00004316 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004317 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00004318 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00004319 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00004320 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00004321 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00004322 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004323
4324 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00004325 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004326 continue;
4327
Chris Lattner34822f62009-08-23 04:44:11 +00004328 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00004329 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00004330 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004331
4332 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4333 TreePatternNode *Variant = Variants[v];
4334
Chris Lattner34822f62009-08-23 04:44:11 +00004335 DEBUG(errs() << " VAR#" << v << ": ";
4336 Variant->dump();
4337 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004338
Chris Lattner8cab0212008-01-05 22:25:12 +00004339 // Scan to see if an instruction or explicit pattern already matches this.
4340 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004341 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004342 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004343 if (PatternsToMatch[i].getPredicates() !=
4344 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00004345 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004346 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004347 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4348 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00004349 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004350 AlreadyExists = true;
4351 break;
4352 }
4353 }
4354 // If we already have it, ignore the variant.
4355 if (AlreadyExists) continue;
4356
4357 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004358 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004359 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4360 Variant, PatternsToMatch[i].getDstPattern(),
4361 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004362 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00004363 }
4364
Chris Lattner34822f62009-08-23 04:44:11 +00004365 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004366 }
4367}