blob: c9dc8a96c8cee35a983cbabc38d8b3959c02a814 [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;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000102 bool ContainsDefault = false;
103 MVT DT = MVT::Other;
104
Zachary Turner249dc142017-09-20 18:01:40 +0000105 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000106 for (const auto &P : VVT) {
107 unsigned M = P.first;
108 Modes.insert(M);
109 // Make sure there exists a set for each specific mode from VVT.
110 Changed |= getOrCreate(M).insert(P.second).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000111 // Cache VVT's default mode.
112 if (DefaultMode == M) {
113 ContainsDefault = true;
114 DT = P.second;
115 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000116 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000117
118 // If VVT has a default mode, add the corresponding type to all
119 // modes in "this" that do not exist in VVT.
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000120 if (ContainsDefault)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000121 for (auto &I : *this)
122 if (!Modes.count(I.first))
123 Changed |= I.second.insert(DT).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000124
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000125 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000126}
127
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000128// Constrain the type set to be the intersection with VTS.
129bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
130 bool Changed = false;
131 if (hasDefault()) {
132 for (const auto &I : VTS) {
133 unsigned M = I.first;
134 if (M == DefaultMode || hasMode(M))
135 continue;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000136 Map.insert({M, Map.at(DefaultMode)});
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000137 Changed = true;
138 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000139 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000140
141 for (auto &I : *this) {
142 unsigned M = I.first;
143 SetType &S = I.second;
144 if (VTS.hasMode(M) || VTS.hasDefault()) {
145 Changed |= intersect(I.second, VTS.get(M));
146 } else if (!S.empty()) {
147 S.clear();
148 Changed = true;
149 }
150 }
151 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000152}
153
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000154template <typename Predicate>
155bool TypeSetByHwMode::constrain(Predicate P) {
156 bool Changed = false;
157 for (auto &I : *this)
Benjamin Kramere57308e2017-09-17 11:19:53 +0000158 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000159 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000160}
161
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000162template <typename Predicate>
163bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
164 assert(empty());
165 for (const auto &I : VTS) {
166 SetType &S = getOrCreate(I.first);
167 for (auto J : I.second)
168 if (P(J))
169 S.insert(J);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000170 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000171 return !empty();
Chris Lattnercabe0372010-03-15 06:00:16 +0000172}
173
Zachary Turner249dc142017-09-20 18:01:40 +0000174void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
175 SmallVector<unsigned, 4> Modes;
176 Modes.reserve(Map.size());
Chris Lattnercabe0372010-03-15 06:00:16 +0000177
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000178 for (const auto &I : *this)
179 Modes.push_back(I.first);
Zachary Turner249dc142017-09-20 18:01:40 +0000180 if (Modes.empty()) {
181 OS << "{}";
182 return;
183 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000184 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000185
Zachary Turner249dc142017-09-20 18:01:40 +0000186 OS << '{';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000187 for (unsigned M : Modes) {
Zachary Turner249dc142017-09-20 18:01:40 +0000188 OS << ' ' << getModeName(M) << ':';
189 writeToStream(get(M), OS);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000190 }
Zachary Turner249dc142017-09-20 18:01:40 +0000191 OS << " }";
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000192}
193
Zachary Turner249dc142017-09-20 18:01:40 +0000194void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
195 SmallVector<MVT, 4> Types(S.begin(), S.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000196 array_pod_sort(Types.begin(), Types.end());
197
Zachary Turner249dc142017-09-20 18:01:40 +0000198 OS << '[';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000199 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
Zachary Turner249dc142017-09-20 18:01:40 +0000200 OS << ValueTypeByHwMode::getMVTName(Types[i]);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000201 if (i != e-1)
Zachary Turner249dc142017-09-20 18:01:40 +0000202 OS << ' ';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000203 }
Zachary Turner249dc142017-09-20 18:01:40 +0000204 OS << ']';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000205}
206
207bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
Simon Pilgrim0e181332018-08-16 16:16:28 +0000208 // The isSimple call is much quicker than hasDefault - check this first.
209 bool IsSimple = isSimple();
210 bool VTSIsSimple = VTS.isSimple();
211 if (IsSimple && VTSIsSimple)
212 return *begin() == *VTS.begin();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000213
Simon Pilgrim0e181332018-08-16 16:16:28 +0000214 // Speedup: We have a default if the set is simple.
215 bool HaveDefault = IsSimple || hasDefault();
216 bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
217 if (HaveDefault != VTSHaveDefault)
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000218 return false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000219
Zachary Turner249dc142017-09-20 18:01:40 +0000220 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000221 for (auto &I : *this)
222 Modes.insert(I.first);
223 for (const auto &I : VTS)
224 Modes.insert(I.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000225
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000226 if (HaveDefault) {
227 // Both sets have default mode.
228 for (unsigned M : Modes) {
229 if (get(M) != VTS.get(M))
David Majnemerc7004902016-08-12 04:32:37 +0000230 return false;
Craig Topper5712d462015-11-24 08:20:47 +0000231 }
Scott Michel94420742008-03-05 17:49:05 +0000232 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000233 // Neither set has default mode.
234 for (unsigned M : Modes) {
235 // If there is no default mode, an empty set is equivalent to not having
236 // the corresponding mode.
237 bool NoModeThis = !hasMode(M) || get(M).empty();
238 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
239 if (NoModeThis != NoModeVTS)
240 return false;
241 if (!NoModeThis)
242 if (get(M) != VTS.get(M))
243 return false;
244 }
Scott Michel94420742008-03-05 17:49:05 +0000245 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000246
247 return true;
Scott Michel94420742008-03-05 17:49:05 +0000248}
249
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000250namespace llvm {
251 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
252 T.writeToStream(OS);
253 return OS;
254 }
255}
256
Krzysztof Parzyszek426bf362017-09-12 15:31:26 +0000257LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000258void TypeSetByHwMode::dump() const {
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000259 dbgs() << *this << '\n';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000260}
261
262bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
263 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
264 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
265
266 if (OutP == InP)
267 return berase_if(Out, Int);
268
269 // Compute the intersection of scalars separately to account for only
270 // one set containing iPTR.
271 // The itersection of iPTR with a set of integer scalar types that does not
272 // include iPTR will result in the most specific scalar type:
273 // - iPTR is more specific than any set with two elements or more
274 // - iPTR is less specific than any single integer scalar type.
275 // For example
276 // { iPTR } * { i32 } -> { i32 }
277 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000278 // and
279 // { iPTR i32 } * { i32 } -> { i32 }
280 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
281 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000282
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000283 // Compute the difference between the two sets in such a way that the
284 // iPTR is in the set that is being subtracted. This is to see if there
285 // are any extra scalars in the set without iPTR that are not in the
286 // set containing iPTR. Then the iPTR could be considered a "wildcard"
287 // matching these scalars. If there is only one such scalar, it would
288 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000289 SetType Diff;
290 if (InP) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000291 Diff = Out;
292 berase_if(Diff, [&In](MVT T) { return In.count(T); });
293 // Pre-remove these elements and rely only on InP/OutP to determine
294 // whether a change has been made.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000295 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000296 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000297 Diff = In;
298 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000299 Out.erase(MVT::iPTR);
300 }
301
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000302 // The actual intersection.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000303 bool Changed = berase_if(Out, Int);
304 unsigned NumD = Diff.size();
305 if (NumD == 0)
306 return Changed;
307
308 if (NumD == 1) {
309 Out.insert(*Diff.begin());
310 // This is a change only if Out was the one with iPTR (which is now
311 // being replaced).
312 Changed |= OutP;
313 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000314 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000315 Out.insert(MVT::iPTR);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000316 Changed |= !OutP;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000317 }
318 return Changed;
319}
320
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000321bool TypeSetByHwMode::validate() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000322#ifndef NDEBUG
323 if (empty())
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000324 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000325 bool AllEmpty = true;
326 for (const auto &I : *this)
327 AllEmpty &= I.second.empty();
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000328 return !AllEmpty;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000329#endif
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000330 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000331}
332
333// --- TypeInfer
334
335bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
336 const TypeSetByHwMode &In) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000337 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000338 In.validate();
339 if (In.empty() || Out == In || TP.hasError())
340 return false;
341 if (Out.empty()) {
342 Out = In;
343 return true;
344 }
345
346 bool Changed = Out.constrain(In);
347 if (Changed && Out.empty())
348 TP.error("Type contradiction");
349
350 return Changed;
351}
352
353bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000354 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000355 if (TP.hasError())
356 return false;
357 assert(!Out.empty() && "cannot pick from an empty set");
358
359 bool Changed = false;
360 for (auto &I : Out) {
361 TypeSetByHwMode::SetType &S = I.second;
362 if (S.size() <= 1)
363 continue;
364 MVT T = *S.begin(); // Pick the first element.
365 S.clear();
366 S.insert(T);
367 Changed = true;
368 }
369 return Changed;
370}
371
372bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000373 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000374 if (TP.hasError())
375 return false;
376 if (!Out.empty())
377 return Out.constrain(isIntegerOrPtr);
378
379 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
380}
381
382bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000383 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000384 if (TP.hasError())
385 return false;
386 if (!Out.empty())
387 return Out.constrain(isFloatingPoint);
388
389 return Out.assign_if(getLegalTypes(), isFloatingPoint);
390}
391
392bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000393 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000394 if (TP.hasError())
395 return false;
396 if (!Out.empty())
397 return Out.constrain(isScalar);
398
399 return Out.assign_if(getLegalTypes(), isScalar);
400}
401
402bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000403 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000404 if (TP.hasError())
405 return false;
406 if (!Out.empty())
407 return Out.constrain(isVector);
408
409 return Out.assign_if(getLegalTypes(), isVector);
410}
411
412bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000413 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000414 if (TP.hasError() || !Out.empty())
415 return false;
416
417 Out = getLegalTypes();
418 return true;
419}
420
421template <typename Iter, typename Pred, typename Less>
422static Iter min_if(Iter B, Iter E, Pred P, Less L) {
423 if (B == E)
424 return E;
425 Iter Min = E;
426 for (Iter I = B; I != E; ++I) {
427 if (!P(*I))
428 continue;
429 if (Min == E || L(*I, *Min))
430 Min = I;
431 }
432 return Min;
433}
434
435template <typename Iter, typename Pred, typename Less>
436static Iter max_if(Iter B, Iter E, Pred P, Less L) {
437 if (B == E)
438 return E;
439 Iter Max = E;
440 for (Iter I = B; I != E; ++I) {
441 if (!P(*I))
442 continue;
443 if (Max == E || L(*Max, *I))
444 Max = I;
445 }
446 return Max;
447}
448
449/// Make sure that for each type in Small, there exists a larger type in Big.
450bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
451 TypeSetByHwMode &Big) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000452 ValidateOnExit _1(Small, *this), _2(Big, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000453 if (TP.hasError())
454 return false;
455 bool Changed = false;
456
457 if (Small.empty())
458 Changed |= EnforceAny(Small);
459 if (Big.empty())
460 Changed |= EnforceAny(Big);
461
462 assert(Small.hasDefault() && Big.hasDefault());
463
464 std::vector<unsigned> Modes = union_modes(Small, Big);
465
466 // 1. Only allow integer or floating point types and make sure that
467 // both sides are both integer or both floating point.
468 // 2. Make sure that either both sides have vector types, or neither
469 // of them does.
470 for (unsigned M : Modes) {
471 TypeSetByHwMode::SetType &S = Small.get(M);
472 TypeSetByHwMode::SetType &B = Big.get(M);
473
474 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000475 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000476 Changed |= berase_if(S, NotInt) |
477 berase_if(B, NotInt);
478 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000479 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000480 Changed |= berase_if(S, NotFP) |
481 berase_if(B, NotFP);
482 } else if (S.empty() || B.empty()) {
483 Changed = !S.empty() || !B.empty();
484 S.clear();
485 B.clear();
486 } else {
487 TP.error("Incompatible types");
488 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000489 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000490
491 if (none_of(S, isVector) || none_of(B, isVector)) {
492 Changed |= berase_if(S, isVector) |
493 berase_if(B, isVector);
494 }
495 }
496
497 auto LT = [](MVT A, MVT B) -> bool {
498 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
499 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
500 A.getSizeInBits() < B.getSizeInBits());
501 };
502 auto LE = [](MVT A, MVT B) -> bool {
503 // This function is used when removing elements: when a vector is compared
504 // to a non-vector, it should return false (to avoid removal).
505 if (A.isVector() != B.isVector())
506 return false;
507
508 // Note on the < comparison below:
509 // X86 has patterns like
510 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
511 // where the truncated vector is given a type v16i8, while the source
512 // vector has type v4i32. They both have the same size in bits.
513 // The minimal type in the result is obviously v16i8, and when we remove
514 // all types from the source that are smaller-or-equal than v8i16, the
515 // only source type would also be removed (since it's equal in size).
516 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
517 A.getSizeInBits() < B.getSizeInBits();
518 };
519
520 for (unsigned M : Modes) {
521 TypeSetByHwMode::SetType &S = Small.get(M);
522 TypeSetByHwMode::SetType &B = Big.get(M);
523 // MinS = min scalar in Small, remove all scalars from Big that are
524 // smaller-or-equal than MinS.
525 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000526 if (MinS != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000527 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000528
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000529 // MaxS = max scalar in Big, remove all scalars from Small that are
530 // larger than MaxS.
531 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000532 if (MaxS != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000533 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000534
535 // MinV = min vector in Small, remove all vectors from Big that are
536 // smaller-or-equal than MinV.
537 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000538 if (MinV != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000539 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000540
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000541 // MaxV = max vector in Big, remove all vectors from Small that are
542 // larger than MaxV.
543 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000544 if (MaxV != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000545 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000546 }
547
548 return Changed;
549}
550
551/// 1. Ensure that for each type T in Vec, T is a vector type, and that
552/// for each type U in Elem, U is a scalar type.
553/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
554/// type T in Vec, such that U is the element type of T.
555bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
556 TypeSetByHwMode &Elem) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000557 ValidateOnExit _1(Vec, *this), _2(Elem, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000558 if (TP.hasError())
559 return false;
560 bool Changed = false;
561
562 if (Vec.empty())
563 Changed |= EnforceVector(Vec);
564 if (Elem.empty())
565 Changed |= EnforceScalar(Elem);
566
567 for (unsigned M : union_modes(Vec, Elem)) {
568 TypeSetByHwMode::SetType &V = Vec.get(M);
569 TypeSetByHwMode::SetType &E = Elem.get(M);
570
571 Changed |= berase_if(V, isScalar); // Scalar = !vector
572 Changed |= berase_if(E, isVector); // Vector = !scalar
573 assert(!V.empty() && !E.empty());
574
575 SmallSet<MVT,4> VT, ST;
576 // Collect element types from the "vector" set.
577 for (MVT T : V)
578 VT.insert(T.getVectorElementType());
579 // Collect scalar types from the "element" set.
580 for (MVT T : E)
581 ST.insert(T);
582
583 // Remove from V all (vector) types whose element type is not in S.
584 Changed |= berase_if(V, [&ST](MVT T) -> bool {
585 return !ST.count(T.getVectorElementType());
586 });
587 // Remove from E all (scalar) types, for which there is no corresponding
588 // type in V.
589 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000590 }
591
592 return Changed;
593}
594
595bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
596 const ValueTypeByHwMode &VVT) {
597 TypeSetByHwMode Tmp(VVT);
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000598 ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000599 return EnforceVectorEltTypeIs(Vec, Tmp);
600}
601
602/// Ensure that for each type T in Sub, T is a vector type, and there
603/// exists a type U in Vec such that U is a vector type with the same
604/// element type as T and at least as many elements as T.
605bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
606 TypeSetByHwMode &Sub) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000607 ValidateOnExit _1(Vec, *this), _2(Sub, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000608 if (TP.hasError())
609 return false;
610
611 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
612 auto IsSubVec = [](MVT B, MVT P) -> bool {
613 if (!B.isVector() || !P.isVector())
614 return false;
Florian Hahn603c6452017-11-07 10:43:56 +0000615 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
616 // but until there are obvious use-cases for this, keep the
617 // types separate.
618 if (B.isScalableVector() != P.isScalableVector())
619 return false;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000620 if (B.getVectorElementType() != P.getVectorElementType())
621 return false;
622 return B.getVectorNumElements() < P.getVectorNumElements();
623 };
624
625 /// Return true if S has no element (vector type) that T is a sub-vector of,
626 /// i.e. has the same element type as T and more elements.
627 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
628 for (const auto &I : S)
629 if (IsSubVec(T, I))
630 return false;
631 return true;
632 };
633
634 /// Return true if S has no element (vector type) that T is a super-vector
635 /// of, i.e. has the same element type as T and fewer elements.
636 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
637 for (const auto &I : S)
638 if (IsSubVec(I, T))
639 return false;
640 return true;
641 };
642
643 bool Changed = false;
644
645 if (Vec.empty())
646 Changed |= EnforceVector(Vec);
647 if (Sub.empty())
648 Changed |= EnforceVector(Sub);
649
650 for (unsigned M : union_modes(Vec, Sub)) {
651 TypeSetByHwMode::SetType &S = Sub.get(M);
652 TypeSetByHwMode::SetType &V = Vec.get(M);
653
654 Changed |= berase_if(S, isScalar);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000655
656 // Erase all types from S that are not sub-vectors of a type in V.
657 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000658
659 // Erase all types from V that are not super-vectors of a type in S.
660 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000661 }
662
663 return Changed;
664}
665
666/// 1. Ensure that V has a scalar type iff W has a scalar type.
667/// 2. Ensure that for each vector type T in V, there exists a vector
668/// type U in W, such that T and U have the same number of elements.
669/// 3. Ensure that for each vector type U in W, there exists a vector
670/// type T in V, such that T and U have the same number of elements
671/// (reverse of 2).
672bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000673 ValidateOnExit _1(V, *this), _2(W, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000674 if (TP.hasError())
675 return false;
676
677 bool Changed = false;
678 if (V.empty())
679 Changed |= EnforceAny(V);
680 if (W.empty())
681 Changed |= EnforceAny(W);
682
683 // An actual vector type cannot have 0 elements, so we can treat scalars
684 // as zero-length vectors. This way both vectors and scalars can be
685 // processed identically.
686 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
687 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
688 };
689
690 for (unsigned M : union_modes(V, W)) {
691 TypeSetByHwMode::SetType &VS = V.get(M);
692 TypeSetByHwMode::SetType &WS = W.get(M);
693
694 SmallSet<unsigned,2> VN, WN;
695 for (MVT T : VS)
696 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
697 for (MVT T : WS)
698 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
699
700 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
701 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
702 }
703 return Changed;
704}
705
706/// 1. Ensure that for each type T in A, there exists a type U in B,
707/// such that T and U have equal size in bits.
708/// 2. Ensure that for each type U in B, there exists a type T in A
709/// such that T and U have equal size in bits (reverse of 1).
710bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000711 ValidateOnExit _1(A, *this), _2(B, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000712 if (TP.hasError())
713 return false;
714 bool Changed = false;
715 if (A.empty())
716 Changed |= EnforceAny(A);
717 if (B.empty())
718 Changed |= EnforceAny(B);
719
720 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
721 return !Sizes.count(T.getSizeInBits());
722 };
723
724 for (unsigned M : union_modes(A, B)) {
725 TypeSetByHwMode::SetType &AS = A.get(M);
726 TypeSetByHwMode::SetType &BS = B.get(M);
727 SmallSet<unsigned,2> AN, BN;
728
729 for (MVT T : AS)
730 AN.insert(T.getSizeInBits());
731 for (MVT T : BS)
732 BN.insert(T.getSizeInBits());
733
734 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
735 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
736 }
737
738 return Changed;
739}
740
741void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000742 ValidateOnExit _1(VTS, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000743 TypeSetByHwMode Legal = getLegalTypes();
744 bool HaveLegalDef = Legal.hasDefault();
745
746 for (auto &I : VTS) {
747 unsigned M = I.first;
748 if (!Legal.hasMode(M) && !HaveLegalDef) {
749 TP.error("Invalid mode " + Twine(M));
750 return;
751 }
752 expandOverloads(I.second, Legal.get(M));
Scott Michel94420742008-03-05 17:49:05 +0000753 }
754}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000755
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000756void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
757 const TypeSetByHwMode::SetType &Legal) {
758 std::set<MVT> Ovs;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000759 for (MVT T : Out) {
760 if (!T.isOverloaded())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000761 continue;
Zachary Turner249dc142017-09-20 18:01:40 +0000762
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000763 Ovs.insert(T);
764 // MachineValueTypeSet allows iteration and erasing.
765 Out.erase(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000766 }
767
768 for (MVT Ov : Ovs) {
769 switch (Ov.SimpleTy) {
770 case MVT::iPTRAny:
771 Out.insert(MVT::iPTR);
772 return;
773 case MVT::iAny:
774 for (MVT T : MVT::integer_valuetypes())
775 if (Legal.count(T))
776 Out.insert(T);
777 for (MVT T : MVT::integer_vector_valuetypes())
778 if (Legal.count(T))
779 Out.insert(T);
780 return;
781 case MVT::fAny:
782 for (MVT T : MVT::fp_valuetypes())
783 if (Legal.count(T))
784 Out.insert(T);
785 for (MVT T : MVT::fp_vector_valuetypes())
786 if (Legal.count(T))
787 Out.insert(T);
788 return;
789 case MVT::vAny:
790 for (MVT T : MVT::vector_valuetypes())
791 if (Legal.count(T))
792 Out.insert(T);
793 return;
794 case MVT::Any:
795 for (MVT T : MVT::all_valuetypes())
796 if (Legal.count(T))
797 Out.insert(T);
798 return;
799 default:
800 break;
801 }
802 }
803}
804
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000805TypeSetByHwMode TypeInfer::getLegalTypes() {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000806 if (!LegalTypesCached) {
807 // Stuff all types from all modes into the default mode.
808 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
809 for (const auto &I : LTS)
810 LegalCache.insert(I.second);
811 LegalTypesCached = true;
812 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000813 TypeSetByHwMode VTS;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000814 VTS.getOrCreate(DefaultMode) = LegalCache;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000815 return VTS;
816}
Chris Lattner514e2922011-04-17 21:38:24 +0000817
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000818#ifndef NDEBUG
819TypeInfer::ValidateOnExit::~ValidateOnExit() {
Ulrich Weigand22b1af82018-07-13 16:42:15 +0000820 if (Infer.Validate && !VTS.validate()) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000821 dbgs() << "Type set is empty for each HW mode:\n"
822 "possible type contradiction in the pattern below "
823 "(use -print-records with llvm-tblgen to see all "
824 "expanded records).\n";
825 Infer.TP.dump();
826 llvm_unreachable(nullptr);
827 }
828}
829#endif
830
Chris Lattner514e2922011-04-17 21:38:24 +0000831//===----------------------------------------------------------------------===//
832// TreePredicateFn Implementation
833//===----------------------------------------------------------------------===//
834
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000835/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
836TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000837 assert(
838 (!hasPredCode() || !hasImmCode()) &&
839 ".td file corrupt: can't have a node predicate *and* an imm predicate");
840}
841
842bool TreePredicateFn::hasPredCode() const {
Daniel Sanders87d196c2017-11-13 22:26:13 +0000843 return isLoad() || isStore() || isAtomic() ||
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000844 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000845}
846
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000847std::string TreePredicateFn::getPredCode() const {
848 std::string Code = "";
849
Daniel Sanders87d196c2017-11-13 22:26:13 +0000850 if (!isLoad() && !isStore() && !isAtomic()) {
851 Record *MemoryVT = getMemoryVT();
852
853 if (MemoryVT)
854 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
855 "MemoryVT requires IsLoad or IsStore");
856 }
857
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000858 if (!isLoad() && !isStore()) {
859 if (isUnindexed())
860 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
861 "IsUnindexed requires IsLoad or IsStore");
862
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000863 Record *ScalarMemoryVT = getScalarMemoryVT();
864
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000865 if (ScalarMemoryVT)
866 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
867 "ScalarMemoryVT requires IsLoad or IsStore");
868 }
869
Daniel Sanders87d196c2017-11-13 22:26:13 +0000870 if (isLoad() + isStore() + isAtomic() > 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000871 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
Daniel Sanders87d196c2017-11-13 22:26:13 +0000872 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000873
874 if (isLoad()) {
875 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
876 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
877 getScalarMemoryVT() == nullptr)
878 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
879 "IsLoad cannot be used by itself");
880 } else {
881 if (isNonExtLoad())
882 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
883 "IsNonExtLoad requires IsLoad");
884 if (isAnyExtLoad())
885 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
886 "IsAnyExtLoad requires IsLoad");
887 if (isSignExtLoad())
888 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
889 "IsSignExtLoad requires IsLoad");
890 if (isZeroExtLoad())
891 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
892 "IsZeroExtLoad requires IsLoad");
893 }
894
895 if (isStore()) {
896 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
897 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
898 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
899 "IsStore cannot be used by itself");
900 } else {
901 if (isNonTruncStore())
902 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
903 "IsNonTruncStore requires IsStore");
904 if (isTruncStore())
905 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
906 "IsTruncStore requires IsStore");
907 }
908
Daniel Sanders87d196c2017-11-13 22:26:13 +0000909 if (isAtomic()) {
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000910 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
911 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
912 !isAtomicOrderingAcquireRelease() &&
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000913 !isAtomicOrderingSequentiallyConsistent() &&
914 !isAtomicOrderingAcquireOrStronger() &&
915 !isAtomicOrderingReleaseOrStronger() &&
916 !isAtomicOrderingWeakerThanAcquire() &&
917 !isAtomicOrderingWeakerThanRelease())
Daniel Sanders87d196c2017-11-13 22:26:13 +0000918 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
919 "IsAtomic cannot be used by itself");
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000920 } else {
921 if (isAtomicOrderingMonotonic())
922 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
923 "IsAtomicOrderingMonotonic requires IsAtomic");
924 if (isAtomicOrderingAcquire())
925 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
926 "IsAtomicOrderingAcquire requires IsAtomic");
927 if (isAtomicOrderingRelease())
928 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
929 "IsAtomicOrderingRelease requires IsAtomic");
930 if (isAtomicOrderingAcquireRelease())
931 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
932 "IsAtomicOrderingAcquireRelease requires IsAtomic");
933 if (isAtomicOrderingSequentiallyConsistent())
934 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
935 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000936 if (isAtomicOrderingAcquireOrStronger())
937 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
938 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
939 if (isAtomicOrderingReleaseOrStronger())
940 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
941 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
942 if (isAtomicOrderingWeakerThanAcquire())
943 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
944 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
Daniel Sanders87d196c2017-11-13 22:26:13 +0000945 }
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000946
Daniel Sanders87d196c2017-11-13 22:26:13 +0000947 if (isLoad() || isStore() || isAtomic()) {
948 StringRef SDNodeName =
949 isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
950
951 Record *MemoryVT = getMemoryVT();
952
953 if (MemoryVT)
954 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
955 MemoryVT->getName() + ") return false;\n")
956 .str();
957 }
958
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000959 if (isAtomic() && isAtomicOrderingMonotonic())
960 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
961 "AtomicOrdering::Monotonic) return false;\n";
962 if (isAtomic() && isAtomicOrderingAcquire())
963 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
964 "AtomicOrdering::Acquire) return false;\n";
965 if (isAtomic() && isAtomicOrderingRelease())
966 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
967 "AtomicOrdering::Release) return false;\n";
968 if (isAtomic() && isAtomicOrderingAcquireRelease())
969 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
970 "AtomicOrdering::AcquireRelease) return false;\n";
971 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
972 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
973 "AtomicOrdering::SequentiallyConsistent) return false;\n";
974
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000975 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
976 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
977 "return false;\n";
978 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
979 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
980 "return false;\n";
981
982 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
983 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
984 "return false;\n";
985 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
986 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
987 "return false;\n";
988
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000989 if (isLoad() || isStore()) {
990 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
991
992 if (isUnindexed())
993 Code += ("if (cast<" + SDNodeName +
994 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
995 "return false;\n")
996 .str();
997
998 if (isLoad()) {
999 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1000 isZeroExtLoad()) > 1)
1001 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1002 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1003 "IsZeroExtLoad are mutually exclusive");
1004 if (isNonExtLoad())
1005 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1006 "ISD::NON_EXTLOAD) return false;\n";
1007 if (isAnyExtLoad())
1008 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1009 "return false;\n";
1010 if (isSignExtLoad())
1011 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1012 "return false;\n";
1013 if (isZeroExtLoad())
1014 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1015 "return false;\n";
1016 } else {
1017 if ((isNonTruncStore() + isTruncStore()) > 1)
1018 PrintFatalError(
1019 getOrigPatFragRecord()->getRecord()->getLoc(),
1020 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1021 if (isNonTruncStore())
1022 Code +=
1023 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1024 if (isTruncStore())
1025 Code +=
1026 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1027 }
1028
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001029 Record *ScalarMemoryVT = getScalarMemoryVT();
1030
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001031 if (ScalarMemoryVT)
1032 Code += ("if (cast<" + SDNodeName +
1033 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1034 ScalarMemoryVT->getName() + ") return false;\n")
1035 .str();
1036 }
1037
1038 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1039
1040 Code += PredicateCode;
1041
1042 if (PredicateCode.empty() && !Code.empty())
1043 Code += "return true;\n";
1044
1045 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +00001046}
1047
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001048bool TreePredicateFn::hasImmCode() const {
1049 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1050}
1051
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001052std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00001053 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001054}
1055
Daniel Sanders649c5852017-10-13 20:42:18 +00001056bool TreePredicateFn::immCodeUsesAPInt() const {
1057 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1058}
1059
1060bool TreePredicateFn::immCodeUsesAPFloat() const {
1061 bool Unset;
1062 // The return value will be false when IsAPFloat is unset.
1063 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1064 Unset);
1065}
1066
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001067bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1068 bool Value) const {
1069 bool Unset;
1070 bool Result =
1071 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1072 if (Unset)
1073 return false;
1074 return Result == Value;
1075}
1076bool TreePredicateFn::isLoad() const {
1077 return isPredefinedPredicateEqualTo("IsLoad", true);
1078}
1079bool TreePredicateFn::isStore() const {
1080 return isPredefinedPredicateEqualTo("IsStore", true);
1081}
Daniel Sanders87d196c2017-11-13 22:26:13 +00001082bool TreePredicateFn::isAtomic() const {
1083 return isPredefinedPredicateEqualTo("IsAtomic", true);
1084}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001085bool TreePredicateFn::isUnindexed() const {
1086 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1087}
1088bool TreePredicateFn::isNonExtLoad() const {
1089 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1090}
1091bool TreePredicateFn::isAnyExtLoad() const {
1092 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1093}
1094bool TreePredicateFn::isSignExtLoad() const {
1095 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1096}
1097bool TreePredicateFn::isZeroExtLoad() const {
1098 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1099}
1100bool TreePredicateFn::isNonTruncStore() const {
1101 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1102}
1103bool TreePredicateFn::isTruncStore() const {
1104 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1105}
Daniel Sanders6d9d30a2017-11-13 23:03:47 +00001106bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1107 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1108}
1109bool TreePredicateFn::isAtomicOrderingAcquire() const {
1110 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1111}
1112bool TreePredicateFn::isAtomicOrderingRelease() const {
1113 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1114}
1115bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1116 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1117}
1118bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1119 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1120 true);
1121}
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001122bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1123 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1124}
1125bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1126 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1127}
1128bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1129 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1130}
1131bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1132 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1133}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001134Record *TreePredicateFn::getMemoryVT() const {
1135 Record *R = getOrigPatFragRecord()->getRecord();
1136 if (R->isValueUnset("MemoryVT"))
1137 return nullptr;
1138 return R->getValueAsDef("MemoryVT");
1139}
1140Record *TreePredicateFn::getScalarMemoryVT() const {
1141 Record *R = getOrigPatFragRecord()->getRecord();
1142 if (R->isValueUnset("ScalarMemoryVT"))
1143 return nullptr;
1144 return R->getValueAsDef("ScalarMemoryVT");
1145}
Daniel Sanders8ead1292018-06-15 23:13:43 +00001146bool TreePredicateFn::hasGISelPredicateCode() const {
1147 return !PatFragRec->getRecord()
1148 ->getValueAsString("GISelPredicateCode")
1149 .empty();
1150}
1151std::string TreePredicateFn::getGISelPredicateCode() const {
1152 return PatFragRec->getRecord()->getValueAsString("GISelPredicateCode");
1153}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001154
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001155StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001156 if (immCodeUsesAPInt())
1157 return "const APInt &";
1158 if (immCodeUsesAPFloat())
1159 return "const APFloat &";
1160 return "int64_t";
1161}
Chris Lattner514e2922011-04-17 21:38:24 +00001162
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001163StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001164 if (immCodeUsesAPInt())
1165 return "APInt";
1166 else if (immCodeUsesAPFloat())
1167 return "APFloat";
1168 return "I64";
1169}
1170
Chris Lattner514e2922011-04-17 21:38:24 +00001171/// isAlwaysTrue - Return true if this is a noop predicate.
1172bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001173 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001174}
1175
1176/// Return the name to use in the generated code to reference this, this is
1177/// "Predicate_foo" if from a pattern fragment "foo".
1178std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001179 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001180}
1181
1182/// getCodeToRunOnSDNode - Return the code for the function body that
1183/// evaluates this predicate. The argument is expected to be in "Node",
1184/// not N. This handles casting and conversion to a concrete node type as
1185/// appropriate.
1186std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001187 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001188 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001189 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001190 if (isLoad())
1191 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1192 "IsLoad cannot be used with ImmLeaf or its subclasses");
1193 if (isStore())
1194 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1195 "IsStore cannot be used with ImmLeaf or its subclasses");
1196 if (isUnindexed())
1197 PrintFatalError(
1198 getOrigPatFragRecord()->getRecord()->getLoc(),
1199 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1200 if (isNonExtLoad())
1201 PrintFatalError(
1202 getOrigPatFragRecord()->getRecord()->getLoc(),
1203 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1204 if (isAnyExtLoad())
1205 PrintFatalError(
1206 getOrigPatFragRecord()->getRecord()->getLoc(),
1207 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1208 if (isSignExtLoad())
1209 PrintFatalError(
1210 getOrigPatFragRecord()->getRecord()->getLoc(),
1211 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1212 if (isZeroExtLoad())
1213 PrintFatalError(
1214 getOrigPatFragRecord()->getRecord()->getLoc(),
1215 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1216 if (isNonTruncStore())
1217 PrintFatalError(
1218 getOrigPatFragRecord()->getRecord()->getLoc(),
1219 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1220 if (isTruncStore())
1221 PrintFatalError(
1222 getOrigPatFragRecord()->getRecord()->getLoc(),
1223 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1224 if (getMemoryVT())
1225 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1226 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1227 if (getScalarMemoryVT())
1228 PrintFatalError(
1229 getOrigPatFragRecord()->getRecord()->getLoc(),
1230 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1231
1232 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001233 if (immCodeUsesAPFloat())
1234 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1235 else if (immCodeUsesAPInt())
1236 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1237 else
1238 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001239 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001240 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001241
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001242 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001243 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001244 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +00001245 if (PatFragRec->getOnlyTree()->isLeaf())
1246 ClassName = "SDNode";
1247 else {
1248 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1249 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1250 }
1251 std::string Result;
1252 if (ClassName == "SDNode")
1253 Result = " SDNode *N = Node;\n";
1254 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001255 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001256
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001257 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +00001258}
1259
Chris Lattner8cab0212008-01-05 22:25:12 +00001260//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001261// PatternToMatch implementation
1262//
1263
Chris Lattner05925fe2010-03-29 01:40:38 +00001264/// getPatternSize - Return the 'size' of this pattern. We want to match large
1265/// patterns before small ones. This is used to determine the size of a
1266/// pattern.
Florian Hahn6b1db822018-06-14 20:32:58 +00001267static unsigned getPatternSize(const TreePatternNode *P,
Chris Lattner05925fe2010-03-29 01:40:38 +00001268 const CodeGenDAGPatterns &CGP) {
1269 unsigned Size = 3; // The node itself.
1270 // If the root node is a ConstantSDNode, increases its size.
1271 // e.g. (set R32:$dst, 0).
Florian Hahn6b1db822018-06-14 20:32:58 +00001272 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001273 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001274
Florian Hahn6b1db822018-06-14 20:32:58 +00001275 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001276 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001277 // We don't want to count any children twice, so return early.
1278 return Size;
1279 }
1280
Chris Lattner05925fe2010-03-29 01:40:38 +00001281 // If this node has some predicate function that must match, it adds to the
1282 // complexity of this node.
Florian Hahn6b1db822018-06-14 20:32:58 +00001283 if (!P->getPredicateFns().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001284 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001285
Chris Lattner05925fe2010-03-29 01:40:38 +00001286 // Count children in the count if they are also nodes.
Florian Hahn6b1db822018-06-14 20:32:58 +00001287 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1288 const TreePatternNode *Child = P->getChild(i);
1289 if (!Child->isLeaf() && Child->getNumTypes()) {
Simon Pilgrimc3c14412018-08-15 20:41:19 +00001290 const TypeSetByHwMode &T0 = Child->getExtType(0);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001291 // At this point, all variable type sets should be simple, i.e. only
1292 // have a default mode.
1293 if (T0.getMachineValueType() != MVT::Other) {
1294 Size += getPatternSize(Child, CGP);
1295 continue;
1296 }
1297 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001298 if (Child->isLeaf()) {
1299 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001300 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Florian Hahn6b1db822018-06-14 20:32:58 +00001301 else if (Child->getComplexPatternInfo(CGP))
Chris Lattner05925fe2010-03-29 01:40:38 +00001302 Size += getPatternSize(Child, CGP);
Florian Hahn6b1db822018-06-14 20:32:58 +00001303 else if (!Child->getPredicateFns().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001304 ++Size;
1305 }
1306 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001307
Chris Lattner05925fe2010-03-29 01:40:38 +00001308 return Size;
1309}
1310
1311/// Compute the complexity metric for the input pattern. This roughly
1312/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001313int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001314getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001315 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
Chris Lattner05925fe2010-03-29 01:40:38 +00001316}
1317
Dan Gohman49e19e92008-08-22 00:20:26 +00001318/// getPredicateCheck - Return a single string containing all of this
1319/// pattern's predicates concatenated with "&&" operators.
1320///
1321std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001322 SmallVector<const Predicate*,4> PredList;
1323 for (const Predicate &P : Predicates)
1324 PredList.push_back(&P);
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00001325 llvm::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +00001326
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001327 std::string Check;
1328 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1329 if (i != 0)
1330 Check += " && ";
1331 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001332 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001333 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001334}
1335
1336//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001337// SDTypeConstraint implementation
1338//
1339
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001340SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001341 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001342
Chris Lattner8cab0212008-01-05 22:25:12 +00001343 if (R->isSubClassOf("SDTCisVT")) {
1344 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001345 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1346 for (const auto &P : VVT)
1347 if (P.second == MVT::isVoid)
1348 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001349 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1350 ConstraintType = SDTCisPtrTy;
1351 } else if (R->isSubClassOf("SDTCisInt")) {
1352 ConstraintType = SDTCisInt;
1353 } else if (R->isSubClassOf("SDTCisFP")) {
1354 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001355 } else if (R->isSubClassOf("SDTCisVec")) {
1356 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001357 } else if (R->isSubClassOf("SDTCisSameAs")) {
1358 ConstraintType = SDTCisSameAs;
1359 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1360 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1361 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001362 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001363 R->getValueAsInt("OtherOperandNum");
1364 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1365 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001366 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001367 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001368 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1369 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001370 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001371 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1372 ConstraintType = SDTCisSubVecOfVec;
1373 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1374 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001375 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1376 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001377 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1378 for (const auto &P : VVT) {
1379 MVT T = P.second;
1380 if (T.isVector())
1381 PrintFatalError(R->getLoc(),
1382 "Cannot use vector type as SDTCVecEltisVT");
1383 if (!T.isInteger() && !T.isFloatingPoint())
1384 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1385 "as SDTCVecEltisVT");
1386 }
Craig Topper0be34582015-03-05 07:11:34 +00001387 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1388 ConstraintType = SDTCisSameNumEltsAs;
1389 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1390 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001391 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1392 ConstraintType = SDTCisSameSizeAs;
1393 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1394 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001395 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001396 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001397 }
1398}
1399
1400/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001401/// N, and the result number in ResNo.
Florian Hahn6b1db822018-06-14 20:32:58 +00001402static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
Chris Lattner2db7aba2010-03-19 21:56:21 +00001403 const SDNodeInfo &NodeInfo,
1404 unsigned &ResNo) {
1405 unsigned NumResults = NodeInfo.getNumResults();
1406 if (OpNo < NumResults) {
1407 ResNo = OpNo;
1408 return N;
1409 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001410
Chris Lattner2db7aba2010-03-19 21:56:21 +00001411 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001412
Florian Hahn6b1db822018-06-14 20:32:58 +00001413 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001414 std::string S;
1415 raw_string_ostream OS(S);
1416 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001417 << (OpNo+NumResults) << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001418 N->print(OS);
James Y Knighte452e272015-05-11 22:17:13 +00001419 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001420 }
1421
Florian Hahn6b1db822018-06-14 20:32:58 +00001422 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001423}
1424
1425/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1426/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001427/// change, false otherwise. If a type contradiction is found, flag an error.
Florian Hahn6b1db822018-06-14 20:32:58 +00001428bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
Chris Lattner8cab0212008-01-05 22:25:12 +00001429 const SDNodeInfo &NodeInfo,
1430 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001431 if (TP.hasError())
1432 return false;
1433
Chris Lattner2db7aba2010-03-19 21:56:21 +00001434 unsigned ResNo = 0; // The result number being referenced.
Florian Hahn6b1db822018-06-14 20:32:58 +00001435 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001436 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001437
Chris Lattner8cab0212008-01-05 22:25:12 +00001438 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001439 case SDTCisVT:
1440 // Operand must be a particular type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001441 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001442 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001443 // Operand must be same as target pointer type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001444 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001445 case SDTCisInt:
1446 // Require it to be one of the legal integer VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001447 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001448 case SDTCisFP:
1449 // Require it to be one of the legal fp VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001450 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001451 case SDTCisVec:
1452 // Require it to be one of the legal vector VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001453 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001454 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001455 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001456 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001457 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001458 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1459 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001460 }
1461 case SDTCisVTSmallerThanOp: {
1462 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1463 // have an integer type that is smaller than the VT.
Florian Hahn6b1db822018-06-14 20:32:58 +00001464 if (!NodeToApply->isLeaf() ||
1465 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1466 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001467 ->isSubClassOf("ValueType")) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001468 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001469 return false;
1470 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001471 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001472 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1473 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1474 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001475
Chris Lattner2db7aba2010-03-19 21:56:21 +00001476 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001477 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001478 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1479 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001480
Florian Hahn6b1db822018-06-14 20:32:58 +00001481 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001482 }
1483 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001484 unsigned BResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001485 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001486 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1487 BResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001488 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1489 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001490 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001491 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001492 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001493 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001494 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1495 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001496 // Filter vector types out of VecOperand that don't have the right element
1497 // type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001498 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1499 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001500 }
David Greene127fd1d2011-01-24 20:53:18 +00001501 case SDTCisSubVecOfVec: {
1502 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001503 TreePatternNode *BigVecOperand =
David Greene127fd1d2011-01-24 20:53:18 +00001504 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1505 VResNo);
1506
1507 // Filter vector types out of BigVecOperand that don't have the
1508 // right subvector type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001509 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1510 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001511 }
Craig Topper0be34582015-03-05 07:11:34 +00001512 case SDTCVecEltisVT: {
Florian Hahn6b1db822018-06-14 20:32:58 +00001513 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001514 }
1515 case SDTCisSameNumEltsAs: {
1516 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001517 TreePatternNode *OtherNode =
Craig Topper0be34582015-03-05 07:11:34 +00001518 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1519 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001520 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1521 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001522 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001523 case SDTCisSameSizeAs: {
1524 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001525 TreePatternNode *OtherNode =
Craig Topper9a44b3f2015-11-26 07:02:18 +00001526 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1527 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001528 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1529 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001530 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001531 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001532 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001533}
1534
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001535// Update the node type to match an instruction operand or result as specified
1536// in the ins or outs lists on the instruction definition. Return true if the
1537// type was actually changed.
1538bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1539 Record *Operand,
1540 TreePattern &TP) {
1541 // The 'unknown' operand indicates that types should be inferred from the
1542 // context.
1543 if (Operand->isSubClassOf("unknown_class"))
1544 return false;
1545
1546 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001547 if (Operand->isSubClassOf("Operand")) {
1548 Record *R = Operand->getValueAsDef("Type");
1549 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1550 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1551 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001552
1553 // PointerLikeRegClass has a type that is determined at runtime.
1554 if (Operand->isSubClassOf("PointerLikeRegClass"))
1555 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1556
1557 // Both RegisterClass and RegisterOperand operands derive their types from a
1558 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001559 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001560 if (Operand->isSubClassOf("RegisterClass"))
1561 RC = Operand;
1562 else if (Operand->isSubClassOf("RegisterOperand"))
1563 RC = Operand->getValueAsDef("RegClass");
1564
1565 assert(RC && "Unknown operand type");
1566 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1567 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1568}
1569
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001570bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1571 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1572 if (!TP.getInfer().isConcrete(Types[i], true))
1573 return true;
1574 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001575 if (getChild(i)->ContainsUnresolvedType(TP))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001576 return true;
1577 return false;
1578}
1579
1580bool TreePatternNode::hasProperTypeByHwMode() const {
1581 for (const TypeSetByHwMode &S : Types)
1582 if (!S.isDefaultOnly())
1583 return true;
Florian Hahn75e87c32018-05-30 21:00:18 +00001584 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001585 if (C->hasProperTypeByHwMode())
1586 return true;
1587 return false;
1588}
1589
1590bool TreePatternNode::hasPossibleType() const {
1591 for (const TypeSetByHwMode &S : Types)
1592 if (!S.isPossible())
1593 return false;
Florian Hahn75e87c32018-05-30 21:00:18 +00001594 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001595 if (!C->hasPossibleType())
1596 return false;
1597 return true;
1598}
1599
1600bool TreePatternNode::setDefaultMode(unsigned Mode) {
1601 for (TypeSetByHwMode &S : Types) {
1602 S.makeSimple(Mode);
1603 // Check if the selected mode had a type conflict.
1604 if (S.get(DefaultMode).empty())
1605 return false;
1606 }
Florian Hahn75e87c32018-05-30 21:00:18 +00001607 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001608 if (!C->setDefaultMode(Mode))
1609 return false;
1610 return true;
1611}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001612
Chris Lattner8cab0212008-01-05 22:25:12 +00001613//===----------------------------------------------------------------------===//
1614// SDNodeInfo implementation
1615//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001616SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001617 EnumName = R->getValueAsString("Opcode");
1618 SDClassName = R->getValueAsString("SDClass");
1619 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1620 NumResults = TypeProfile->getValueAsInt("NumResults");
1621 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001622
Chris Lattner8cab0212008-01-05 22:25:12 +00001623 // Parse the properties.
Matt Arsenault303327d2017-12-20 19:36:28 +00001624 Properties = parseSDPatternOperatorProperties(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001625
Chris Lattner8cab0212008-01-05 22:25:12 +00001626 // Parse the type constraints.
1627 std::vector<Record*> ConstraintList =
1628 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001629 for (Record *R : ConstraintList)
1630 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001631}
1632
Chris Lattner99e53b32010-02-28 00:22:30 +00001633/// getKnownType - If the type constraints on this node imply a fixed type
1634/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001635/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001636MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001637 unsigned NumResults = getNumResults();
1638 assert(NumResults <= 1 &&
1639 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001640 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001641
Craig Topper306cb122015-11-22 20:46:24 +00001642 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001643 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001644 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001645 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001646
Craig Topper306cb122015-11-22 20:46:24 +00001647 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001648 default: break;
1649 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001650 if (Constraint.VVT.isSimple())
1651 return Constraint.VVT.getSimple().SimpleTy;
1652 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001653 case SDTypeConstraint::SDTCisPtrTy:
1654 return MVT::iPTR;
1655 }
1656 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001657 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001658}
1659
Chris Lattner8cab0212008-01-05 22:25:12 +00001660//===----------------------------------------------------------------------===//
1661// TreePatternNode implementation
1662//
1663
Chris Lattnerf1447252010-03-19 21:37:09 +00001664static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1665 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001666 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001667 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001668
Chris Lattner2109cb42010-03-22 20:56:36 +00001669 if (Operator->isSubClassOf("Intrinsic"))
1670 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001671
Chris Lattnerf1447252010-03-19 21:37:09 +00001672 if (Operator->isSubClassOf("SDNode"))
1673 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001674
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001675 if (Operator->isSubClassOf("PatFrags")) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001676 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1677 // the forward reference case where one pattern fragment references another
1678 // before it is processed.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001679 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1680 // The number of results of a fragment with alternative records is the
1681 // maximum number of results across all alternatives.
1682 unsigned NumResults = 0;
1683 for (auto T : PFRec->getTrees())
1684 NumResults = std::max(NumResults, T->getNumTypes());
1685 return NumResults;
1686 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001687
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001688 ListInit *LI = Operator->getValueAsListInit("Fragments");
1689 assert(LI && "Invalid Fragment");
1690 unsigned NumResults = 0;
1691 for (Init *I : LI->getValues()) {
1692 Record *Op = nullptr;
1693 if (DagInit *Dag = dyn_cast<DagInit>(I))
1694 if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1695 Op = DI->getDef();
1696 assert(Op && "Invalid Fragment");
1697 NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1698 }
1699 return NumResults;
Chris Lattnerf1447252010-03-19 21:37:09 +00001700 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001701
Chris Lattnerf1447252010-03-19 21:37:09 +00001702 if (Operator->isSubClassOf("Instruction")) {
1703 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001704
Craig Topper3a8eb892015-03-20 05:09:06 +00001705 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1706
1707 // Subtract any defaulted outputs.
1708 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1709 Record *OperandNode = InstInfo.Operands[i].Rec;
1710
1711 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1712 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1713 --NumDefsToAdd;
1714 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001715
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001716 // Add on one implicit def if it has a resolvable type.
1717 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1718 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001719 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001720 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001721
Chris Lattnerf1447252010-03-19 21:37:09 +00001722 if (Operator->isSubClassOf("SDNodeXForm"))
1723 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001724
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001725 if (Operator->isSubClassOf("ValueType"))
1726 return 1; // A type-cast of one result.
1727
Tim Northoverc807a172014-05-20 11:52:46 +00001728 if (Operator->isSubClassOf("ComplexPattern"))
1729 return 1;
1730
Matthias Braun8c209aa2017-01-28 02:02:38 +00001731 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001732 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001733}
1734
1735void TreePatternNode::print(raw_ostream &OS) const {
1736 if (isLeaf())
1737 OS << *getLeafValue();
1738 else
1739 OS << '(' << getOperator()->getName();
1740
Zachary Turner249dc142017-09-20 18:01:40 +00001741 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1742 OS << ':';
1743 getExtType(i).writeToStream(OS);
1744 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001745
1746 if (!isLeaf()) {
1747 if (getNumChildren() != 0) {
1748 OS << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001749 getChild(0)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001750 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1751 OS << ", ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001752 getChild(i)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001753 }
1754 }
1755 OS << ")";
1756 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001757
Craig Topper306cb122015-11-22 20:46:24 +00001758 for (const TreePredicateFn &Pred : PredicateFns)
1759 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001760 if (TransformFn)
1761 OS << "<<X:" << TransformFn->getName() << ">>";
1762 if (!getName().empty())
1763 OS << ":$" << getName();
1764
1765}
1766void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001767 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001768}
1769
Scott Michel94420742008-03-05 17:49:05 +00001770/// isIsomorphicTo - Return true if this node is recursively
1771/// isomorphic to the specified node. For this comparison, the node's
1772/// entire state is considered. The assigned name is ignored, since
1773/// nodes with differing names are considered isomorphic. However, if
1774/// the assigned name is present in the dependent variable set, then
1775/// the assigned name is considered significant and the node is
1776/// isomorphic if the names match.
Florian Hahn6b1db822018-06-14 20:32:58 +00001777bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
Scott Michel94420742008-03-05 17:49:05 +00001778 const MultipleUseVarSet &DepVars) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001779 if (N == this) return true;
1780 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1781 getPredicateFns() != N->getPredicateFns() ||
1782 getTransformFn() != N->getTransformFn())
Chris Lattner8cab0212008-01-05 22:25:12 +00001783 return false;
1784
1785 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001786 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001787 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001788 return ((DI->getDef() == NDI->getDef())
1789 && (DepVars.find(getName()) == DepVars.end()
Florian Hahn6b1db822018-06-14 20:32:58 +00001790 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001791 }
1792 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001793 return getLeafValue() == N->getLeafValue();
Chris Lattner8cab0212008-01-05 22:25:12 +00001794 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001795
Florian Hahn6b1db822018-06-14 20:32:58 +00001796 if (N->getOperator() != getOperator() ||
1797 N->getNumChildren() != getNumChildren()) return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001798 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001799 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001800 return false;
1801 return true;
1802}
1803
1804/// clone - Make a copy of this tree and all of its children.
1805///
Florian Hahn75e87c32018-05-30 21:00:18 +00001806TreePatternNodePtr TreePatternNode::clone() const {
1807 TreePatternNodePtr New;
Chris Lattner8cab0212008-01-05 22:25:12 +00001808 if (isLeaf()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001809 New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001810 } else {
Florian Hahn75e87c32018-05-30 21:00:18 +00001811 std::vector<TreePatternNodePtr> CChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00001812 CChildren.reserve(Children.size());
1813 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001814 CChildren.push_back(getChild(i)->clone());
Craig Topper26fc06352018-07-15 06:52:49 +00001815 New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
Florian Hahn75e87c32018-05-30 21:00:18 +00001816 getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001817 }
1818 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001819 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001820 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001821 New->setTransformFn(getTransformFn());
1822 return New;
1823}
1824
Chris Lattner53c39ba2010-02-14 22:22:58 +00001825/// RemoveAllTypes - Recursively strip all the types of this tree.
1826void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001827 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001828 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001829 if (isLeaf()) return;
1830 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001831 getChild(i)->RemoveAllTypes();
Chris Lattner53c39ba2010-02-14 22:22:58 +00001832}
1833
1834
Chris Lattner8cab0212008-01-05 22:25:12 +00001835/// SubstituteFormalArguments - Replace the formal arguments in this tree
1836/// with actual values specified by ArgMap.
Florian Hahn75e87c32018-05-30 21:00:18 +00001837void TreePatternNode::SubstituteFormalArguments(
1838 std::map<std::string, TreePatternNodePtr> &ArgMap) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001839 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001840
Chris Lattner8cab0212008-01-05 22:25:12 +00001841 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001842 TreePatternNode *Child = getChild(i);
1843 if (Child->isLeaf()) {
1844 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001845 // Note that, when substituting into an output pattern, Val might be an
1846 // UnsetInit.
1847 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1848 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001849 // We found a use of a formal argument, replace it with its value.
Florian Hahn6b1db822018-06-14 20:32:58 +00001850 TreePatternNodePtr NewChild = ArgMap[Child->getName()];
Dan Gohman6e979022008-10-15 06:17:21 +00001851 assert(NewChild && "Couldn't find formal argument!");
Florian Hahn6b1db822018-06-14 20:32:58 +00001852 assert((Child->getPredicateFns().empty() ||
1853 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
Dan Gohman6e979022008-10-15 06:17:21 +00001854 "Non-empty child predicate clobbered!");
Florian Hahn0a2e0b62018-06-14 11:56:19 +00001855 setChild(i, std::move(NewChild));
Chris Lattner8cab0212008-01-05 22:25:12 +00001856 }
1857 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00001858 getChild(i)->SubstituteFormalArguments(ArgMap);
Chris Lattner8cab0212008-01-05 22:25:12 +00001859 }
1860 }
1861}
1862
1863
1864/// InlinePatternFragments - If this pattern refers to any pattern
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001865/// fragments, return the set of inlined versions (this can be more than
1866/// one if a PatFrags record has multiple alternatives).
1867void TreePatternNode::InlinePatternFragments(
1868 TreePatternNodePtr T, TreePattern &TP,
1869 std::vector<TreePatternNodePtr> &OutAlternatives) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001870
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001871 if (TP.hasError())
1872 return;
1873
1874 if (isLeaf()) {
1875 OutAlternatives.push_back(T); // nothing to do.
1876 return;
1877 }
1878
Chris Lattner8cab0212008-01-05 22:25:12 +00001879 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001880
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001881 if (!Op->isSubClassOf("PatFrags")) {
1882 if (getNumChildren() == 0) {
1883 OutAlternatives.push_back(T);
1884 return;
1885 }
1886
1887 // Recursively inline children nodes.
1888 std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
1889 ChildAlternatives.resize(getNumChildren());
Dan Gohman6e979022008-10-15 06:17:21 +00001890 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001891 TreePatternNodePtr Child = getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001892 Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
1893 // If there are no alternatives for any child, there are no
1894 // alternatives for this expression as whole.
1895 if (ChildAlternatives[i].empty())
1896 return;
Dan Gohman6e979022008-10-15 06:17:21 +00001897
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001898 for (auto NewChild : ChildAlternatives[i])
1899 assert((Child->getPredicateFns().empty() ||
1900 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1901 "Non-empty child predicate clobbered!");
Dan Gohman6e979022008-10-15 06:17:21 +00001902 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001903
1904 // The end result is an all-pairs construction of the resultant pattern.
1905 std::vector<unsigned> Idxs;
1906 Idxs.resize(ChildAlternatives.size());
1907 bool NotDone;
1908 do {
1909 // Create the variant and add it to the output list.
1910 std::vector<TreePatternNodePtr> NewChildren;
1911 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
1912 NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
1913 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00001914 getOperator(), std::move(NewChildren), getNumTypes());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001915
1916 // Copy over properties.
1917 R->setName(getName());
1918 R->setPredicateFns(getPredicateFns());
1919 R->setTransformFn(getTransformFn());
1920 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
1921 R->setType(i, getExtType(i));
1922
1923 // Register alternative.
1924 OutAlternatives.push_back(R);
1925
1926 // Increment indices to the next permutation by incrementing the
1927 // indices from last index backward, e.g., generate the sequence
1928 // [0, 0], [0, 1], [1, 0], [1, 1].
1929 int IdxsIdx;
1930 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
1931 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
1932 Idxs[IdxsIdx] = 0;
1933 else
1934 break;
1935 }
1936 NotDone = (IdxsIdx >= 0);
1937 } while (NotDone);
1938
1939 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001940 }
1941
1942 // Otherwise, we found a reference to a fragment. First, look up its
1943 // TreePattern record.
1944 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001945
Chris Lattner8cab0212008-01-05 22:25:12 +00001946 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001947 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001948 TP.error("'" + Op->getName() + "' fragment requires " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001949 Twine(Frag->getNumArgs()) + " operands!");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001950 return;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001951 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001952
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001953 // Compute the map of formal to actual arguments.
1954 std::map<std::string, TreePatternNodePtr> ArgMap;
1955 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
1956 const TreePatternNodePtr &Child = getChildShared(i);
1957 ArgMap[Frag->getArgName(i)] = Child;
Chris Lattner8cab0212008-01-05 22:25:12 +00001958 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001959
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001960 // Loop over all fragment alternatives.
1961 for (auto Alternative : Frag->getTrees()) {
1962 TreePatternNodePtr FragTree = Alternative->clone();
Dan Gohman6e979022008-10-15 06:17:21 +00001963
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001964 TreePredicateFn PredFn(Frag);
1965 if (!PredFn.isAlwaysTrue())
1966 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001967
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001968 // Resolve formal arguments to their actual value.
1969 if (Frag->getNumArgs())
1970 FragTree->SubstituteFormalArguments(ArgMap);
1971
1972 // Transfer types. Note that the resolved alternative may have fewer
1973 // (but not more) results than the PatFrags node.
1974 FragTree->setName(getName());
1975 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
1976 FragTree->UpdateNodeType(i, getExtType(i), TP);
1977
1978 // Transfer in the old predicates.
1979 for (const TreePredicateFn &Pred : getPredicateFns())
1980 FragTree->addPredicateFn(Pred);
1981
1982 // The fragment we inlined could have recursive inlining that is needed. See
1983 // if there are any pattern fragments in it and inline them as needed.
1984 FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
1985 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001986}
1987
1988/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001989/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001990/// references from the register file information, for example.
1991///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001992/// When Unnamed is set, return the type of a DAG operand with no name, such as
1993/// the F8RC register class argument in:
1994///
1995/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1996///
1997/// When Unnamed is false, return the type of a named DAG operand such as the
1998/// GPR:$src operand above.
1999///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002000static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2001 bool NotRegisters,
2002 bool Unnamed,
2003 TreePattern &TP) {
2004 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2005
Owen Andersona84be6c2011-06-27 21:06:21 +00002006 // Check to see if this is a register operand.
2007 if (R->isSubClassOf("RegisterOperand")) {
2008 assert(ResNo == 0 && "Regoperand ref only has one result!");
2009 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002010 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00002011 Record *RegClass = R->getValueAsDef("RegClass");
2012 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002013 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00002014 }
2015
Chris Lattnercabe0372010-03-15 06:00:16 +00002016 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00002017 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002018 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002019 // An unnamed register class represents itself as an i32 immediate, for
2020 // example on a COPY_TO_REGCLASS instruction.
2021 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002022 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002023
2024 // In a named operand, the register class provides the possible set of
2025 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002026 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002027 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00002028 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002029 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00002030 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002031
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002032 if (R->isSubClassOf("PatFrags")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002033 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002034 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002035 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00002036 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002037
Chris Lattner6070ee22010-03-23 23:50:31 +00002038 if (R->isSubClassOf("Register")) {
2039 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002040 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002041 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002042 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002043 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00002044 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002045
2046 if (R->isSubClassOf("SubRegIndex")) {
2047 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002048 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002049 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002050
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002051 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002052 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002053 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2054 //
2055 // (sext_inreg GPR:$src, i16)
2056 // ~~~
2057 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002058 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002059 // With a name, the ValueType simply provides the type of the named
2060 // variable.
2061 //
2062 // (sext_inreg i32:$src, i16)
2063 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002064 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002065 return TypeSetByHwMode(); // Unknown.
2066 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2067 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002068 }
2069
2070 if (R->isSubClassOf("CondCode")) {
2071 assert(ResNo == 0 && "This node only has one result!");
2072 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002073 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00002074 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002075
Chris Lattner6070ee22010-03-23 23:50:31 +00002076 if (R->isSubClassOf("ComplexPattern")) {
2077 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002078 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002079 return TypeSetByHwMode(); // Unknown.
2080 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00002081 }
2082 if (R->isSubClassOf("PointerLikeRegClass")) {
2083 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002084 TypeSetByHwMode VTS(MVT::iPTR);
2085 TP.getInfer().expandOverloads(VTS);
2086 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00002087 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002088
Chris Lattner6070ee22010-03-23 23:50:31 +00002089 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2090 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002091 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002092 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002093 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002094
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002095 if (R->isSubClassOf("Operand")) {
2096 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2097 Record *T = R->getValueAsDef("Type");
2098 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2099 }
Tim Northoverc807a172014-05-20 11:52:46 +00002100
Chris Lattner8cab0212008-01-05 22:25:12 +00002101 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002102 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00002103}
2104
Chris Lattner89c65662008-01-06 05:36:50 +00002105
2106/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2107/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2108const CodeGenIntrinsic *TreePatternNode::
2109getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2110 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2111 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2112 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00002113 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002114
Florian Hahn6b1db822018-06-14 20:32:58 +00002115 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00002116 return &CDP.getIntrinsicInfo(IID);
2117}
2118
Chris Lattner53c39ba2010-02-14 22:22:58 +00002119/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2120/// return the ComplexPattern information, otherwise return null.
2121const ComplexPattern *
2122TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00002123 Record *Rec;
2124 if (isLeaf()) {
2125 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2126 if (!DI)
2127 return nullptr;
2128 Rec = DI->getDef();
2129 } else
2130 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002131
Tim Northoverc807a172014-05-20 11:52:46 +00002132 if (!Rec->isSubClassOf("ComplexPattern"))
2133 return nullptr;
2134 return &CGP.getComplexPattern(Rec);
2135}
2136
2137unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2138 // A ComplexPattern specifically declares how many results it fills in.
2139 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2140 return CP->getNumOperands();
2141
2142 // If MIOperandInfo is specified, that gives the count.
2143 if (isLeaf()) {
2144 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2145 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2146 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2147 if (MIOps->getNumArgs())
2148 return MIOps->getNumArgs();
2149 }
2150 }
2151
2152 // Otherwise there is just one result.
2153 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00002154}
2155
2156/// NodeHasProperty - Return true if this node has the specified property.
2157bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002158 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002159 if (isLeaf()) {
2160 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2161 return CP->hasProperty(Property);
Matt Arsenault303327d2017-12-20 19:36:28 +00002162
Chris Lattner53c39ba2010-02-14 22:22:58 +00002163 return false;
2164 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002165
Matt Arsenault303327d2017-12-20 19:36:28 +00002166 if (Property != SDNPHasChain) {
2167 // The chain proprety is already present on the different intrinsic node
2168 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2169 // on the intrinsic. Anything else is specific to the individual intrinsic.
2170 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2171 return Int->hasProperty(Property);
2172 }
2173
2174 if (!Operator->isSubClassOf("SDPatternOperator"))
2175 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002176
Chris Lattner53c39ba2010-02-14 22:22:58 +00002177 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2178}
2179
2180
2181
2182
2183/// TreeHasProperty - Return true if any node in this tree has the specified
2184/// property.
2185bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002186 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002187 if (NodeHasProperty(Property, CGP))
2188 return true;
2189 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002190 if (getChild(i)->TreeHasProperty(Property, CGP))
Chris Lattner53c39ba2010-02-14 22:22:58 +00002191 return true;
2192 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002193}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002194
Evan Cheng49bad4c2008-06-16 20:29:38 +00002195/// isCommutativeIntrinsic - Return true if the node corresponds to a
2196/// commutative intrinsic.
2197bool
2198TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2199 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2200 return Int->isCommutative;
2201 return false;
2202}
2203
Florian Hahn6b1db822018-06-14 20:32:58 +00002204static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2205 if (!N->isLeaf())
2206 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002207
Florian Hahn6b1db822018-06-14 20:32:58 +00002208 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
Matt Arsenaulteb492162014-11-02 23:46:51 +00002209 if (DI && DI->getDef()->isSubClassOf(Class))
2210 return true;
2211
2212 return false;
2213}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002214
2215static void emitTooManyOperandsError(TreePattern &TP,
2216 StringRef InstName,
2217 unsigned Expected,
2218 unsigned Actual) {
2219 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2220 " operands but expected only " + Twine(Expected) + "!");
2221}
2222
2223static void emitTooFewOperandsError(TreePattern &TP,
2224 StringRef InstName,
2225 unsigned Actual) {
2226 TP.error("Instruction '" + InstName +
2227 "' expects more than the provided " + Twine(Actual) + " operands!");
2228}
2229
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002230/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002231/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002232/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002233bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002234 if (TP.hasError())
2235 return false;
2236
Chris Lattnerab3242f2008-01-06 01:10:31 +00002237 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002238 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002239 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002240 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002241 bool MadeChange = false;
2242 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2243 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002244 NotRegisters,
2245 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002246 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002247 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002248
Sean Silvafb509ed2012-10-10 20:24:43 +00002249 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002250 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002251
Chris Lattnerf1447252010-03-19 21:37:09 +00002252 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002253 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002254
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002255 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002256 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002257
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002258 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2259 for (auto &P : VVT) {
2260 MVT::SimpleValueType VT = P.second.SimpleTy;
2261 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2262 continue;
2263 unsigned Size = MVT(VT).getSizeInBits();
2264 // Make sure that the value is representable for this type.
2265 if (Size >= 32)
2266 continue;
2267 // Check that the value doesn't use more bits than we have. It must
2268 // either be a sign- or zero-extended equivalent of the original.
2269 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2270 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2271 SignBitAndAbove == 1)
2272 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002273
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002274 TP.error("Integer value '" + Twine(II->getValue()) +
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002275 "' is out of range for type '" + getEnumName(VT) + "'!");
2276 break;
2277 }
2278 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002279 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002280
Chris Lattner8cab0212008-01-05 22:25:12 +00002281 return false;
2282 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002283
Chris Lattneree820ac2010-02-23 05:51:07 +00002284 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002285 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002286
Chris Lattner8cab0212008-01-05 22:25:12 +00002287 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002288 unsigned NumRetVTs = Int->IS.RetVTs.size();
2289 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002290
Bill Wendling91821472008-11-13 09:08:33 +00002291 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002292 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002293
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002294 if (getNumChildren() != NumParamVTs + 1) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002295 TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2296 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002297 return false;
2298 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002299
2300 // Apply type info to the intrinsic ID.
Florian Hahn6b1db822018-06-14 20:32:58 +00002301 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002302
Chris Lattnerf1447252010-03-19 21:37:09 +00002303 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002304 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002305
Chris Lattnerf1447252010-03-19 21:37:09 +00002306 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
Florian Hahn6b1db822018-06-14 20:32:58 +00002307 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2308 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002309 }
2310 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002311 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002312
Chris Lattneree820ac2010-02-23 05:51:07 +00002313 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002314 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002315
Chris Lattner135091b2010-03-28 08:48:47 +00002316 // Check that the number of operands is sane. Negative operands -> varargs.
2317 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002318 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002319 TP.error(getOperator()->getName() + " node requires exactly " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002320 Twine(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002321 return false;
2322 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002323
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002324 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002325 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002326 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2327 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002328 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002329 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002330
Chris Lattneree820ac2010-02-23 05:51:07 +00002331 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002332 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002333 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002334 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002335
Chris Lattnerd44966f2010-03-27 19:15:02 +00002336 bool MadeChange = false;
2337
2338 // Apply the result types to the node, these come from the things in the
2339 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002340 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2341 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002342 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2343 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002344
Chris Lattnerd44966f2010-03-27 19:15:02 +00002345 // If the instruction has implicit defs, we apply the first one as a result.
2346 // FIXME: This sucks, it should apply all implicit defs.
2347 if (!InstInfo.ImplicitDefs.empty()) {
2348 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002349
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002350 // FIXME: Generalize to multiple possible types and multiple possible
2351 // ImplicitDefs.
2352 MVT::SimpleValueType VT =
2353 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002354
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002355 if (VT != MVT::Other)
2356 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002357 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002358
Chris Lattnercabe0372010-03-15 06:00:16 +00002359 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2360 // be the same.
2361 if (getOperator()->getName() == "INSERT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00002362 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2363 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2364 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002365 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2366 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2367 // variadic.
2368
2369 unsigned NChild = getNumChildren();
2370 if (NChild < 3) {
2371 TP.error("REG_SEQUENCE requires at least 3 operands!");
2372 return false;
2373 }
2374
2375 if (NChild % 2 == 0) {
2376 TP.error("REG_SEQUENCE requires an odd number of operands!");
2377 return false;
2378 }
2379
2380 if (!isOperandClass(getChild(0), "RegisterClass")) {
2381 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2382 return false;
2383 }
2384
2385 for (unsigned I = 1; I < NChild; I += 2) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002386 TreePatternNode *SubIdxChild = getChild(I + 1);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002387 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2388 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002389 Twine(I + 1) + "!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00002390 return false;
2391 }
2392 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002393 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002394
2395 unsigned ChildNo = 0;
2396 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2397 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002398
Chris Lattner8cab0212008-01-05 22:25:12 +00002399 // If the instruction expects a predicate or optional def operand, we
2400 // codegen this by setting the operand to it's default value if it has a
2401 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002402 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002403 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2404 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002405
Chris Lattner8cab0212008-01-05 22:25:12 +00002406 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002407 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002408 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002409 return false;
2410 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002411
Florian Hahn6b1db822018-06-14 20:32:58 +00002412 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002413 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002414
2415 // If the operand has sub-operands, they may be provided by distinct
2416 // child patterns, so attempt to match each sub-operand separately.
2417 if (OperandNode->isSubClassOf("Operand")) {
2418 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2419 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2420 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002421 // a single ComplexPattern-related Operand.
2422
2423 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002424 // Match first sub-operand against the child we already have.
2425 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2426 MadeChange |=
2427 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2428
2429 // And the remaining sub-operands against subsequent children.
2430 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2431 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002432 emitTooFewOperandsError(TP, getOperator()->getName(),
2433 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002434 return false;
2435 }
Florian Hahn6b1db822018-06-14 20:32:58 +00002436 Child = getChild(ChildNo++);
Ulrich Weigande618abd2013-03-19 19:51:09 +00002437
2438 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2439 MadeChange |=
2440 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2441 }
2442 continue;
2443 }
2444 }
2445 }
2446
2447 // If we didn't match by pieces above, attempt to match the whole
2448 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002449 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002450 }
Christopher Lamba7312392008-03-11 09:33:47 +00002451
Matt Arsenaulteb492162014-11-02 23:46:51 +00002452 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002453 emitTooManyOperandsError(TP, getOperator()->getName(),
2454 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002455 return false;
2456 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002457
Ulrich Weigande618abd2013-03-19 19:51:09 +00002458 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002459 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002460 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002461 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002462
Tim Northoverc807a172014-05-20 11:52:46 +00002463 if (getOperator()->isSubClassOf("ComplexPattern")) {
2464 bool MadeChange = false;
2465
2466 for (unsigned i = 0; i < getNumChildren(); ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002467 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Tim Northoverc807a172014-05-20 11:52:46 +00002468
2469 return MadeChange;
2470 }
2471
Chris Lattneree820ac2010-02-23 05:51:07 +00002472 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002473
Chris Lattneree820ac2010-02-23 05:51:07 +00002474 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002475 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002476 TP.error("Node transform '" + getOperator()->getName() +
2477 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002478 return false;
2479 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002480
Florian Hahn6b1db822018-06-14 20:32:58 +00002481 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002482 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002483}
2484
2485/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2486/// RHS of a commutative operation, not the on LHS.
Florian Hahn6b1db822018-06-14 20:32:58 +00002487static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2488 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
Chris Lattner8cab0212008-01-05 22:25:12 +00002489 return true;
Florian Hahn6b1db822018-06-14 20:32:58 +00002490 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002491 return true;
2492 return false;
2493}
2494
2495
2496/// canPatternMatch - If it is impossible for this pattern to match on this
2497/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002498/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002499/// that can never possibly work), and to prevent the pattern permuter from
2500/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002501bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002502 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002503 if (isLeaf()) return true;
2504
2505 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002506 if (!getChild(i)->canPatternMatch(Reason, CDP))
Chris Lattner8cab0212008-01-05 22:25:12 +00002507 return false;
2508
2509 // If this is an intrinsic, handle cases that would make it not match. For
2510 // example, if an operand is required to be an immediate.
2511 if (getOperator()->isSubClassOf("Intrinsic")) {
2512 // TODO:
2513 return true;
2514 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002515
Tim Northoverc807a172014-05-20 11:52:46 +00002516 if (getOperator()->isSubClassOf("ComplexPattern"))
2517 return true;
2518
Chris Lattner8cab0212008-01-05 22:25:12 +00002519 // If this node is a commutative operator, check that the LHS isn't an
2520 // immediate.
2521 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002522 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2523 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002524 // Scan all of the operands of the node and make sure that only the last one
2525 // is a constant node, unless the RHS also is.
2526 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002527 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002528 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002529 if (OnlyOnRHSOfCommutative(getChild(i))) {
2530 Reason="Immediate value must be on the RHS of commutative operators!";
2531 return false;
2532 }
2533 }
2534 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002535
Chris Lattner8cab0212008-01-05 22:25:12 +00002536 return true;
2537}
2538
2539//===----------------------------------------------------------------------===//
2540// TreePattern implementation
2541//
2542
David Greeneaf8ee2c2011-07-29 22:43:06 +00002543TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002544 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002545 isInputPattern(isInput), HasError(false),
2546 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002547 for (Init *I : RawPat->getValues())
2548 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002549}
2550
David Greeneaf8ee2c2011-07-29 22:43:06 +00002551TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002552 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002553 isInputPattern(isInput), HasError(false),
2554 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002555 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002556}
2557
Florian Hahn75e87c32018-05-30 21:00:18 +00002558TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2559 CodeGenDAGPatterns &cdp)
2560 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2561 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002562 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002563}
2564
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002565void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002566 if (HasError)
2567 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002568 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002569 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2570 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002571}
2572
Chris Lattnercabe0372010-03-15 06:00:16 +00002573void TreePattern::ComputeNamedNodes() {
Florian Hahn6b1db822018-06-14 20:32:58 +00002574 for (TreePatternNodePtr &Tree : Trees)
2575 ComputeNamedNodes(Tree.get());
Chris Lattnercabe0372010-03-15 06:00:16 +00002576}
2577
Florian Hahn6b1db822018-06-14 20:32:58 +00002578void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002579 if (!N->getName().empty())
Florian Hahn6b1db822018-06-14 20:32:58 +00002580 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002581
Chris Lattnercabe0372010-03-15 06:00:16 +00002582 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002583 ComputeNamedNodes(N->getChild(i));
Chris Lattnercabe0372010-03-15 06:00:16 +00002584}
2585
Florian Hahn75e87c32018-05-30 21:00:18 +00002586TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2587 StringRef OpName) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002588 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002589 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002590
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002591 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002592 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002593 /// (foo GPR, imm) -> (foo GPR, (imm))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002594 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
David Greenee32ebf22011-07-29 19:07:07 +00002595 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002596 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002597 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002598 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002599
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002600 // Input argument?
Florian Hahn75e87c32018-05-30 21:00:18 +00002601 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002602 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002603 if (OpName.empty())
2604 error("'node' argument requires a name to match with operand list");
2605 Args.push_back(OpName);
2606 }
2607
2608 Res->setName(OpName);
2609 return Res;
2610 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002611
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002612 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002613 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002614 if (OpName.empty())
2615 error("'?' argument requires a name to match with operand list");
Florian Hahn75e87c32018-05-30 21:00:18 +00002616 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002617 Args.push_back(OpName);
2618 Res->setName(OpName);
2619 return Res;
2620 }
2621
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002622 if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002623 if (!OpName.empty())
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002624 error("Constant int or bit argument should not have a name!");
2625 if (isa<BitInit>(TheInit))
2626 TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2627 return std::make_shared<TreePatternNode>(TheInit, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002628 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002629
Sean Silvafb509ed2012-10-10 20:24:43 +00002630 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002631 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002632 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002633 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002634 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002635 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002636 }
2637
Sean Silvafb509ed2012-10-10 20:24:43 +00002638 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002639 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002640 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002641 error("Pattern has unexpected init kind!");
2642 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002643 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002644 if (!OpDef) error("Pattern has unexpected operator type!");
2645 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002646
Chris Lattner8cab0212008-01-05 22:25:12 +00002647 if (Operator->isSubClassOf("ValueType")) {
2648 // If the operator is a ValueType, then this must be "type cast" of a leaf
2649 // node.
2650 if (Dag->getNumArgs() != 1)
2651 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002652
Florian Hahn75e87c32018-05-30 21:00:18 +00002653 TreePatternNodePtr New =
2654 ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002655
Chris Lattner8cab0212008-01-05 22:25:12 +00002656 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002657 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002658 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2659 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002660
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002661 if (!OpName.empty())
2662 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002663 return New;
2664 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002665
Chris Lattner8cab0212008-01-05 22:25:12 +00002666 // Verify that this is something that makes sense for an operator.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002667 if (!Operator->isSubClassOf("PatFrags") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002668 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002669 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002670 !Operator->isSubClassOf("SDNodeXForm") &&
2671 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002672 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002673 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002674 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002675 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002676
Chris Lattner8cab0212008-01-05 22:25:12 +00002677 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002678 if (isInputPattern) {
2679 if (Operator->isSubClassOf("Instruction") ||
2680 Operator->isSubClassOf("SDNodeXForm"))
2681 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2682 } else {
2683 if (Operator->isSubClassOf("Intrinsic"))
2684 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002685
Chris Lattner2e9eae12010-03-28 06:57:56 +00002686 if (Operator->isSubClassOf("SDNode") &&
2687 Operator->getName() != "imm" &&
2688 Operator->getName() != "fpimm" &&
2689 Operator->getName() != "tglobaltlsaddr" &&
2690 Operator->getName() != "tconstpool" &&
2691 Operator->getName() != "tjumptable" &&
2692 Operator->getName() != "tframeindex" &&
2693 Operator->getName() != "texternalsym" &&
2694 Operator->getName() != "tblockaddress" &&
2695 Operator->getName() != "tglobaladdr" &&
2696 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002697 Operator->getName() != "vt" &&
2698 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002699 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2700 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002701
Florian Hahn75e87c32018-05-30 21:00:18 +00002702 std::vector<TreePatternNodePtr> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002703
2704 // Parse all the operands.
2705 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002706 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002707
Hal Finkel8b4bdfdb2018-01-03 11:35:09 +00002708 // Get the actual number of results before Operator is converted to an intrinsic
2709 // node (which is hard-coded to have either zero or one result).
2710 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2711
Fangrui Song956ee792018-03-30 22:22:31 +00002712 // If the operator is an intrinsic, then this is just syntactic sugar for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002713 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002714 // convert the intrinsic name to a number.
2715 if (Operator->isSubClassOf("Intrinsic")) {
2716 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2717 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2718
2719 // If this intrinsic returns void, it must have side-effects and thus a
2720 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002721 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002722 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002723 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002724 // Has side-effects, requires chain.
2725 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002726 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002727 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002728
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002729 Children.insert(Children.begin(),
2730 std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
Chris Lattner8cab0212008-01-05 22:25:12 +00002731 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002732
Tim Northoverc807a172014-05-20 11:52:46 +00002733 if (Operator->isSubClassOf("ComplexPattern")) {
2734 for (unsigned i = 0; i < Children.size(); ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002735 TreePatternNodePtr Child = Children[i];
Tim Northoverc807a172014-05-20 11:52:46 +00002736
2737 if (Child->getName().empty())
2738 error("All arguments to a ComplexPattern must be named");
2739
2740 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2741 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2742 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2743 auto OperandId = std::make_pair(Operator, i);
2744 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2745 if (PrevOp != ComplexPatternOperands.end()) {
2746 if (PrevOp->getValue() != OperandId)
2747 error("All ComplexPattern operands must appear consistently: "
2748 "in the same order in just one ComplexPattern instance.");
2749 } else
2750 ComplexPatternOperands[Child->getName()] = OperandId;
2751 }
2752 }
2753
Florian Hahn6b1db822018-06-14 20:32:58 +00002754 TreePatternNodePtr Result =
Craig Topper26fc06352018-07-15 06:52:49 +00002755 std::make_shared<TreePatternNode>(Operator, std::move(Children),
2756 NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002757 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002758
Matthias Braun7cf3b112016-12-05 06:00:41 +00002759 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002760 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002761 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002762 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002763 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002764}
2765
Chris Lattnera787c9e2010-03-28 08:38:32 +00002766/// SimplifyTree - See if we can simplify this tree to eliminate something that
2767/// will never match in favor of something obvious that will. This is here
2768/// strictly as a convenience to target authors because it allows them to write
2769/// more type generic things and have useless type casts fold away.
2770///
2771/// This returns true if any change is made.
Florian Hahn75e87c32018-05-30 21:00:18 +00002772static bool SimplifyTree(TreePatternNodePtr &N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002773 if (N->isLeaf())
2774 return false;
2775
2776 // If we have a bitconvert with a resolved type and if the source and
2777 // destination types are the same, then the bitconvert is useless, remove it.
2778 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002779 N->getExtType(0).isValueTypeByHwMode(false) &&
Florian Hahn6b1db822018-06-14 20:32:58 +00002780 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002781 N->getName().empty()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002782 N = N->getChildShared(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002783 SimplifyTree(N);
2784 return true;
2785 }
2786
2787 // Walk all children.
2788 bool MadeChange = false;
2789 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002790 TreePatternNodePtr Child = N->getChildShared(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002791 MadeChange |= SimplifyTree(Child);
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002792 N->setChild(i, std::move(Child));
Chris Lattnera787c9e2010-03-28 08:38:32 +00002793 }
2794 return MadeChange;
2795}
2796
2797
2798
Chris Lattner8cab0212008-01-05 22:25:12 +00002799/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002800/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002801/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002802bool TreePattern::
2803InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2804 if (NamedNodes.empty())
2805 ComputeNamedNodes();
2806
Chris Lattner8cab0212008-01-05 22:25:12 +00002807 bool MadeChange = true;
2808 while (MadeChange) {
2809 MadeChange = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002810 for (TreePatternNodePtr &Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002811 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2812 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002813 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002814
2815 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002816 for (auto &Entry : NamedNodes) {
2817 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002818
Chris Lattnercabe0372010-03-15 06:00:16 +00002819 // If we have input named node types, propagate their types to the named
2820 // values here.
2821 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002822 if (!InNamedTypes->count(Entry.getKey())) {
2823 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002824 "' in output pattern but not input pattern");
2825 return true;
2826 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002827
2828 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002829 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002830
2831 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002832 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002833 // If this node is a register class, and it is the root of the pattern
2834 // then we're mapping something onto an input register. We allow
2835 // changing the type of the input register in this case. This allows
2836 // us to match things like:
2837 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Florian Hahn75e87c32018-05-30 21:00:18 +00002838 if (Node == Trees[0].get() && Node->isLeaf()) {
Craig Topper306cb122015-11-22 20:46:24 +00002839 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002840 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2841 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002842 continue;
2843 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002844
Craig Topper306cb122015-11-22 20:46:24 +00002845 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002846 InNodes[0]->getNumTypes() == 1 &&
2847 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002848 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2849 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002850 }
2851 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002852
Chris Lattnercabe0372010-03-15 06:00:16 +00002853 // If there are multiple nodes with the same name, they must all have the
2854 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002855 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002856 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002857 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002858 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002859 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002860
Chris Lattnerf1447252010-03-19 21:37:09 +00002861 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2862 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002863 }
2864 }
2865 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002866 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002867
Chris Lattner8cab0212008-01-05 22:25:12 +00002868 bool HasUnresolvedTypes = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002869 for (const TreePatternNodePtr &Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002870 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002871 return !HasUnresolvedTypes;
2872}
2873
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002874void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002875 OS << getRecord()->getName();
2876 if (!Args.empty()) {
2877 OS << "(" << Args[0];
2878 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2879 OS << ", " << Args[i];
2880 OS << ")";
2881 }
2882 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002883
Chris Lattner8cab0212008-01-05 22:25:12 +00002884 if (Trees.size() > 1)
2885 OS << "[\n";
Florian Hahn75e87c32018-05-30 21:00:18 +00002886 for (const TreePatternNodePtr &Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002887 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002888 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002889 OS << "\n";
2890 }
2891
2892 if (Trees.size() > 1)
2893 OS << "]\n";
2894}
2895
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002896void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002897
2898//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002899// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002900//
2901
Daniel Sanders7e523672017-11-11 03:23:44 +00002902CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2903 PatternRewriterFn PatternRewriter)
2904 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2905 PatternRewriter(PatternRewriter) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002906
Justin Bogner92a8c612016-07-15 16:31:37 +00002907 Intrinsics = CodeGenIntrinsicTable(Records, false);
2908 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002909 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002910 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002911 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002912 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002913 ParseDefaultOperands();
2914 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002915 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002916 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002917
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002918 // Break patterns with parameterized types into a series of patterns,
2919 // where each one has a fixed type and is predicated on the conditions
2920 // of the associated HW mode.
2921 ExpandHwModeBasedTypes();
2922
Chris Lattner8cab0212008-01-05 22:25:12 +00002923 // Generate variants. For example, commutative patterns can match
2924 // multiple ways. Add them to PatternsToMatch as well.
2925 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002926
2927 // Infer instruction flags. For example, we can detect loads,
2928 // stores, and side effects in many cases by examining an
2929 // instruction's pattern.
2930 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002931
2932 // Verify that instruction flags match the patterns.
2933 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002934}
2935
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00002936Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002937 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002938 if (!N || !N->isSubClassOf("SDNode"))
2939 PrintFatalError("Error getting SDNode '" + Name + "'!");
2940
Chris Lattner8cab0212008-01-05 22:25:12 +00002941 return N;
2942}
2943
2944// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002945void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002946 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002947 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2948
Chris Lattner8cab0212008-01-05 22:25:12 +00002949 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002950 Record *R = Nodes.back();
2951 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002952 Nodes.pop_back();
2953 }
2954
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002955 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002956 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2957 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2958 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2959}
2960
2961/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2962/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002963void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002964 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2965 while (!Xforms.empty()) {
2966 Record *XFormNode = Xforms.back();
2967 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002968 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002969 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002970
2971 Xforms.pop_back();
2972 }
2973}
2974
Chris Lattnerab3242f2008-01-06 01:10:31 +00002975void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002976 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2977 while (!AMs.empty()) {
2978 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2979 AMs.pop_back();
2980 }
2981}
2982
2983
2984/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2985/// file, building up the PatternFragments map. After we've collected them all,
2986/// inline fragments together as necessary, so that there are no references left
2987/// inside a pattern fragment to a pattern fragment.
2988///
Hal Finkel2756dc12014-02-28 00:26:56 +00002989void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002990 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002991
Chris Lattnere7170df2008-01-05 22:43:57 +00002992 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002993 for (Record *Frag : Fragments) {
2994 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002995 continue;
2996
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002997 ListInit *LI = Frag->getValueAsListInit("Fragments");
Hal Finkel2756dc12014-02-28 00:26:56 +00002998 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002999 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003000 Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00003001 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003002
Chris Lattnere7170df2008-01-05 22:43:57 +00003003 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00003004 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00003005 // Copy the args so we can take StringRefs to them.
3006 auto ArgsCopy = Args;
3007 SmallDenseSet<StringRef, 4> OperandsSet;
3008 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003009
Chris Lattnere7170df2008-01-05 22:43:57 +00003010 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00003011 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003012
Chris Lattner8cab0212008-01-05 22:25:12 +00003013 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00003014 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00003015 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00003016 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003017 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00003018 if (!OpsOp ||
3019 (OpsOp->getDef()->getName() != "ops" &&
3020 OpsOp->getDef()->getName() != "outs" &&
3021 OpsOp->getDef()->getName() != "ins"))
3022 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003023
3024 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00003025 Args.clear();
3026 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003027 if (!isa<DefInit>(OpsList->getArg(j)) ||
3028 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00003029 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00003030 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00003031 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00003032 StringRef ArgNameStr = OpsList->getArgNameStr(j);
3033 if (!OperandsSet.count(ArgNameStr))
3034 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00003035 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00003036 OperandsSet.erase(ArgNameStr);
3037 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003038 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003039
Chris Lattnere7170df2008-01-05 22:43:57 +00003040 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003041 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00003042 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003043
Chris Lattnere7170df2008-01-05 22:43:57 +00003044 // If there is a code init for this fragment, keep track of the fact that
3045 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00003046 TreePredicateFn PredFn(P);
3047 if (!PredFn.isAlwaysTrue())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003048 for (auto T : P->getTrees())
3049 T->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003050
Chris Lattner8cab0212008-01-05 22:25:12 +00003051 // If there is a node transformation corresponding to this, keep track of
3052 // it.
Craig Topper306cb122015-11-22 20:46:24 +00003053 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00003054 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003055 for (auto T : P->getTrees())
3056 T->setTransformFn(Transform);
Chris Lattner8cab0212008-01-05 22:25:12 +00003057 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003058
Chris Lattner8cab0212008-01-05 22:25:12 +00003059 // Now that we've parsed all of the tree fragments, do a closure on them so
3060 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00003061 for (Record *Frag : Fragments) {
3062 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003063 continue;
3064
Craig Topper306cb122015-11-22 20:46:24 +00003065 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00003066 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003067
Chris Lattner8cab0212008-01-05 22:25:12 +00003068 // Infer as many types as possible. Don't worry about it if we don't infer
Ulrich Weigand22b1af82018-07-13 16:42:15 +00003069 // all of them, some may depend on the inputs of the pattern. Also, don't
3070 // validate type sets; validation may cause spurious failures e.g. if a
3071 // fragment needs floating-point types but the current target does not have
3072 // any (this is only an error if that fragment is ever used!).
3073 {
3074 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3075 ThePat.InferAllTypes();
3076 ThePat.resetError();
3077 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003078
Chris Lattner8cab0212008-01-05 22:25:12 +00003079 // If debugging, print out the pattern fragment result.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003080 LLVM_DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003081 }
3082}
3083
Chris Lattnerab3242f2008-01-06 01:10:31 +00003084void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00003085 std::vector<Record*> DefaultOps;
3086 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00003087
3088 // Find some SDNode.
3089 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00003090 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003091
Tom Stellardb7246a72012-09-06 14:15:52 +00003092 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3093 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003094
Tom Stellardb7246a72012-09-06 14:15:52 +00003095 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3096 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00003097 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00003098 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3099 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3100 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00003101 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003102
Tom Stellardb7246a72012-09-06 14:15:52 +00003103 // Create a TreePattern to parse this.
3104 TreePattern P(DefaultOps[i], DI, false, *this);
3105 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003106
Tom Stellardb7246a72012-09-06 14:15:52 +00003107 // Copy the operands over into a DAGDefaultOperand.
3108 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003109
Florian Hahn75e87c32018-05-30 21:00:18 +00003110 const TreePatternNodePtr &T = P.getTree(0);
Tom Stellardb7246a72012-09-06 14:15:52 +00003111 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
Florian Hahn75e87c32018-05-30 21:00:18 +00003112 TreePatternNodePtr TPN = T->getChildShared(op);
Tom Stellardb7246a72012-09-06 14:15:52 +00003113 while (TPN->ApplyTypeConstraints(P, false))
3114 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003115
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003116 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00003117 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3118 DefaultOps[i]->getName() +
3119 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003120 }
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003121 DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
Chris Lattner8cab0212008-01-05 22:25:12 +00003122 }
Tom Stellardb7246a72012-09-06 14:15:52 +00003123
3124 // Insert it into the DefaultOperands map so we can find it later.
3125 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00003126 }
3127}
3128
3129/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3130/// instruction input. Return true if this is a real use.
David Blaikie19b22d42018-06-11 22:14:43 +00003131static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003132 std::map<std::string, TreePatternNodePtr> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003133 // No name -> not interesting.
3134 if (Pat->getName().empty()) {
3135 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003136 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00003137 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3138 DI->getDef()->isSubClassOf("RegisterOperand")))
David Blaikie19b22d42018-06-11 22:14:43 +00003139 I.error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003140 }
3141 return false;
3142 }
3143
3144 Record *Rec;
3145 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003146 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
David Blaikie19b22d42018-06-11 22:14:43 +00003147 if (!DI)
3148 I.error("Input $" + Pat->getName() + " must be an identifier!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003149 Rec = DI->getDef();
3150 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003151 Rec = Pat->getOperator();
3152 }
3153
3154 // SRCVALUE nodes are ignored.
3155 if (Rec->getName() == "srcvalue")
3156 return false;
3157
Florian Hahn75e87c32018-05-30 21:00:18 +00003158 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
Chris Lattner8cab0212008-01-05 22:25:12 +00003159 if (!Slot) {
3160 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003161 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00003162 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003163 Record *SlotRec;
3164 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003165 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003166 } else {
3167 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3168 SlotRec = Slot->getOperator();
3169 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003170
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003171 // Ensure that the inputs agree if we've already seen this input.
3172 if (Rec != SlotRec)
David Blaikie19b22d42018-06-11 22:14:43 +00003173 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003174 // Ensure that the types can agree as well.
3175 Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3176 Pat->UpdateNodeType(0, Slot->getExtType(0), I);
Chris Lattnerf1447252010-03-19 21:37:09 +00003177 if (Slot->getExtTypes() != Pat->getExtTypes())
David Blaikie19b22d42018-06-11 22:14:43 +00003178 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003179 return true;
3180}
3181
3182/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3183/// part of "I", the instruction), computing the set of inputs and outputs of
3184/// the pattern. Report errors if we see anything naughty.
Florian Hahn75e87c32018-05-30 21:00:18 +00003185void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
Florian Hahn6b1db822018-06-14 20:32:58 +00003186 TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003187 std::map<std::string, TreePatternNodePtr> &InstInputs,
3188 std::map<std::string, TreePatternNodePtr> &InstResults,
3189 std::vector<Record *> &InstImpResults) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003190
3191 // The instruction pattern still has unresolved fragments. For *named*
3192 // nodes we must resolve those here. This may not result in multiple
3193 // alternatives.
3194 if (!Pat->getName().empty()) {
3195 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3196 SrcPattern.InlinePatternFragments();
3197 SrcPattern.InferAllTypes();
3198 Pat = SrcPattern.getOnlyTree();
3199 }
3200
Chris Lattner8cab0212008-01-05 22:25:12 +00003201 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003202 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00003203 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003204 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003205 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003206 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003207
Chris Lattnerf2d70992010-02-17 06:53:36 +00003208 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003209 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003210 TreePatternNode *Dest = Pat->getChild(i);
3211 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003212 I.error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003213
Florian Hahn6b1db822018-06-14 20:32:58 +00003214 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003215 if (!Val || !Val->getDef()->isSubClassOf("Register"))
David Blaikie19b22d42018-06-11 22:14:43 +00003216 I.error("implicitly defined value should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003217 InstImpResults.push_back(Val->getDef());
3218 }
3219 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003220 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003221
Chris Lattnerf2d70992010-02-17 06:53:36 +00003222 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003223 // If this is not a set, verify that the children nodes are not void typed,
3224 // and recurse.
3225 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003226 if (Pat->getChild(i)->getNumTypes() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003227 I.error("Cannot have void nodes inside of patterns!");
Florian Hahn75e87c32018-05-30 21:00:18 +00003228 FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3229 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003230 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003231
Chris Lattner8cab0212008-01-05 22:25:12 +00003232 // If this is a non-leaf node with no children, treat it basically as if
3233 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003234 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003235
Chris Lattner8cab0212008-01-05 22:25:12 +00003236 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003237 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003238 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003239 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003240
Chris Lattner8cab0212008-01-05 22:25:12 +00003241 // Otherwise, this is a set, validate and collect instruction results.
3242 if (Pat->getNumChildren() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003243 I.error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003244
Chris Lattner8cab0212008-01-05 22:25:12 +00003245 if (Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003246 I.error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003247
Chris Lattner8cab0212008-01-05 22:25:12 +00003248 // Check the set destinations.
3249 unsigned NumDests = Pat->getNumChildren()-1;
3250 for (unsigned i = 0; i != NumDests; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003251 TreePatternNodePtr Dest = Pat->getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003252 // For set destinations we also must resolve fragments here.
3253 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3254 DestPattern.InlinePatternFragments();
3255 DestPattern.InferAllTypes();
3256 Dest = DestPattern.getOnlyTree();
3257
Chris Lattner8cab0212008-01-05 22:25:12 +00003258 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003259 I.error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003260
Sean Silvafb509ed2012-10-10 20:24:43 +00003261 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003262 if (!Val) {
David Blaikie19b22d42018-06-11 22:14:43 +00003263 I.error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003264 continue;
3265 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003266
3267 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003268 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003269 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003270 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003271 if (Dest->getName().empty())
David Blaikie19b22d42018-06-11 22:14:43 +00003272 I.error("set destination must have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003273 if (InstResults.count(Dest->getName()))
David Blaikie19b22d42018-06-11 22:14:43 +00003274 I.error("cannot set '" + Dest->getName() + "' multiple times");
Chris Lattner8cab0212008-01-05 22:25:12 +00003275 InstResults[Dest->getName()] = Dest;
3276 } else if (Val->getDef()->isSubClassOf("Register")) {
3277 InstImpResults.push_back(Val->getDef());
3278 } else {
David Blaikie19b22d42018-06-11 22:14:43 +00003279 I.error("set destination should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003280 }
3281 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003282
Chris Lattner8cab0212008-01-05 22:25:12 +00003283 // Verify and collect info from the computation.
Florian Hahn75e87c32018-05-30 21:00:18 +00003284 FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3285 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003286}
3287
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003288//===----------------------------------------------------------------------===//
3289// Instruction Analysis
3290//===----------------------------------------------------------------------===//
3291
3292class InstAnalyzer {
3293 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003294public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003295 bool hasSideEffects;
3296 bool mayStore;
3297 bool mayLoad;
3298 bool isBitcast;
3299 bool isVariadic;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003300 bool hasChain;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003301
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003302 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3303 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003304 isBitcast(false), isVariadic(false), hasChain(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003305
Craig Topper2a053a92017-06-20 16:34:37 +00003306 void Analyze(const PatternToMatch &Pat) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003307 const TreePatternNode *N = Pat.getSrcPattern();
3308 AnalyzeNode(N);
3309 // These properties are detected only on the root node.
3310 isBitcast = IsNodeBitcast(N);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003311 }
3312
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003313private:
Florian Hahn6b1db822018-06-14 20:32:58 +00003314 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003315 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003316 return false;
3317
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003318 if (N->isLeaf())
3319 return false;
3320 if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
Evan Cheng880e299d2011-03-15 05:09:26 +00003321 return false;
3322
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003323 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
Evan Cheng880e299d2011-03-15 05:09:26 +00003324 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3325 return false;
3326 return OpInfo.getEnumName() == "ISD::BITCAST";
3327 }
3328
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003329public:
Florian Hahn6b1db822018-06-14 20:32:58 +00003330 void AnalyzeNode(const TreePatternNode *N) {
3331 if (N->isLeaf()) {
3332 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003333 Record *LeafRec = DI->getDef();
3334 // Handle ComplexPattern leaves.
3335 if (LeafRec->isSubClassOf("ComplexPattern")) {
3336 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3337 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3338 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003339 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003340 }
3341 }
3342 return;
3343 }
3344
3345 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003346 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3347 AnalyzeNode(N->getChild(i));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003348
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003349 // Notice properties of the node.
Florian Hahn6b1db822018-06-14 20:32:58 +00003350 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3351 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3352 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3353 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003354 if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003355
Florian Hahn6b1db822018-06-14 20:32:58 +00003356 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003357 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003358 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003359 mayLoad = true;// These may load memory.
3360
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003361 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003362 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3363
Matt Arsenault868af922017-04-28 21:01:46 +00003364 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3365 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003366 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003367 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003368 }
3369 }
3370
3371};
3372
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003373static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003374 const InstAnalyzer &PatInfo,
3375 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003376 bool Error = false;
3377
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003378 // Remember where InstInfo got its flags.
3379 if (InstInfo.hasUndefFlags())
3380 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003381
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003382 // Check explicitly set flags for consistency.
3383 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3384 !InstInfo.hasSideEffects_Unset) {
3385 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3386 // the pattern has no side effects. That could be useful for div/rem
3387 // instructions that may trap.
3388 if (!InstInfo.hasSideEffects) {
3389 Error = true;
3390 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3391 Twine(InstInfo.hasSideEffects));
3392 }
3393 }
3394
3395 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3396 Error = true;
3397 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3398 Twine(InstInfo.mayStore));
3399 }
3400
3401 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3402 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003403 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003404 if (!InstInfo.mayLoad) {
3405 Error = true;
3406 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3407 Twine(InstInfo.mayLoad));
3408 }
3409 }
3410
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003411 // Transfer inferred flags.
3412 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3413 InstInfo.mayStore |= PatInfo.mayStore;
3414 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003415
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003416 // These flags are silently added without any verification.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003417 // FIXME: To match historical behavior of TableGen, for now add those flags
3418 // only when we're inferring from the primary instruction pattern.
3419 if (PatDef->isSubClassOf("Instruction")) {
3420 InstInfo.isBitcast |= PatInfo.isBitcast;
3421 InstInfo.hasChain |= PatInfo.hasChain;
3422 InstInfo.hasChain_Inferred = true;
3423 }
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003424
3425 // Don't infer isVariadic. This flag means something different on SDNodes and
3426 // instructions. For example, a CALL SDNode is variadic because it has the
3427 // call arguments as operands, but a CALL instruction is not variadic - it
3428 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003429
3430 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003431}
3432
Jim Grosbach514410b2012-07-17 00:47:06 +00003433/// hasNullFragReference - Return true if the DAG has any reference to the
3434/// null_frag operator.
3435static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003436 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003437 if (!OpDef) return false;
3438 Record *Operator = OpDef->getDef();
3439
3440 // If this is the null fragment, return true.
3441 if (Operator->getName() == "null_frag") return true;
3442 // If any of the arguments reference the null fragment, return true.
3443 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003444 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003445 if (Arg && hasNullFragReference(Arg))
3446 return true;
3447 }
3448
3449 return false;
3450}
3451
3452/// hasNullFragReference - Return true if any DAG in the list references
3453/// the null_frag operator.
3454static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003455 for (Init *I : LI->getValues()) {
3456 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003457 assert(DI && "non-dag in an instruction Pattern list?!");
3458 if (hasNullFragReference(DI))
3459 return true;
3460 }
3461 return false;
3462}
3463
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003464/// Get all the instructions in a tree.
3465static void
Florian Hahn6b1db822018-06-14 20:32:58 +00003466getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3467 if (Tree->isLeaf())
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003468 return;
Florian Hahn6b1db822018-06-14 20:32:58 +00003469 if (Tree->getOperator()->isSubClassOf("Instruction"))
3470 Instrs.push_back(Tree->getOperator());
3471 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3472 getInstructionsInTree(Tree->getChild(i), Instrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003473}
3474
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003475/// Check the class of a pattern leaf node against the instruction operand it
3476/// represents.
3477static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3478 Record *Leaf) {
3479 if (OI.Rec == Leaf)
3480 return true;
3481
3482 // Allow direct value types to be used in instruction set patterns.
3483 // The type will be checked later.
3484 if (Leaf->isSubClassOf("ValueType"))
3485 return true;
3486
3487 // Patterns can also be ComplexPattern instances.
3488 if (Leaf->isSubClassOf("ComplexPattern"))
3489 return true;
3490
3491 return false;
3492}
3493
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003494void CodeGenDAGPatterns::parseInstructionPattern(
Ahmed Bougacha14107512013-10-28 18:07:21 +00003495 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003496
Craig Topper0d1fb902015-03-10 03:25:04 +00003497 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003498
Craig Topper0d1fb902015-03-10 03:25:04 +00003499 // Parse the instruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003500 TreePattern I(CGI.TheDef, Pat, true, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003501
Craig Topper0d1fb902015-03-10 03:25:04 +00003502 // InstInputs - Keep track of all of the inputs of the instruction, along
3503 // with the record they are declared as.
Florian Hahn75e87c32018-05-30 21:00:18 +00003504 std::map<std::string, TreePatternNodePtr> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003505
Craig Topper0d1fb902015-03-10 03:25:04 +00003506 // InstResults - Keep track of all the virtual registers that are 'set'
3507 // in the instruction, including what reg class they are.
Florian Hahn75e87c32018-05-30 21:00:18 +00003508 std::map<std::string, TreePatternNodePtr> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003509
Craig Topper0d1fb902015-03-10 03:25:04 +00003510 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003511
Craig Topper0d1fb902015-03-10 03:25:04 +00003512 // Verify that the top-level forms in the instruction are of void type, and
3513 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003514 SmallString<32> TypesString;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003515 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003516 TypesString.clear();
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003517 TreePatternNodePtr Pat = I.getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003518 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003519 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003520 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3521 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003522 OS << ", ";
3523 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003524 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003525 I.error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003526 " void types, has types " +
3527 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003528 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003529
Craig Topper0d1fb902015-03-10 03:25:04 +00003530 // Find inputs and outputs, and verify the structure of the uses/defs.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003531 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Craig Topper0d1fb902015-03-10 03:25:04 +00003532 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003533 }
3534
Craig Topper0d1fb902015-03-10 03:25:04 +00003535 // Now that we have inputs and outputs of the pattern, inspect the operands
3536 // list for the instruction. This determines the order that operands are
3537 // added to the machine instruction the node corresponds to.
3538 unsigned NumResults = InstResults.size();
3539
3540 // Parse the operands list from the (ops) list, validating it.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003541 assert(I.getArgList().empty() && "Args list should still be empty here!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003542
3543 // Check that all of the results occur first in the list.
3544 std::vector<Record*> Results;
Florian Hahn75e87c32018-05-30 21:00:18 +00003545 SmallVector<TreePatternNodePtr, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003546 for (unsigned i = 0; i != NumResults; ++i) {
3547 if (i == CGI.Operands.size())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003548 I.error("'" + InstResults.begin()->first +
Craig Topper0d1fb902015-03-10 03:25:04 +00003549 "' set but does not appear in operand list!");
3550 const std::string &OpName = CGI.Operands[i].Name;
3551
3552 // Check that it exists in InstResults.
Florian Hahn75e87c32018-05-30 21:00:18 +00003553 TreePatternNodePtr RNode = InstResults[OpName];
Craig Topper0d1fb902015-03-10 03:25:04 +00003554 if (!RNode)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003555 I.error("Operand $" + OpName + " does not exist in operand list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003556
Craig Topper3a8eb892015-03-20 05:09:06 +00003557
Craig Topper0d1fb902015-03-10 03:25:04 +00003558 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003559 ResNodes.push_back(std::move(RNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003560 if (!R)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003561 I.error("Operand $" + OpName + " should be a set destination: all "
Craig Topper0d1fb902015-03-10 03:25:04 +00003562 "outputs must occur before inputs in operand list!");
3563
3564 if (!checkOperandClass(CGI.Operands[i], R))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003565 I.error("Operand $" + OpName + " class mismatch!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003566
3567 // Remember the return type.
3568 Results.push_back(CGI.Operands[i].Rec);
3569
3570 // Okay, this one checks out.
3571 InstResults.erase(OpName);
3572 }
3573
Craig Topper765b9202018-07-15 06:52:48 +00003574 // Loop over the inputs next.
Florian Hahn75e87c32018-05-30 21:00:18 +00003575 std::vector<TreePatternNodePtr> ResultNodeOperands;
Craig Topper0d1fb902015-03-10 03:25:04 +00003576 std::vector<Record*> Operands;
3577 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3578 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3579 const std::string &OpName = Op.Name;
3580 if (OpName.empty())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003581 I.error("Operand #" + Twine(i) + " in operands list has no name!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003582
Craig Topper765b9202018-07-15 06:52:48 +00003583 if (!InstInputs.count(OpName)) {
Craig Topper0d1fb902015-03-10 03:25:04 +00003584 // If this is an operand with a DefaultOps set filled in, we can ignore
3585 // this. When we codegen it, we will do so as always executed.
3586 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3587 // Does it have a non-empty DefaultOps field? If so, ignore this
3588 // operand.
3589 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3590 continue;
3591 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003592 I.error("Operand $" + OpName +
Craig Topper0d1fb902015-03-10 03:25:04 +00003593 " does not appear in the instruction pattern");
3594 }
Craig Topper765b9202018-07-15 06:52:48 +00003595 TreePatternNodePtr InVal = InstInputs[OpName];
3596 InstInputs.erase(OpName); // It occurred, remove from map.
Craig Topper0d1fb902015-03-10 03:25:04 +00003597
3598 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3599 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3600 if (!checkOperandClass(Op, InRec))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003601 I.error("Operand $" + OpName + "'s register class disagrees"
Craig Topper0d1fb902015-03-10 03:25:04 +00003602 " between the operand and pattern");
3603 }
3604 Operands.push_back(Op.Rec);
3605
3606 // Construct the result for the dest-pattern operand list.
Florian Hahn75e87c32018-05-30 21:00:18 +00003607 TreePatternNodePtr OpNode = InVal->clone();
Craig Topper0d1fb902015-03-10 03:25:04 +00003608
3609 // No predicate is useful on the result.
3610 OpNode->clearPredicateFns();
3611
3612 // Promote the xform function to be an explicit node if set.
3613 if (Record *Xform = OpNode->getTransformFn()) {
3614 OpNode->setTransformFn(nullptr);
Florian Hahn75e87c32018-05-30 21:00:18 +00003615 std::vector<TreePatternNodePtr> Children;
Craig Topper0d1fb902015-03-10 03:25:04 +00003616 Children.push_back(OpNode);
Craig Topper26fc06352018-07-15 06:52:49 +00003617 OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
Florian Hahn6b1db822018-06-14 20:32:58 +00003618 OpNode->getNumTypes());
Craig Topper0d1fb902015-03-10 03:25:04 +00003619 }
3620
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003621 ResultNodeOperands.push_back(std::move(OpNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003622 }
3623
Craig Topper765b9202018-07-15 06:52:48 +00003624 if (!InstInputs.empty())
3625 I.error("Input operand $" + InstInputs.begin()->first +
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003626 " occurs in pattern but not in operands list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003627
Florian Hahn6b1db822018-06-14 20:32:58 +00003628 TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00003629 I.getRecord(), std::move(ResultNodeOperands),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003630 GetNumNodeResults(I.getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003631 // Copy fully inferred output node types to instruction result pattern.
3632 for (unsigned i = 0; i != NumResults; ++i) {
3633 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3634 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3635 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003636
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003637 // FIXME: Assume only the first tree is the pattern. The others are clobber
3638 // nodes.
3639 TreePatternNodePtr Pattern = I.getTree(0);
3640 TreePatternNodePtr SrcPattern;
3641 if (Pattern->getOperator()->getName() == "set") {
3642 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3643 } else{
3644 // Not a set (store or something?)
3645 SrcPattern = Pattern;
3646 }
3647
Craig Topper0d1fb902015-03-10 03:25:04 +00003648 // Create and insert the instruction.
3649 // FIXME: InstImpResults should not be part of DAGInstruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003650 Record *R = I.getRecord();
3651 DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3652 std::forward_as_tuple(Results, Operands, InstImpResults,
3653 SrcPattern, ResultPattern));
Craig Topper0d1fb902015-03-10 03:25:04 +00003654
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003655 LLVM_DEBUG(I.dump());
Craig Topper0d1fb902015-03-10 03:25:04 +00003656}
3657
Ahmed Bougacha14107512013-10-28 18:07:21 +00003658/// ParseInstructions - Parse all of the instructions, inlining and resolving
3659/// any fragments involved. This populates the Instructions list with fully
3660/// resolved instructions.
3661void CodeGenDAGPatterns::ParseInstructions() {
3662 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3663
Craig Topper306cb122015-11-22 20:46:24 +00003664 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003665 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003666
Craig Topper306cb122015-11-22 20:46:24 +00003667 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3668 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003669
3670 // If there is no pattern, only collect minimal information about the
3671 // instruction for its operand list. We have to assume that there is one
3672 // result, as we have no detailed info. A pattern which references the
3673 // null_frag operator is as-if no pattern were specified. Normally this
3674 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3675 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003676 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003677 std::vector<Record*> Results;
3678 std::vector<Record*> Operands;
3679
Craig Topper306cb122015-11-22 20:46:24 +00003680 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003681
3682 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003683 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3684 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003685
Craig Topper3a8eb892015-03-20 05:09:06 +00003686 // The rest are inputs.
3687 for (unsigned j = InstInfo.Operands.NumDefs,
3688 e = InstInfo.Operands.size(); j < e; ++j)
3689 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003690 }
3691
3692 // Create and insert the instruction.
3693 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003694 Instructions.insert(std::make_pair(Instr,
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003695 DAGInstruction(Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003696 continue; // no pattern.
3697 }
3698
Craig Topper306cb122015-11-22 20:46:24 +00003699 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003700 parseInstructionPattern(CGI, LI, Instructions);
Chris Lattner8cab0212008-01-05 22:25:12 +00003701 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003702
Chris Lattner8cab0212008-01-05 22:25:12 +00003703 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003704 for (auto &Entry : Instructions) {
Craig Topper306cb122015-11-22 20:46:24 +00003705 Record *Instr = Entry.first;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003706 DAGInstruction &TheInst = Entry.second;
3707 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3708 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3709
3710 if (SrcPattern && ResultPattern) {
3711 TreePattern Pattern(Instr, SrcPattern, true, *this);
3712 TreePattern Result(Instr, ResultPattern, false, *this);
3713 ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3714 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003715 }
3716}
3717
Florian Hahn6b1db822018-06-14 20:32:58 +00003718typedef std::pair<TreePatternNode *, unsigned> NameRecord;
Chris Lattnera7722b62010-02-23 06:55:24 +00003719
Florian Hahn6b1db822018-06-14 20:32:58 +00003720static void FindNames(TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003721 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003722 TreePattern *PatternTop) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003723 if (!P->getName().empty()) {
3724 NameRecord &Rec = Names[P->getName()];
Chris Lattnera7722b62010-02-23 06:55:24 +00003725 // If this is the first instance of the name, remember the node.
3726 if (Rec.second++ == 0)
Florian Hahn6b1db822018-06-14 20:32:58 +00003727 Rec.first = P;
3728 else if (Rec.first->getExtTypes() != P->getExtTypes())
3729 PatternTop->error("repetition of value: $" + P->getName() +
Chris Lattner5b0e2492010-02-23 07:22:28 +00003730 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003731 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003732
Florian Hahn6b1db822018-06-14 20:32:58 +00003733 if (!P->isLeaf()) {
3734 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3735 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003736 }
3737}
3738
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003739std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3740 std::vector<Predicate> Preds;
3741 for (Init *I : L->getValues()) {
3742 if (DefInit *Pred = dyn_cast<DefInit>(I))
3743 Preds.push_back(Pred->getDef());
3744 else
3745 llvm_unreachable("Non-def on the list");
3746 }
3747
3748 // Sort so that different orders get canonicalized to the same string.
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00003749 llvm::sort(Preds.begin(), Preds.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003750 return Preds;
3751}
3752
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003753void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003754 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003755 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003756 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003757 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3758 PrintWarning(Pattern->getRecord()->getLoc(),
3759 Twine("Pattern can never match: ") + Reason);
3760 return;
3761 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003762
Chris Lattner1e634e32010-03-01 22:29:19 +00003763 // If the source pattern's root is a complex pattern, that complex pattern
3764 // must specify the nodes it can potentially match.
3765 if (const ComplexPattern *CP =
3766 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3767 if (CP->getRootNodes().empty())
3768 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3769 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003770
3771
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003772 // Find all of the named values in the input and output, ensure they have the
3773 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003774 std::map<std::string, NameRecord> SrcNames, DstNames;
Florian Hahn6b1db822018-06-14 20:32:58 +00003775 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3776 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003777
3778 // Scan all of the named values in the destination pattern, rejecting them if
3779 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003780 for (const auto &Entry : DstNames) {
3781 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003782 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003783 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003784 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003785
Chris Lattnera7722b62010-02-23 06:55:24 +00003786 // Scan all of the named values in the source pattern, rejecting them if the
3787 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003788 for (const auto &Entry : SrcNames)
3789 if (DstNames[Entry.first].first == nullptr &&
3790 SrcNames[Entry.first].second == 1)
3791 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003792
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003793 PatternsToMatch.push_back(PTM);
Chris Lattner0c0baa92010-02-23 06:16:51 +00003794}
3795
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003796void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003797 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003798 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003799
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003800 unsigned Errors = 0;
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003801
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003802 // Try to infer flags from all patterns in PatternToMatch. These include
3803 // both the primary instruction patterns (which always come first) and
3804 // patterns defined outside the instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003805 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003806 // We can only infer from single-instruction patterns, otherwise we won't
3807 // know which instruction should get the flags.
3808 SmallVector<Record*, 8> PatInstrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003809 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003810 if (PatInstrs.size() != 1)
3811 continue;
3812
3813 // Get the single instruction.
3814 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3815
3816 // Only infer properties from the first pattern. We'll verify the others.
3817 if (InstInfo.InferredFrom)
3818 continue;
3819
3820 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003821 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003822 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3823 }
3824
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003825 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003826 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003827
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003828 // If requested by the target, guess any undefined properties.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003829 if (Target.guessInstructionProperties()) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003830 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3831 CodeGenInstruction *InstInfo =
3832 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003833 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003834 continue;
3835 // The mayLoad and mayStore flags default to false.
3836 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003837 if (InstInfo->hasSideEffects_Unset)
3838 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003839 }
3840 return;
3841 }
3842
3843 // Complain about any flags that are still undefined.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003844 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3845 CodeGenInstruction *InstInfo =
3846 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003847 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003848 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003849 if (InstInfo->hasSideEffects_Unset)
3850 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003851 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003852 if (InstInfo->mayStore_Unset)
3853 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003854 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003855 if (InstInfo->mayLoad_Unset)
3856 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003857 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003858 }
3859}
3860
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003861
3862/// Verify instruction flags against pattern node properties.
3863void CodeGenDAGPatterns::VerifyInstructionFlags() {
3864 unsigned Errors = 0;
3865 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3866 const PatternToMatch &PTM = *I;
3867 SmallVector<Record*, 8> Instrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003868 getInstructionsInTree(PTM.getDstPattern(), Instrs);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003869 if (Instrs.empty())
3870 continue;
3871
3872 // Count the number of instructions with each flag set.
3873 unsigned NumSideEffects = 0;
3874 unsigned NumStores = 0;
3875 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003876 for (const Record *Instr : Instrs) {
3877 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003878 NumSideEffects += InstInfo.hasSideEffects;
3879 NumStores += InstInfo.mayStore;
3880 NumLoads += InstInfo.mayLoad;
3881 }
3882
3883 // Analyze the source pattern.
3884 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003885 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003886
3887 // Collect error messages.
3888 SmallVector<std::string, 4> Msgs;
3889
3890 // Check for missing flags in the output.
3891 // Permit extra flags for now at least.
3892 if (PatInfo.hasSideEffects && !NumSideEffects)
3893 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3894
3895 // Don't verify store flags on instructions with side effects. At least for
3896 // intrinsics, side effects implies mayStore.
3897 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3898 Msgs.push_back("pattern may store, but mayStore isn't set");
3899
3900 // Similarly, mayStore implies mayLoad on intrinsics.
3901 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3902 Msgs.push_back("pattern may load, but mayLoad isn't set");
3903
3904 // Print error messages.
3905 if (Msgs.empty())
3906 continue;
3907 ++Errors;
3908
Craig Topper306cb122015-11-22 20:46:24 +00003909 for (const std::string &Msg : Msgs)
3910 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003911 (Instrs.size() == 1 ?
3912 "instruction" : "output instructions"));
3913 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003914 for (const Record *Instr : Instrs) {
3915 if (Instr != PTM.getSrcRecord())
3916 PrintError(Instr->getLoc(), "defined here");
3917 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003918 if (InstInfo.InferredFrom &&
3919 InstInfo.InferredFrom != InstInfo.TheDef &&
3920 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003921 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003922 }
3923 }
3924 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003925 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003926}
3927
Chris Lattnercabe0372010-03-15 06:00:16 +00003928/// Given a pattern result with an unresolved type, see if we can find one
3929/// instruction with an unresolved result type. Force this result type to an
3930/// arbitrary element if it's possible types to converge results.
Florian Hahn6b1db822018-06-14 20:32:58 +00003931static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3932 if (N->isLeaf())
Chris Lattnercabe0372010-03-15 06:00:16 +00003933 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003934
Chris Lattnercabe0372010-03-15 06:00:16 +00003935 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003936 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3937 if (ForceArbitraryInstResultType(N->getChild(i), TP))
Chris Lattnercabe0372010-03-15 06:00:16 +00003938 return true;
3939
Florian Hahn6b1db822018-06-14 20:32:58 +00003940 if (!N->getOperator()->isSubClassOf("Instruction"))
Chris Lattnercabe0372010-03-15 06:00:16 +00003941 return false;
3942
3943 // If this type is already concrete or completely unknown we can't do
3944 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003945 TypeInfer &TI = TP.getInfer();
Florian Hahn6b1db822018-06-14 20:32:58 +00003946 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3947 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003948 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003949
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003950 // Otherwise, force its type to an arbitrary choice.
Florian Hahn6b1db822018-06-14 20:32:58 +00003951 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003952 return true;
3953 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003954
Chris Lattnerf1447252010-03-19 21:37:09 +00003955 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003956}
3957
Ulrich Weigand58a97862018-08-01 11:57:58 +00003958// Promote xform function to be an explicit node wherever set.
3959static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
3960 if (Record *Xform = N->getTransformFn()) {
3961 N->setTransformFn(nullptr);
3962 std::vector<TreePatternNodePtr> Children;
3963 Children.push_back(PromoteXForms(N));
3964 return std::make_shared<TreePatternNode>(Xform, std::move(Children),
3965 N->getNumTypes());
3966 }
3967
3968 if (!N->isLeaf())
3969 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3970 TreePatternNodePtr Child = N->getChildShared(i);
Ulrich Weigandf989cd72018-08-01 12:07:32 +00003971 N->setChild(i, PromoteXForms(Child));
Ulrich Weigand58a97862018-08-01 11:57:58 +00003972 }
3973 return N;
3974}
3975
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003976void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
3977 TreePattern &Pattern, TreePattern &Result,
3978 const std::vector<Record *> &InstImpResults) {
3979
3980 // Inline pattern fragments and expand multiple alternatives.
3981 Pattern.InlinePatternFragments();
3982 Result.InlinePatternFragments();
3983
3984 if (Result.getNumTrees() != 1)
3985 Result.error("Cannot use multi-alternative fragments in result pattern!");
3986
3987 // Infer types.
3988 bool IterateInference;
3989 bool InferredAllPatternTypes, InferredAllResultTypes;
3990 do {
3991 // Infer as many types as possible. If we cannot infer all of them, we
3992 // can never do anything with this pattern: report it to the user.
3993 InferredAllPatternTypes =
3994 Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
3995
3996 // Infer as many types as possible. If we cannot infer all of them, we
3997 // can never do anything with this pattern: report it to the user.
3998 InferredAllResultTypes =
3999 Result.InferAllTypes(&Pattern.getNamedNodesMap());
4000
4001 IterateInference = false;
4002
4003 // Apply the type of the result to the source pattern. This helps us
4004 // resolve cases where the input type is known to be a pointer type (which
4005 // is considered resolved), but the result knows it needs to be 32- or
4006 // 64-bits. Infer the other way for good measure.
4007 for (auto T : Pattern.getTrees())
4008 for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4009 T->getNumTypes());
4010 i != e; ++i) {
4011 IterateInference |= T->UpdateNodeType(
4012 i, Result.getOnlyTree()->getExtType(i), Result);
4013 IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4014 i, T->getExtType(i), Result);
4015 }
4016
4017 // If our iteration has converged and the input pattern's types are fully
4018 // resolved but the result pattern is not fully resolved, we may have a
4019 // situation where we have two instructions in the result pattern and
4020 // the instructions require a common register class, but don't care about
4021 // what actual MVT is used. This is actually a bug in our modelling:
4022 // output patterns should have register classes, not MVTs.
4023 //
4024 // In any case, to handle this, we just go through and disambiguate some
4025 // arbitrary types to the result pattern's nodes.
4026 if (!IterateInference && InferredAllPatternTypes &&
4027 !InferredAllResultTypes)
4028 IterateInference =
4029 ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4030 } while (IterateInference);
4031
4032 // Verify that we inferred enough types that we can do something with the
4033 // pattern and result. If these fire the user has to add type casts.
4034 if (!InferredAllPatternTypes)
4035 Pattern.error("Could not infer all types in pattern!");
4036 if (!InferredAllResultTypes) {
4037 Pattern.dump();
4038 Result.error("Could not infer all types in pattern result!");
4039 }
4040
Ulrich Weigand58a97862018-08-01 11:57:58 +00004041 // Promote xform function to be an explicit node wherever set.
4042 TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004043
4044 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4045 Temp.InferAllTypes();
4046
4047 ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4048 int Complexity = TheDef->getValueAsInt("AddedComplexity");
4049
4050 if (PatternRewriter)
4051 PatternRewriter(&Pattern);
4052
4053 // A pattern may end up with an "impossible" type, i.e. a situation
4054 // where all types have been eliminated for some node in this pattern.
4055 // This could occur for intrinsics that only make sense for a specific
4056 // value type, and use a specific register class. If, for some mode,
4057 // that register class does not accept that type, the type inference
4058 // will lead to a contradiction, which is not an error however, but
4059 // a sign that this pattern will simply never match.
4060 if (Temp.getOnlyTree()->hasPossibleType())
4061 for (auto T : Pattern.getTrees())
4062 if (T->hasPossibleType())
4063 AddPatternToMatch(&Pattern,
4064 PatternToMatch(TheDef, makePredList(Preds),
4065 T, Temp.getOnlyTree(),
4066 InstImpResults, Complexity,
4067 TheDef->getID()));
4068}
4069
Chris Lattnerab3242f2008-01-06 01:10:31 +00004070void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00004071 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4072
Craig Topper306cb122015-11-22 20:46:24 +00004073 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00004074 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00004075
4076 // If the pattern references the null_frag, there's nothing to do.
4077 if (hasNullFragReference(Tree))
4078 continue;
4079
Florian Hahn75e87c32018-05-30 21:00:18 +00004080 TreePattern Pattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00004081
David Greeneaf8ee2c2011-07-29 22:43:06 +00004082 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00004083 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004084
Chris Lattner8cab0212008-01-05 22:25:12 +00004085 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004086 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004087
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004088 if (Result.getNumTrees() != 1)
4089 Result.error("Cannot handle instructions producing instructions "
4090 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004091
Chris Lattner8cab0212008-01-05 22:25:12 +00004092 // Validate that the input pattern is correct.
Florian Hahn75e87c32018-05-30 21:00:18 +00004093 std::map<std::string, TreePatternNodePtr> InstInputs;
4094 std::map<std::string, TreePatternNodePtr> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00004095 std::vector<Record*> InstImpResults;
Florian Hahn75e87c32018-05-30 21:00:18 +00004096 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
David Blaikie19b22d42018-06-11 22:14:43 +00004097 FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
Florian Hahn75e87c32018-05-30 21:00:18 +00004098 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004099
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004100 ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004101 }
4102}
4103
Florian Hahn6b1db822018-06-14 20:32:58 +00004104static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004105 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4106 for (const auto &I : VTS)
4107 Modes.insert(I.first);
4108
4109 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00004110 collectModes(Modes, N->getChild(i));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004111}
4112
4113void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4114 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4115 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4116 std::vector<PatternToMatch> Copy = PatternsToMatch;
4117 PatternsToMatch.clear();
4118
Florian Hahn75e87c32018-05-30 21:00:18 +00004119 auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4120 TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4121 TreePatternNodePtr NewDst = P.DstPattern->clone();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004122 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004123 return;
4124 }
4125
4126 std::vector<Predicate> Preds = P.Predicates;
4127 const std::vector<Predicate> &MC = ModeChecks[Mode];
4128 Preds.insert(Preds.end(), MC.begin(), MC.end());
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004129 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4130 std::move(NewDst), P.getDstRegs(),
4131 P.getAddedComplexity(), Record::getNewUID(),
4132 Mode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004133 };
4134
4135 for (PatternToMatch &P : Copy) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004136 TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
Florian Hahn6b1db822018-06-14 20:32:58 +00004137 if (P.SrcPattern->hasProperTypeByHwMode())
4138 SrcP = P.SrcPattern;
4139 if (P.DstPattern->hasProperTypeByHwMode())
4140 DstP = P.DstPattern;
4141 if (!SrcP && !DstP) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004142 PatternsToMatch.push_back(P);
4143 continue;
4144 }
4145
4146 std::set<unsigned> Modes;
Florian Hahn6b1db822018-06-14 20:32:58 +00004147 if (SrcP)
4148 collectModes(Modes, SrcP.get());
4149 if (DstP)
4150 collectModes(Modes, DstP.get());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004151
4152 // The predicate for the default mode needs to be constructed for each
4153 // pattern separately.
4154 // Since not all modes must be present in each pattern, if a mode m is
4155 // absent, then there is no point in constructing a check for m. If such
4156 // a check was created, it would be equivalent to checking the default
4157 // mode, except not all modes' predicates would be a part of the checking
4158 // code. The subsequently generated check for the default mode would then
4159 // have the exact same patterns, but a different predicate code. To avoid
4160 // duplicated patterns with different predicate checks, construct the
4161 // default check as a negation of all predicates that are actually present
4162 // in the source/destination patterns.
4163 std::vector<Predicate> DefaultPred;
4164
4165 for (unsigned M : Modes) {
4166 if (M == DefaultMode)
4167 continue;
4168 if (ModeChecks.find(M) != ModeChecks.end())
4169 continue;
4170
4171 // Fill the map entry for this mode.
4172 const HwMode &HM = CGH.getMode(M);
4173 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4174
4175 // Add negations of the HM's predicates to the default predicate.
4176 DefaultPred.emplace_back(Predicate(HM.Features, false));
4177 }
4178
4179 for (unsigned M : Modes) {
4180 if (M == DefaultMode)
4181 continue;
4182 AppendPattern(P, M);
4183 }
4184
4185 bool HasDefault = Modes.count(DefaultMode);
4186 if (HasDefault)
4187 AppendPattern(P, DefaultMode);
4188 }
4189}
4190
4191/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004192typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004193
Florian Hahn6b1db822018-06-14 20:32:58 +00004194static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4195 if (N->isLeaf()) {
4196 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4197 DepMap[N->getName()]++;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004198 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00004199 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4200 FindDepVarsOf(N->getChild(i), DepMap);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004201 }
4202}
4203
4204/// Find dependent variables within child patterns
Florian Hahn6b1db822018-06-14 20:32:58 +00004205static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004206 DepVarMap depcounts;
4207 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004208 for (const auto &Pair : depcounts) {
4209 if (Pair.getValue() > 1)
4210 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004211 }
4212}
4213
4214#ifndef NDEBUG
4215/// Dump the dependent variable set:
4216static void DumpDepVars(MultipleUseVarSet &DepVars) {
4217 if (DepVars.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004218 LLVM_DEBUG(errs() << "<empty set>");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004219 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004220 LLVM_DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004221 for (const auto &DepVar : DepVars) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004222 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004223 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004224 LLVM_DEBUG(errs() << "]");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004225 }
4226}
4227#endif
4228
4229
Chris Lattner8cab0212008-01-05 22:25:12 +00004230/// CombineChildVariants - Given a bunch of permutations of each child of the
4231/// 'operator' node, put them together in all possible ways.
Florian Hahn75e87c32018-05-30 21:00:18 +00004232static void CombineChildVariants(
Florian Hahn6b1db822018-06-14 20:32:58 +00004233 TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004234 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4235 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4236 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004237 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004238 for (const auto &Variants : ChildVariants)
4239 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004240 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004241
Chris Lattner8cab0212008-01-05 22:25:12 +00004242 // The end result is an all-pairs construction of the resultant pattern.
4243 std::vector<unsigned> Idxs;
4244 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004245 bool NotDone;
4246 do {
4247#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004248 LLVM_DEBUG(if (!Idxs.empty()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004249 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004250 for (unsigned Idx : Idxs) {
4251 errs() << Idx << " ";
4252 }
4253 errs() << "]\n";
4254 });
Scott Michel94420742008-03-05 17:49:05 +00004255#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004256 // Create the variant and add it to the output list.
Florian Hahn75e87c32018-05-30 21:00:18 +00004257 std::vector<TreePatternNodePtr> NewChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004258 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4259 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Florian Hahn75e87c32018-05-30 21:00:18 +00004260 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00004261 Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004262
Chris Lattner8cab0212008-01-05 22:25:12 +00004263 // Copy over properties.
Florian Hahn6b1db822018-06-14 20:32:58 +00004264 R->setName(Orig->getName());
4265 R->setPredicateFns(Orig->getPredicateFns());
4266 R->setTransformFn(Orig->getTransformFn());
4267 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4268 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004269
Scott Michel94420742008-03-05 17:49:05 +00004270 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004271 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004272 // Scan to see if this pattern has already been emitted. We can get
4273 // duplication due to things like commuting:
4274 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4275 // which are the same pattern. Ignore the dups.
4276 if (R->canPatternMatch(ErrString, CDP) &&
Florian Hahn75e87c32018-05-30 21:00:18 +00004277 none_of(OutVariants, [&](TreePatternNodePtr Variant) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004278 return R->isIsomorphicTo(Variant.get(), DepVars);
David Majnemer0a16c222016-08-11 21:15:00 +00004279 }))
Florian Hahn75e87c32018-05-30 21:00:18 +00004280 OutVariants.push_back(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004281
Scott Michel94420742008-03-05 17:49:05 +00004282 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004283 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004284 // [0, 0], [0, 1], [1, 0], [1, 1].
4285 int IdxsIdx;
4286 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4287 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4288 Idxs[IdxsIdx] = 0;
4289 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004290 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004291 }
Scott Michel94420742008-03-05 17:49:05 +00004292 NotDone = (IdxsIdx >= 0);
4293 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004294}
4295
4296/// CombineChildVariants - A helper function for binary operators.
4297///
Florian Hahn6b1db822018-06-14 20:32:58 +00004298static void CombineChildVariants(TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004299 const std::vector<TreePatternNodePtr> &LHS,
4300 const std::vector<TreePatternNodePtr> &RHS,
4301 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004302 CodeGenDAGPatterns &CDP,
4303 const MultipleUseVarSet &DepVars) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004304 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004305 ChildVariants.push_back(LHS);
4306 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004307 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004308}
Chris Lattner8cab0212008-01-05 22:25:12 +00004309
Florian Hahn75e87c32018-05-30 21:00:18 +00004310static void
Florian Hahn6b1db822018-06-14 20:32:58 +00004311GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004312 std::vector<TreePatternNodePtr> &Children) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004313 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4314 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004315
Chris Lattner8cab0212008-01-05 22:25:12 +00004316 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00004317 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004318 N->getTransformFn()) {
4319 Children.push_back(N);
4320 return;
4321 }
4322
Florian Hahn6b1db822018-06-14 20:32:58 +00004323 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004324 Children.push_back(N->getChildShared(0));
Chris Lattner8cab0212008-01-05 22:25:12 +00004325 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004326 GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004327
Florian Hahn6b1db822018-06-14 20:32:58 +00004328 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004329 Children.push_back(N->getChildShared(1));
Chris Lattner8cab0212008-01-05 22:25:12 +00004330 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004331 GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004332}
4333
4334/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4335/// the (potentially recursive) pattern by using algebraic laws.
4336///
Florian Hahn6b1db822018-06-14 20:32:58 +00004337static void GenerateVariantsOf(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004338 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004339 CodeGenDAGPatterns &CDP,
4340 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004341 // We cannot permute leaves or ComplexPattern uses.
4342 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004343 OutVariants.push_back(N);
4344 return;
4345 }
4346
4347 // Look up interesting info about the node.
4348 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4349
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004350 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004351 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004352 // Re-associate by pulling together all of the linked operators
Florian Hahn75e87c32018-05-30 21:00:18 +00004353 std::vector<TreePatternNodePtr> MaximalChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004354 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4355
4356 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4357 // permutations.
4358 if (MaximalChildren.size() == 3) {
4359 // Find the variants of all of our maximal children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004360 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004361 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4362 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4363 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004364
Chris Lattner8cab0212008-01-05 22:25:12 +00004365 // There are only two ways we can permute the tree:
4366 // (A op B) op C and A op (B op C)
4367 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004368
Chris Lattner8cab0212008-01-05 22:25:12 +00004369 // Generate legal pair permutations of A/B/C.
Florian Hahn75e87c32018-05-30 21:00:18 +00004370 std::vector<TreePatternNodePtr> ABVariants;
4371 std::vector<TreePatternNodePtr> BAVariants;
4372 std::vector<TreePatternNodePtr> ACVariants;
4373 std::vector<TreePatternNodePtr> CAVariants;
4374 std::vector<TreePatternNodePtr> BCVariants;
4375 std::vector<TreePatternNodePtr> CBVariants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004376 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4377 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4378 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4379 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4380 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4381 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004382
4383 // Combine those into the result: (x op x) op x
Florian Hahn6b1db822018-06-14 20:32:58 +00004384 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4385 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4386 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4387 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4388 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4389 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004390
4391 // Combine those into the result: x op (x op x)
Florian Hahn6b1db822018-06-14 20:32:58 +00004392 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4393 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4394 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4395 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4396 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4397 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004398 return;
4399 }
4400 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004401
Chris Lattner8cab0212008-01-05 22:25:12 +00004402 // Compute permutations of all children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004403 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004404 ChildVariants.resize(N->getNumChildren());
4405 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn75e87c32018-05-30 21:00:18 +00004406 GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004407
4408 // Build all permutations based on how the children were formed.
Florian Hahn6b1db822018-06-14 20:32:58 +00004409 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004410
4411 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004412 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4413 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004414 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004415 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004416 // Don't count children which are actually register references.
4417 unsigned NC = 0;
4418 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004419 TreePatternNode *Child = N->getChild(i);
4420 if (Child->isLeaf())
4421 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004422 Record *RR = DI->getDef();
4423 if (RR->isSubClassOf("Register"))
4424 continue;
4425 }
4426 NC++;
4427 }
4428 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004429 if (isCommIntrinsic) {
4430 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4431 // operands are the commutative operands, and there might be more operands
4432 // after those.
4433 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004434 "Commutative intrinsic should have at least 3 children!");
Florian Hahn75e87c32018-05-30 21:00:18 +00004435 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004436 Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4437 Variants.push_back(std::move(ChildVariants[2]));
4438 Variants.push_back(std::move(ChildVariants[1]));
Evan Cheng49bad4c2008-06-16 20:29:38 +00004439 for (unsigned i = 3; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004440 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004441 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004442 } else if (NC == N->getNumChildren()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004443 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004444 Variants.push_back(std::move(ChildVariants[1]));
4445 Variants.push_back(std::move(ChildVariants[0]));
Craig Topper98a96282017-09-04 03:44:33 +00004446 for (unsigned i = 2; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004447 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004448 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004449 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004450 }
4451}
4452
4453
4454// GenerateVariants - Generate variants. For example, commutative patterns can
4455// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004456void CodeGenDAGPatterns::GenerateVariants() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004457 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004458
Chris Lattner8cab0212008-01-05 22:25:12 +00004459 // Loop over all of the patterns we've collected, checking to see if we can
4460 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004461 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004462 // the .td file having to contain tons of variants of instructions.
4463 //
4464 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4465 // intentionally do not reconsider these. Any variants of added patterns have
4466 // already been added.
4467 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00004468 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00004469 MultipleUseVarSet DepVars;
Florian Hahn75e87c32018-05-30 21:00:18 +00004470 std::vector<TreePatternNodePtr> Variants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004471 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004472 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4473 LLVM_DEBUG(DumpDepVars(DepVars));
4474 LLVM_DEBUG(errs() << "\n");
Florian Hahn75e87c32018-05-30 21:00:18 +00004475 GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4476 *this, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004477
4478 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00004479 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004480 continue;
4481
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004482 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4483 PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004484
4485 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004486 TreePatternNodePtr Variant = Variants[v];
Chris Lattner8cab0212008-01-05 22:25:12 +00004487
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004488 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4489 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004490
Chris Lattner8cab0212008-01-05 22:25:12 +00004491 // Scan to see if an instruction or explicit pattern already matches this.
4492 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004493 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004494 // Skip if the top level predicates do not match.
Simon Pilgrimf19cdc62018-08-16 16:04:05 +00004495 if ((i != p) && (PatternsToMatch[i].getPredicates() !=
4496 PatternsToMatch[p].getPredicates()))
Evan Cheng34c8c742009-06-26 05:59:16 +00004497 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004498 // Check to see if this variant already exists.
Florian Hahn6b1db822018-06-14 20:32:58 +00004499 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004500 DepVars)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004501 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004502 AlreadyExists = true;
4503 break;
4504 }
4505 }
4506 // If we already have it, ignore the variant.
4507 if (AlreadyExists) continue;
4508
4509 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004510 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004511 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
Florian Hahn75e87c32018-05-30 21:00:18 +00004512 Variant, PatternsToMatch[i].getDstPatternShared(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004513 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004514 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00004515 }
4516
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004517 LLVM_DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004518 }
4519}