blob: 19a7874ee1fb43e34aca98d30fe13c9814279c6d [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner8cab0212008-01-05 22:25:12 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattnerab3242f2008-01-06 01:10:31 +00009// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner8cab0212008-01-05 22:25:12 +000010// represent the patterns present in a .td file for instructions.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner78ac0742008-01-05 23:37:52 +000014#include "CodeGenDAGPatterns.h"
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +000015#include "llvm/ADT/BitVector.h"
Zachary Turner249dc142017-09-20 18:01:40 +000016#include "llvm/ADT/DenseSet.h"
Craig Topperbd199f82018-12-05 00:47:59 +000017#include "llvm/ADT/MapVector.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000018#include "llvm/ADT/STLExtras.h"
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000019#include "llvm/ADT/SmallSet.h"
Craig Topper3522ab32015-11-28 08:23:02 +000020#include "llvm/ADT/SmallString.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000021#include "llvm/ADT/StringExtras.h"
Craig Topperddfdd942017-09-21 04:55:03 +000022#include "llvm/ADT/StringMap.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000023#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000024#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000025#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000026#include "llvm/TableGen/Error.h"
27#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000028#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000029#include <cstdio>
Craig Topperbd199f82018-12-05 00:47:59 +000030#include <iterator>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000031#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000032using namespace llvm;
33
Chandler Carruthe96dd892014-04-21 22:55:11 +000034#define DEBUG_TYPE "dag-patterns"
35
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000036static inline bool isIntegerOrPtr(MVT VT) {
37 return VT.isInteger() || VT == MVT::iPTR;
Duncan Sands13237ac2008-06-06 12:08:01 +000038}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000039static inline bool isFloatingPoint(MVT VT) {
40 return VT.isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000041}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000042static inline bool isVector(MVT VT) {
43 return VT.isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000044}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000045static inline bool isScalar(MVT VT) {
46 return !VT.isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000047}
Duncan Sands13237ac2008-06-06 12:08:01 +000048
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000049template <typename Predicate>
50static bool berase_if(MachineValueTypeSet &S, Predicate P) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000051 bool Erased = false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000052 // It is ok to iterate over MachineValueTypeSet and remove elements from it
53 // at the same time.
54 for (MVT T : S) {
55 if (!P(T))
56 continue;
57 Erased = true;
58 S.erase(T);
Chris Lattnercabe0372010-03-15 06:00:16 +000059 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000060 return Erased;
Chris Lattner8cab0212008-01-05 22:25:12 +000061}
62
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000063// --- TypeSetByHwMode
Chris Lattnercabe0372010-03-15 06:00:16 +000064
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000065// This is a parameterized type-set class. For each mode there is a list
66// of types that are currently possible for a given tree node. Type
67// inference will apply to each mode separately.
Jim Grosbach65586fe2010-12-21 16:16:00 +000068
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000069TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
Tom Stellard9ad714f2019-02-20 19:43:47 +000070 for (const ValueTypeByHwMode &VVT : VTList) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000071 insert(VVT);
Tom Stellard9ad714f2019-02-20 19:43:47 +000072 AddrSpaces.push_back(VVT.PtrAddrSpace);
73 }
Chris Lattner8cab0212008-01-05 22:25:12 +000074}
75
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000076bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
77 for (const auto &I : *this) {
78 if (I.second.size() > 1)
79 return false;
80 if (!AllowEmpty && I.second.empty())
81 return false;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000082 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000083 return true;
84}
Chris Lattnercabe0372010-03-15 06:00:16 +000085
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000086ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
87 assert(isValueTypeByHwMode(true) &&
88 "The type set has multiple types for at least one HW mode");
89 ValueTypeByHwMode VVT;
Tom Stellard9ad714f2019-02-20 19:43:47 +000090 auto ASI = AddrSpaces.begin();
91
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000092 for (const auto &I : *this) {
93 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
94 VVT.getOrCreateTypeForMode(I.first, T);
Tom Stellard9ad714f2019-02-20 19:43:47 +000095 if (ASI != AddrSpaces.end())
96 VVT.PtrAddrSpace = *ASI++;
Chris Lattnercabe0372010-03-15 06:00:16 +000097 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000098 return VVT;
Bob Wilson2cd5da82009-08-11 01:14:02 +000099}
Chris Lattnercabe0372010-03-15 06:00:16 +0000100
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000101bool TypeSetByHwMode::isPossible() const {
102 for (const auto &I : *this)
103 if (!I.second.empty())
104 return true;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000105 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000106}
107
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000108bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
109 bool Changed = false;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000110 bool ContainsDefault = false;
111 MVT DT = MVT::Other;
112
Zachary Turner249dc142017-09-20 18:01:40 +0000113 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000114 for (const auto &P : VVT) {
115 unsigned M = P.first;
116 Modes.insert(M);
117 // Make sure there exists a set for each specific mode from VVT.
118 Changed |= getOrCreate(M).insert(P.second).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000119 // Cache VVT's default mode.
120 if (DefaultMode == M) {
121 ContainsDefault = true;
122 DT = P.second;
123 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000124 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000125
126 // If VVT has a default mode, add the corresponding type to all
127 // modes in "this" that do not exist in VVT.
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000128 if (ContainsDefault)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000129 for (auto &I : *this)
130 if (!Modes.count(I.first))
131 Changed |= I.second.insert(DT).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000132
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000133 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000134}
135
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000136// Constrain the type set to be the intersection with VTS.
137bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
138 bool Changed = false;
139 if (hasDefault()) {
140 for (const auto &I : VTS) {
141 unsigned M = I.first;
142 if (M == DefaultMode || hasMode(M))
143 continue;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000144 Map.insert({M, Map.at(DefaultMode)});
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000145 Changed = true;
146 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000147 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000148
149 for (auto &I : *this) {
150 unsigned M = I.first;
151 SetType &S = I.second;
152 if (VTS.hasMode(M) || VTS.hasDefault()) {
153 Changed |= intersect(I.second, VTS.get(M));
154 } else if (!S.empty()) {
155 S.clear();
156 Changed = true;
157 }
158 }
159 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000160}
161
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000162template <typename Predicate>
163bool TypeSetByHwMode::constrain(Predicate P) {
164 bool Changed = false;
165 for (auto &I : *this)
Benjamin Kramere57308e2017-09-17 11:19:53 +0000166 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000167 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000168}
169
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000170template <typename Predicate>
171bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
172 assert(empty());
173 for (const auto &I : VTS) {
174 SetType &S = getOrCreate(I.first);
175 for (auto J : I.second)
176 if (P(J))
177 S.insert(J);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000178 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000179 return !empty();
Chris Lattnercabe0372010-03-15 06:00:16 +0000180}
181
Zachary Turner249dc142017-09-20 18:01:40 +0000182void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
183 SmallVector<unsigned, 4> Modes;
184 Modes.reserve(Map.size());
Chris Lattnercabe0372010-03-15 06:00:16 +0000185
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000186 for (const auto &I : *this)
187 Modes.push_back(I.first);
Zachary Turner249dc142017-09-20 18:01:40 +0000188 if (Modes.empty()) {
189 OS << "{}";
190 return;
191 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000192 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000193
Zachary Turner249dc142017-09-20 18:01:40 +0000194 OS << '{';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000195 for (unsigned M : Modes) {
Zachary Turner249dc142017-09-20 18:01:40 +0000196 OS << ' ' << getModeName(M) << ':';
197 writeToStream(get(M), OS);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000198 }
Zachary Turner249dc142017-09-20 18:01:40 +0000199 OS << " }";
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000200}
201
Zachary Turner249dc142017-09-20 18:01:40 +0000202void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
203 SmallVector<MVT, 4> Types(S.begin(), S.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000204 array_pod_sort(Types.begin(), Types.end());
205
Zachary Turner249dc142017-09-20 18:01:40 +0000206 OS << '[';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000207 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
Zachary Turner249dc142017-09-20 18:01:40 +0000208 OS << ValueTypeByHwMode::getMVTName(Types[i]);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000209 if (i != e-1)
Zachary Turner249dc142017-09-20 18:01:40 +0000210 OS << ' ';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000211 }
Zachary Turner249dc142017-09-20 18:01:40 +0000212 OS << ']';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000213}
214
215bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
Simon Pilgrim0e181332018-08-16 16:16:28 +0000216 // The isSimple call is much quicker than hasDefault - check this first.
217 bool IsSimple = isSimple();
218 bool VTSIsSimple = VTS.isSimple();
219 if (IsSimple && VTSIsSimple)
220 return *begin() == *VTS.begin();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000221
Simon Pilgrim0e181332018-08-16 16:16:28 +0000222 // Speedup: We have a default if the set is simple.
223 bool HaveDefault = IsSimple || hasDefault();
224 bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
225 if (HaveDefault != VTSHaveDefault)
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000226 return false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000227
Zachary Turner249dc142017-09-20 18:01:40 +0000228 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000229 for (auto &I : *this)
230 Modes.insert(I.first);
231 for (const auto &I : VTS)
232 Modes.insert(I.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000233
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000234 if (HaveDefault) {
235 // Both sets have default mode.
236 for (unsigned M : Modes) {
237 if (get(M) != VTS.get(M))
David Majnemerc7004902016-08-12 04:32:37 +0000238 return false;
Craig Topper5712d462015-11-24 08:20:47 +0000239 }
Scott Michel94420742008-03-05 17:49:05 +0000240 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000241 // Neither set has default mode.
242 for (unsigned M : Modes) {
243 // If there is no default mode, an empty set is equivalent to not having
244 // the corresponding mode.
245 bool NoModeThis = !hasMode(M) || get(M).empty();
246 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
247 if (NoModeThis != NoModeVTS)
248 return false;
249 if (!NoModeThis)
250 if (get(M) != VTS.get(M))
251 return false;
252 }
Scott Michel94420742008-03-05 17:49:05 +0000253 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000254
255 return true;
Scott Michel94420742008-03-05 17:49:05 +0000256}
257
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000258namespace llvm {
259 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
260 T.writeToStream(OS);
261 return OS;
262 }
263}
264
Krzysztof Parzyszek426bf362017-09-12 15:31:26 +0000265LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000266void TypeSetByHwMode::dump() const {
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000267 dbgs() << *this << '\n';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000268}
269
270bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
271 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
272 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
273
274 if (OutP == InP)
275 return berase_if(Out, Int);
276
277 // Compute the intersection of scalars separately to account for only
278 // one set containing iPTR.
279 // The itersection of iPTR with a set of integer scalar types that does not
280 // include iPTR will result in the most specific scalar type:
281 // - iPTR is more specific than any set with two elements or more
282 // - iPTR is less specific than any single integer scalar type.
283 // For example
284 // { iPTR } * { i32 } -> { i32 }
285 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000286 // and
287 // { iPTR i32 } * { i32 } -> { i32 }
288 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
289 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000290
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000291 // Compute the difference between the two sets in such a way that the
292 // iPTR is in the set that is being subtracted. This is to see if there
293 // are any extra scalars in the set without iPTR that are not in the
294 // set containing iPTR. Then the iPTR could be considered a "wildcard"
295 // matching these scalars. If there is only one such scalar, it would
296 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000297 SetType Diff;
298 if (InP) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000299 Diff = Out;
300 berase_if(Diff, [&In](MVT T) { return In.count(T); });
301 // Pre-remove these elements and rely only on InP/OutP to determine
302 // whether a change has been made.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000303 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000304 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000305 Diff = In;
306 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000307 Out.erase(MVT::iPTR);
308 }
309
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000310 // The actual intersection.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000311 bool Changed = berase_if(Out, Int);
312 unsigned NumD = Diff.size();
313 if (NumD == 0)
314 return Changed;
315
316 if (NumD == 1) {
317 Out.insert(*Diff.begin());
318 // This is a change only if Out was the one with iPTR (which is now
319 // being replaced).
320 Changed |= OutP;
321 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000322 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000323 Out.insert(MVT::iPTR);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000324 Changed |= !OutP;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000325 }
326 return Changed;
327}
328
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000329bool TypeSetByHwMode::validate() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000330#ifndef NDEBUG
331 if (empty())
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000332 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000333 bool AllEmpty = true;
334 for (const auto &I : *this)
335 AllEmpty &= I.second.empty();
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000336 return !AllEmpty;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000337#endif
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000338 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000339}
340
341// --- TypeInfer
342
343bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
344 const TypeSetByHwMode &In) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000345 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000346 In.validate();
347 if (In.empty() || Out == In || TP.hasError())
348 return false;
349 if (Out.empty()) {
350 Out = In;
351 return true;
352 }
353
354 bool Changed = Out.constrain(In);
355 if (Changed && Out.empty())
356 TP.error("Type contradiction");
357
358 return Changed;
359}
360
361bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000362 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000363 if (TP.hasError())
364 return false;
365 assert(!Out.empty() && "cannot pick from an empty set");
366
367 bool Changed = false;
368 for (auto &I : Out) {
369 TypeSetByHwMode::SetType &S = I.second;
370 if (S.size() <= 1)
371 continue;
372 MVT T = *S.begin(); // Pick the first element.
373 S.clear();
374 S.insert(T);
375 Changed = true;
376 }
377 return Changed;
378}
379
380bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000381 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000382 if (TP.hasError())
383 return false;
384 if (!Out.empty())
385 return Out.constrain(isIntegerOrPtr);
386
387 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
388}
389
390bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000391 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000392 if (TP.hasError())
393 return false;
394 if (!Out.empty())
395 return Out.constrain(isFloatingPoint);
396
397 return Out.assign_if(getLegalTypes(), isFloatingPoint);
398}
399
400bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000401 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000402 if (TP.hasError())
403 return false;
404 if (!Out.empty())
405 return Out.constrain(isScalar);
406
407 return Out.assign_if(getLegalTypes(), isScalar);
408}
409
410bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000411 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000412 if (TP.hasError())
413 return false;
414 if (!Out.empty())
415 return Out.constrain(isVector);
416
417 return Out.assign_if(getLegalTypes(), isVector);
418}
419
420bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000421 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000422 if (TP.hasError() || !Out.empty())
423 return false;
424
425 Out = getLegalTypes();
426 return true;
427}
428
429template <typename Iter, typename Pred, typename Less>
430static Iter min_if(Iter B, Iter E, Pred P, Less L) {
431 if (B == E)
432 return E;
433 Iter Min = E;
434 for (Iter I = B; I != E; ++I) {
435 if (!P(*I))
436 continue;
437 if (Min == E || L(*I, *Min))
438 Min = I;
439 }
440 return Min;
441}
442
443template <typename Iter, typename Pred, typename Less>
444static Iter max_if(Iter B, Iter E, Pred P, Less L) {
445 if (B == E)
446 return E;
447 Iter Max = E;
448 for (Iter I = B; I != E; ++I) {
449 if (!P(*I))
450 continue;
451 if (Max == E || L(*Max, *I))
452 Max = I;
453 }
454 return Max;
455}
456
457/// Make sure that for each type in Small, there exists a larger type in Big.
458bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
459 TypeSetByHwMode &Big) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000460 ValidateOnExit _1(Small, *this), _2(Big, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000461 if (TP.hasError())
462 return false;
463 bool Changed = false;
464
465 if (Small.empty())
466 Changed |= EnforceAny(Small);
467 if (Big.empty())
468 Changed |= EnforceAny(Big);
469
470 assert(Small.hasDefault() && Big.hasDefault());
471
472 std::vector<unsigned> Modes = union_modes(Small, Big);
473
474 // 1. Only allow integer or floating point types and make sure that
475 // both sides are both integer or both floating point.
476 // 2. Make sure that either both sides have vector types, or neither
477 // of them does.
478 for (unsigned M : Modes) {
479 TypeSetByHwMode::SetType &S = Small.get(M);
480 TypeSetByHwMode::SetType &B = Big.get(M);
481
482 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000483 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000484 Changed |= berase_if(S, NotInt) |
485 berase_if(B, NotInt);
486 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000487 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000488 Changed |= berase_if(S, NotFP) |
489 berase_if(B, NotFP);
490 } else if (S.empty() || B.empty()) {
491 Changed = !S.empty() || !B.empty();
492 S.clear();
493 B.clear();
494 } else {
495 TP.error("Incompatible types");
496 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000497 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000498
499 if (none_of(S, isVector) || none_of(B, isVector)) {
500 Changed |= berase_if(S, isVector) |
501 berase_if(B, isVector);
502 }
503 }
504
505 auto LT = [](MVT A, MVT B) -> bool {
506 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
507 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
508 A.getSizeInBits() < B.getSizeInBits());
509 };
510 auto LE = [](MVT A, MVT B) -> bool {
511 // This function is used when removing elements: when a vector is compared
512 // to a non-vector, it should return false (to avoid removal).
513 if (A.isVector() != B.isVector())
514 return false;
515
516 // Note on the < comparison below:
517 // X86 has patterns like
518 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
519 // where the truncated vector is given a type v16i8, while the source
520 // vector has type v4i32. They both have the same size in bits.
521 // The minimal type in the result is obviously v16i8, and when we remove
522 // all types from the source that are smaller-or-equal than v8i16, the
523 // only source type would also be removed (since it's equal in size).
524 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
525 A.getSizeInBits() < B.getSizeInBits();
526 };
527
528 for (unsigned M : Modes) {
529 TypeSetByHwMode::SetType &S = Small.get(M);
530 TypeSetByHwMode::SetType &B = Big.get(M);
531 // MinS = min scalar in Small, remove all scalars from Big that are
532 // smaller-or-equal than MinS.
533 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000534 if (MinS != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000535 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000536
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000537 // MaxS = max scalar in Big, remove all scalars from Small that are
538 // larger than MaxS.
539 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000540 if (MaxS != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000541 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000542
543 // MinV = min vector in Small, remove all vectors from Big that are
544 // smaller-or-equal than MinV.
545 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000546 if (MinV != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000547 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000548
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000549 // MaxV = max vector in Big, remove all vectors from Small that are
550 // larger than MaxV.
551 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000552 if (MaxV != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000553 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000554 }
555
556 return Changed;
557}
558
559/// 1. Ensure that for each type T in Vec, T is a vector type, and that
560/// for each type U in Elem, U is a scalar type.
561/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
562/// type T in Vec, such that U is the element type of T.
563bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
564 TypeSetByHwMode &Elem) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000565 ValidateOnExit _1(Vec, *this), _2(Elem, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000566 if (TP.hasError())
567 return false;
568 bool Changed = false;
569
570 if (Vec.empty())
571 Changed |= EnforceVector(Vec);
572 if (Elem.empty())
573 Changed |= EnforceScalar(Elem);
574
575 for (unsigned M : union_modes(Vec, Elem)) {
576 TypeSetByHwMode::SetType &V = Vec.get(M);
577 TypeSetByHwMode::SetType &E = Elem.get(M);
578
579 Changed |= berase_if(V, isScalar); // Scalar = !vector
580 Changed |= berase_if(E, isVector); // Vector = !scalar
581 assert(!V.empty() && !E.empty());
582
583 SmallSet<MVT,4> VT, ST;
584 // Collect element types from the "vector" set.
585 for (MVT T : V)
586 VT.insert(T.getVectorElementType());
587 // Collect scalar types from the "element" set.
588 for (MVT T : E)
589 ST.insert(T);
590
591 // Remove from V all (vector) types whose element type is not in S.
592 Changed |= berase_if(V, [&ST](MVT T) -> bool {
593 return !ST.count(T.getVectorElementType());
594 });
595 // Remove from E all (scalar) types, for which there is no corresponding
596 // type in V.
597 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000598 }
599
600 return Changed;
601}
602
603bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
604 const ValueTypeByHwMode &VVT) {
605 TypeSetByHwMode Tmp(VVT);
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000606 ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000607 return EnforceVectorEltTypeIs(Vec, Tmp);
608}
609
610/// Ensure that for each type T in Sub, T is a vector type, and there
611/// exists a type U in Vec such that U is a vector type with the same
612/// element type as T and at least as many elements as T.
613bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
614 TypeSetByHwMode &Sub) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000615 ValidateOnExit _1(Vec, *this), _2(Sub, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000616 if (TP.hasError())
617 return false;
618
619 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
620 auto IsSubVec = [](MVT B, MVT P) -> bool {
621 if (!B.isVector() || !P.isVector())
622 return false;
Florian Hahn603c6452017-11-07 10:43:56 +0000623 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
624 // but until there are obvious use-cases for this, keep the
625 // types separate.
626 if (B.isScalableVector() != P.isScalableVector())
627 return false;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000628 if (B.getVectorElementType() != P.getVectorElementType())
629 return false;
630 return B.getVectorNumElements() < P.getVectorNumElements();
631 };
632
633 /// Return true if S has no element (vector type) that T is a sub-vector of,
634 /// i.e. has the same element type as T and more elements.
635 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
636 for (const auto &I : S)
637 if (IsSubVec(T, I))
638 return false;
639 return true;
640 };
641
642 /// Return true if S has no element (vector type) that T is a super-vector
643 /// of, i.e. has the same element type as T and fewer elements.
644 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
645 for (const auto &I : S)
646 if (IsSubVec(I, T))
647 return false;
648 return true;
649 };
650
651 bool Changed = false;
652
653 if (Vec.empty())
654 Changed |= EnforceVector(Vec);
655 if (Sub.empty())
656 Changed |= EnforceVector(Sub);
657
658 for (unsigned M : union_modes(Vec, Sub)) {
659 TypeSetByHwMode::SetType &S = Sub.get(M);
660 TypeSetByHwMode::SetType &V = Vec.get(M);
661
662 Changed |= berase_if(S, isScalar);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000663
664 // Erase all types from S that are not sub-vectors of a type in V.
665 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000666
667 // Erase all types from V that are not super-vectors of a type in S.
668 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000669 }
670
671 return Changed;
672}
673
674/// 1. Ensure that V has a scalar type iff W has a scalar type.
675/// 2. Ensure that for each vector type T in V, there exists a vector
676/// type U in W, such that T and U have the same number of elements.
677/// 3. Ensure that for each vector type U in W, there exists a vector
678/// type T in V, such that T and U have the same number of elements
679/// (reverse of 2).
680bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000681 ValidateOnExit _1(V, *this), _2(W, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000682 if (TP.hasError())
683 return false;
684
685 bool Changed = false;
686 if (V.empty())
687 Changed |= EnforceAny(V);
688 if (W.empty())
689 Changed |= EnforceAny(W);
690
691 // An actual vector type cannot have 0 elements, so we can treat scalars
692 // as zero-length vectors. This way both vectors and scalars can be
693 // processed identically.
694 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
695 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
696 };
697
698 for (unsigned M : union_modes(V, W)) {
699 TypeSetByHwMode::SetType &VS = V.get(M);
700 TypeSetByHwMode::SetType &WS = W.get(M);
701
702 SmallSet<unsigned,2> VN, WN;
703 for (MVT T : VS)
704 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
705 for (MVT T : WS)
706 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
707
708 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
709 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
710 }
711 return Changed;
712}
713
714/// 1. Ensure that for each type T in A, there exists a type U in B,
715/// such that T and U have equal size in bits.
716/// 2. Ensure that for each type U in B, there exists a type T in A
717/// such that T and U have equal size in bits (reverse of 1).
718bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000719 ValidateOnExit _1(A, *this), _2(B, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000720 if (TP.hasError())
721 return false;
722 bool Changed = false;
723 if (A.empty())
724 Changed |= EnforceAny(A);
725 if (B.empty())
726 Changed |= EnforceAny(B);
727
728 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
729 return !Sizes.count(T.getSizeInBits());
730 };
731
732 for (unsigned M : union_modes(A, B)) {
733 TypeSetByHwMode::SetType &AS = A.get(M);
734 TypeSetByHwMode::SetType &BS = B.get(M);
735 SmallSet<unsigned,2> AN, BN;
736
737 for (MVT T : AS)
738 AN.insert(T.getSizeInBits());
739 for (MVT T : BS)
740 BN.insert(T.getSizeInBits());
741
742 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
743 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
744 }
745
746 return Changed;
747}
748
749void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000750 ValidateOnExit _1(VTS, *this);
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000751 const TypeSetByHwMode &Legal = getLegalTypes();
752 assert(Legal.isDefaultOnly() && "Default-mode only expected");
753 const TypeSetByHwMode::SetType &LegalTypes = Legal.get(DefaultMode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000754
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000755 for (auto &I : VTS)
756 expandOverloads(I.second, LegalTypes);
Scott Michel94420742008-03-05 17:49:05 +0000757}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000758
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000759void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
760 const TypeSetByHwMode::SetType &Legal) {
761 std::set<MVT> Ovs;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000762 for (MVT T : Out) {
763 if (!T.isOverloaded())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000764 continue;
Zachary Turner249dc142017-09-20 18:01:40 +0000765
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000766 Ovs.insert(T);
767 // MachineValueTypeSet allows iteration and erasing.
768 Out.erase(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000769 }
770
771 for (MVT Ov : Ovs) {
772 switch (Ov.SimpleTy) {
773 case MVT::iPTRAny:
774 Out.insert(MVT::iPTR);
775 return;
776 case MVT::iAny:
777 for (MVT T : MVT::integer_valuetypes())
778 if (Legal.count(T))
779 Out.insert(T);
780 for (MVT T : MVT::integer_vector_valuetypes())
781 if (Legal.count(T))
782 Out.insert(T);
783 return;
784 case MVT::fAny:
785 for (MVT T : MVT::fp_valuetypes())
786 if (Legal.count(T))
787 Out.insert(T);
788 for (MVT T : MVT::fp_vector_valuetypes())
789 if (Legal.count(T))
790 Out.insert(T);
791 return;
792 case MVT::vAny:
793 for (MVT T : MVT::vector_valuetypes())
794 if (Legal.count(T))
795 Out.insert(T);
796 return;
797 case MVT::Any:
798 for (MVT T : MVT::all_valuetypes())
799 if (Legal.count(T))
800 Out.insert(T);
801 return;
802 default:
803 break;
804 }
805 }
806}
807
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000808const TypeSetByHwMode &TypeInfer::getLegalTypes() {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000809 if (!LegalTypesCached) {
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000810 TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000811 // Stuff all types from all modes into the default mode.
812 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
813 for (const auto &I : LTS)
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000814 LegalTypes.insert(I.second);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000815 LegalTypesCached = true;
816 }
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000817 assert(LegalCache.isDefaultOnly() && "Default-mode only expected");
818 return LegalCache;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000819}
Chris Lattner514e2922011-04-17 21:38:24 +0000820
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000821#ifndef NDEBUG
822TypeInfer::ValidateOnExit::~ValidateOnExit() {
Ulrich Weigand22b1af82018-07-13 16:42:15 +0000823 if (Infer.Validate && !VTS.validate()) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000824 dbgs() << "Type set is empty for each HW mode:\n"
825 "possible type contradiction in the pattern below "
826 "(use -print-records with llvm-tblgen to see all "
827 "expanded records).\n";
828 Infer.TP.dump();
829 llvm_unreachable(nullptr);
830 }
831}
832#endif
833
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000834
835//===----------------------------------------------------------------------===//
836// ScopedName Implementation
837//===----------------------------------------------------------------------===//
838
839bool ScopedName::operator==(const ScopedName &o) const {
840 return Scope == o.Scope && Identifier == o.Identifier;
841}
842
843bool ScopedName::operator!=(const ScopedName &o) const {
844 return !(*this == o);
845}
846
847
Chris Lattner514e2922011-04-17 21:38:24 +0000848//===----------------------------------------------------------------------===//
849// TreePredicateFn Implementation
850//===----------------------------------------------------------------------===//
851
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000852/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
853TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000854 assert(
855 (!hasPredCode() || !hasImmCode()) &&
856 ".td file corrupt: can't have a node predicate *and* an imm predicate");
857}
858
859bool TreePredicateFn::hasPredCode() const {
Daniel Sanders87d196c2017-11-13 22:26:13 +0000860 return isLoad() || isStore() || isAtomic() ||
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000861 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000862}
863
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000864std::string TreePredicateFn::getPredCode() const {
865 std::string Code = "";
866
Daniel Sanders87d196c2017-11-13 22:26:13 +0000867 if (!isLoad() && !isStore() && !isAtomic()) {
868 Record *MemoryVT = getMemoryVT();
869
870 if (MemoryVT)
871 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
872 "MemoryVT requires IsLoad or IsStore");
873 }
874
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000875 if (!isLoad() && !isStore()) {
876 if (isUnindexed())
877 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
878 "IsUnindexed requires IsLoad or IsStore");
879
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000880 Record *ScalarMemoryVT = getScalarMemoryVT();
881
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000882 if (ScalarMemoryVT)
883 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
884 "ScalarMemoryVT requires IsLoad or IsStore");
885 }
886
Daniel Sanders87d196c2017-11-13 22:26:13 +0000887 if (isLoad() + isStore() + isAtomic() > 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000888 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
Daniel Sanders87d196c2017-11-13 22:26:13 +0000889 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000890
891 if (isLoad()) {
892 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
893 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
894 getScalarMemoryVT() == nullptr)
895 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
896 "IsLoad cannot be used by itself");
897 } else {
898 if (isNonExtLoad())
899 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
900 "IsNonExtLoad requires IsLoad");
901 if (isAnyExtLoad())
902 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
903 "IsAnyExtLoad requires IsLoad");
904 if (isSignExtLoad())
905 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
906 "IsSignExtLoad requires IsLoad");
907 if (isZeroExtLoad())
908 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
909 "IsZeroExtLoad requires IsLoad");
910 }
911
912 if (isStore()) {
913 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
914 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
915 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
916 "IsStore cannot be used by itself");
917 } else {
918 if (isNonTruncStore())
919 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
920 "IsNonTruncStore requires IsStore");
921 if (isTruncStore())
922 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
923 "IsTruncStore requires IsStore");
924 }
925
Daniel Sanders87d196c2017-11-13 22:26:13 +0000926 if (isAtomic()) {
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000927 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
928 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
929 !isAtomicOrderingAcquireRelease() &&
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000930 !isAtomicOrderingSequentiallyConsistent() &&
931 !isAtomicOrderingAcquireOrStronger() &&
932 !isAtomicOrderingReleaseOrStronger() &&
933 !isAtomicOrderingWeakerThanAcquire() &&
934 !isAtomicOrderingWeakerThanRelease())
Daniel Sanders87d196c2017-11-13 22:26:13 +0000935 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
936 "IsAtomic cannot be used by itself");
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000937 } else {
938 if (isAtomicOrderingMonotonic())
939 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
940 "IsAtomicOrderingMonotonic requires IsAtomic");
941 if (isAtomicOrderingAcquire())
942 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
943 "IsAtomicOrderingAcquire requires IsAtomic");
944 if (isAtomicOrderingRelease())
945 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
946 "IsAtomicOrderingRelease requires IsAtomic");
947 if (isAtomicOrderingAcquireRelease())
948 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
949 "IsAtomicOrderingAcquireRelease requires IsAtomic");
950 if (isAtomicOrderingSequentiallyConsistent())
951 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
952 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000953 if (isAtomicOrderingAcquireOrStronger())
954 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
955 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
956 if (isAtomicOrderingReleaseOrStronger())
957 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
958 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
959 if (isAtomicOrderingWeakerThanAcquire())
960 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
961 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
Daniel Sanders87d196c2017-11-13 22:26:13 +0000962 }
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000963
Daniel Sanders87d196c2017-11-13 22:26:13 +0000964 if (isLoad() || isStore() || isAtomic()) {
965 StringRef SDNodeName =
966 isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
967
968 Record *MemoryVT = getMemoryVT();
969
970 if (MemoryVT)
971 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
972 MemoryVT->getName() + ") return false;\n")
973 .str();
974 }
975
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000976 if (isAtomic() && isAtomicOrderingMonotonic())
977 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
978 "AtomicOrdering::Monotonic) return false;\n";
979 if (isAtomic() && isAtomicOrderingAcquire())
980 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
981 "AtomicOrdering::Acquire) return false;\n";
982 if (isAtomic() && isAtomicOrderingRelease())
983 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
984 "AtomicOrdering::Release) return false;\n";
985 if (isAtomic() && isAtomicOrderingAcquireRelease())
986 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
987 "AtomicOrdering::AcquireRelease) return false;\n";
988 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
989 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
990 "AtomicOrdering::SequentiallyConsistent) return false;\n";
991
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000992 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
993 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
994 "return false;\n";
995 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
996 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
997 "return false;\n";
998
999 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
1000 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1001 "return false;\n";
1002 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
1003 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1004 "return false;\n";
1005
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001006 if (isLoad() || isStore()) {
1007 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
1008
1009 if (isUnindexed())
1010 Code += ("if (cast<" + SDNodeName +
1011 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1012 "return false;\n")
1013 .str();
1014
1015 if (isLoad()) {
1016 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1017 isZeroExtLoad()) > 1)
1018 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1019 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1020 "IsZeroExtLoad are mutually exclusive");
1021 if (isNonExtLoad())
1022 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1023 "ISD::NON_EXTLOAD) return false;\n";
1024 if (isAnyExtLoad())
1025 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1026 "return false;\n";
1027 if (isSignExtLoad())
1028 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1029 "return false;\n";
1030 if (isZeroExtLoad())
1031 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1032 "return false;\n";
1033 } else {
1034 if ((isNonTruncStore() + isTruncStore()) > 1)
1035 PrintFatalError(
1036 getOrigPatFragRecord()->getRecord()->getLoc(),
1037 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1038 if (isNonTruncStore())
1039 Code +=
1040 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1041 if (isTruncStore())
1042 Code +=
1043 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1044 }
1045
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001046 Record *ScalarMemoryVT = getScalarMemoryVT();
1047
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001048 if (ScalarMemoryVT)
1049 Code += ("if (cast<" + SDNodeName +
1050 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1051 ScalarMemoryVT->getName() + ") return false;\n")
1052 .str();
1053 }
1054
1055 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1056
1057 Code += PredicateCode;
1058
1059 if (PredicateCode.empty() && !Code.empty())
1060 Code += "return true;\n";
1061
1062 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +00001063}
1064
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001065bool TreePredicateFn::hasImmCode() const {
1066 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1067}
1068
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001069std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00001070 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001071}
1072
Daniel Sanders649c5852017-10-13 20:42:18 +00001073bool TreePredicateFn::immCodeUsesAPInt() const {
1074 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1075}
1076
1077bool TreePredicateFn::immCodeUsesAPFloat() const {
1078 bool Unset;
1079 // The return value will be false when IsAPFloat is unset.
1080 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1081 Unset);
1082}
1083
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001084bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1085 bool Value) const {
1086 bool Unset;
1087 bool Result =
1088 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1089 if (Unset)
1090 return false;
1091 return Result == Value;
1092}
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001093bool TreePredicateFn::usesOperands() const {
1094 return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1095}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001096bool TreePredicateFn::isLoad() const {
1097 return isPredefinedPredicateEqualTo("IsLoad", true);
1098}
1099bool TreePredicateFn::isStore() const {
1100 return isPredefinedPredicateEqualTo("IsStore", true);
1101}
Daniel Sanders87d196c2017-11-13 22:26:13 +00001102bool TreePredicateFn::isAtomic() const {
1103 return isPredefinedPredicateEqualTo("IsAtomic", true);
1104}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001105bool TreePredicateFn::isUnindexed() const {
1106 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1107}
1108bool TreePredicateFn::isNonExtLoad() const {
1109 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1110}
1111bool TreePredicateFn::isAnyExtLoad() const {
1112 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1113}
1114bool TreePredicateFn::isSignExtLoad() const {
1115 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1116}
1117bool TreePredicateFn::isZeroExtLoad() const {
1118 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1119}
1120bool TreePredicateFn::isNonTruncStore() const {
1121 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1122}
1123bool TreePredicateFn::isTruncStore() const {
1124 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1125}
Daniel Sanders6d9d30a2017-11-13 23:03:47 +00001126bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1127 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1128}
1129bool TreePredicateFn::isAtomicOrderingAcquire() const {
1130 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1131}
1132bool TreePredicateFn::isAtomicOrderingRelease() const {
1133 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1134}
1135bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1136 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1137}
1138bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1139 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1140 true);
1141}
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001142bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1143 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1144}
1145bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1146 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1147}
1148bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1149 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1150}
1151bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1152 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1153}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001154Record *TreePredicateFn::getMemoryVT() const {
1155 Record *R = getOrigPatFragRecord()->getRecord();
1156 if (R->isValueUnset("MemoryVT"))
1157 return nullptr;
1158 return R->getValueAsDef("MemoryVT");
1159}
1160Record *TreePredicateFn::getScalarMemoryVT() const {
1161 Record *R = getOrigPatFragRecord()->getRecord();
1162 if (R->isValueUnset("ScalarMemoryVT"))
1163 return nullptr;
1164 return R->getValueAsDef("ScalarMemoryVT");
1165}
Daniel Sanders8ead1292018-06-15 23:13:43 +00001166bool TreePredicateFn::hasGISelPredicateCode() const {
1167 return !PatFragRec->getRecord()
1168 ->getValueAsString("GISelPredicateCode")
1169 .empty();
1170}
1171std::string TreePredicateFn::getGISelPredicateCode() const {
1172 return PatFragRec->getRecord()->getValueAsString("GISelPredicateCode");
1173}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001174
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001175StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001176 if (immCodeUsesAPInt())
1177 return "const APInt &";
1178 if (immCodeUsesAPFloat())
1179 return "const APFloat &";
1180 return "int64_t";
1181}
Chris Lattner514e2922011-04-17 21:38:24 +00001182
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001183StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001184 if (immCodeUsesAPInt())
1185 return "APInt";
1186 else if (immCodeUsesAPFloat())
1187 return "APFloat";
1188 return "I64";
1189}
1190
Chris Lattner514e2922011-04-17 21:38:24 +00001191/// isAlwaysTrue - Return true if this is a noop predicate.
1192bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001193 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001194}
1195
1196/// Return the name to use in the generated code to reference this, this is
1197/// "Predicate_foo" if from a pattern fragment "foo".
1198std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001199 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001200}
1201
1202/// getCodeToRunOnSDNode - Return the code for the function body that
1203/// evaluates this predicate. The argument is expected to be in "Node",
1204/// not N. This handles casting and conversion to a concrete node type as
1205/// appropriate.
1206std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001207 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001208 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001209 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001210 if (isLoad())
1211 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1212 "IsLoad cannot be used with ImmLeaf or its subclasses");
1213 if (isStore())
1214 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1215 "IsStore cannot be used with ImmLeaf or its subclasses");
1216 if (isUnindexed())
1217 PrintFatalError(
1218 getOrigPatFragRecord()->getRecord()->getLoc(),
1219 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1220 if (isNonExtLoad())
1221 PrintFatalError(
1222 getOrigPatFragRecord()->getRecord()->getLoc(),
1223 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1224 if (isAnyExtLoad())
1225 PrintFatalError(
1226 getOrigPatFragRecord()->getRecord()->getLoc(),
1227 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1228 if (isSignExtLoad())
1229 PrintFatalError(
1230 getOrigPatFragRecord()->getRecord()->getLoc(),
1231 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1232 if (isZeroExtLoad())
1233 PrintFatalError(
1234 getOrigPatFragRecord()->getRecord()->getLoc(),
1235 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1236 if (isNonTruncStore())
1237 PrintFatalError(
1238 getOrigPatFragRecord()->getRecord()->getLoc(),
1239 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1240 if (isTruncStore())
1241 PrintFatalError(
1242 getOrigPatFragRecord()->getRecord()->getLoc(),
1243 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1244 if (getMemoryVT())
1245 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1246 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1247 if (getScalarMemoryVT())
1248 PrintFatalError(
1249 getOrigPatFragRecord()->getRecord()->getLoc(),
1250 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1251
1252 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001253 if (immCodeUsesAPFloat())
1254 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1255 else if (immCodeUsesAPInt())
1256 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1257 else
1258 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001259 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001260 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001261
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001262 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001263 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001264 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +00001265 if (PatFragRec->getOnlyTree()->isLeaf())
1266 ClassName = "SDNode";
1267 else {
1268 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1269 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1270 }
1271 std::string Result;
1272 if (ClassName == "SDNode")
1273 Result = " SDNode *N = Node;\n";
1274 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001275 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001276
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001277 return (Twine(Result) + " (void)N;\n" + getPredCode()).str();
Scott Michel94420742008-03-05 17:49:05 +00001278}
1279
Chris Lattner8cab0212008-01-05 22:25:12 +00001280//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001281// PatternToMatch implementation
1282//
1283
Chris Lattner05925fe2010-03-29 01:40:38 +00001284/// getPatternSize - Return the 'size' of this pattern. We want to match large
1285/// patterns before small ones. This is used to determine the size of a
1286/// pattern.
Florian Hahn6b1db822018-06-14 20:32:58 +00001287static unsigned getPatternSize(const TreePatternNode *P,
Chris Lattner05925fe2010-03-29 01:40:38 +00001288 const CodeGenDAGPatterns &CGP) {
1289 unsigned Size = 3; // The node itself.
1290 // If the root node is a ConstantSDNode, increases its size.
1291 // e.g. (set R32:$dst, 0).
Florian Hahn6b1db822018-06-14 20:32:58 +00001292 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001293 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001294
Florian Hahn6b1db822018-06-14 20:32:58 +00001295 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001296 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001297 // We don't want to count any children twice, so return early.
1298 return Size;
1299 }
1300
Chris Lattner05925fe2010-03-29 01:40:38 +00001301 // If this node has some predicate function that must match, it adds to the
1302 // complexity of this node.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001303 if (!P->getPredicateCalls().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001304 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001305
Chris Lattner05925fe2010-03-29 01:40:38 +00001306 // Count children in the count if they are also nodes.
Florian Hahn6b1db822018-06-14 20:32:58 +00001307 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1308 const TreePatternNode *Child = P->getChild(i);
1309 if (!Child->isLeaf() && Child->getNumTypes()) {
Simon Pilgrimc3c14412018-08-15 20:41:19 +00001310 const TypeSetByHwMode &T0 = Child->getExtType(0);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001311 // At this point, all variable type sets should be simple, i.e. only
1312 // have a default mode.
1313 if (T0.getMachineValueType() != MVT::Other) {
1314 Size += getPatternSize(Child, CGP);
1315 continue;
1316 }
1317 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001318 if (Child->isLeaf()) {
1319 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001320 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Florian Hahn6b1db822018-06-14 20:32:58 +00001321 else if (Child->getComplexPatternInfo(CGP))
Chris Lattner05925fe2010-03-29 01:40:38 +00001322 Size += getPatternSize(Child, CGP);
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001323 else if (!Child->getPredicateCalls().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001324 ++Size;
1325 }
1326 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001327
Chris Lattner05925fe2010-03-29 01:40:38 +00001328 return Size;
1329}
1330
1331/// Compute the complexity metric for the input pattern. This roughly
1332/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001333int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001334getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001335 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
Chris Lattner05925fe2010-03-29 01:40:38 +00001336}
1337
Dan Gohman49e19e92008-08-22 00:20:26 +00001338/// getPredicateCheck - Return a single string containing all of this
1339/// pattern's predicates concatenated with "&&" operators.
1340///
1341std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001342 SmallVector<const Predicate*,4> PredList;
1343 for (const Predicate &P : Predicates)
1344 PredList.push_back(&P);
Fangrui Song0cac7262018-09-27 02:13:45 +00001345 llvm::sort(PredList, deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +00001346
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001347 std::string Check;
1348 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1349 if (i != 0)
1350 Check += " && ";
1351 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001352 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001353 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001354}
1355
1356//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001357// SDTypeConstraint implementation
1358//
1359
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001360SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001361 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001362
Chris Lattner8cab0212008-01-05 22:25:12 +00001363 if (R->isSubClassOf("SDTCisVT")) {
1364 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001365 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1366 for (const auto &P : VVT)
1367 if (P.second == MVT::isVoid)
1368 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001369 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1370 ConstraintType = SDTCisPtrTy;
1371 } else if (R->isSubClassOf("SDTCisInt")) {
1372 ConstraintType = SDTCisInt;
1373 } else if (R->isSubClassOf("SDTCisFP")) {
1374 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001375 } else if (R->isSubClassOf("SDTCisVec")) {
1376 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001377 } else if (R->isSubClassOf("SDTCisSameAs")) {
1378 ConstraintType = SDTCisSameAs;
1379 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1380 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1381 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001382 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001383 R->getValueAsInt("OtherOperandNum");
1384 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1385 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001386 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001387 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001388 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1389 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001390 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001391 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1392 ConstraintType = SDTCisSubVecOfVec;
1393 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1394 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001395 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1396 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001397 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1398 for (const auto &P : VVT) {
1399 MVT T = P.second;
1400 if (T.isVector())
1401 PrintFatalError(R->getLoc(),
1402 "Cannot use vector type as SDTCVecEltisVT");
1403 if (!T.isInteger() && !T.isFloatingPoint())
1404 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1405 "as SDTCVecEltisVT");
1406 }
Craig Topper0be34582015-03-05 07:11:34 +00001407 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1408 ConstraintType = SDTCisSameNumEltsAs;
1409 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1410 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001411 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1412 ConstraintType = SDTCisSameSizeAs;
1413 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1414 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001415 } else {
Daniel Sandersdff673b2019-02-12 17:36:57 +00001416 PrintFatalError(R->getLoc(),
1417 "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001418 }
1419}
1420
1421/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001422/// N, and the result number in ResNo.
Florian Hahn6b1db822018-06-14 20:32:58 +00001423static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
Chris Lattner2db7aba2010-03-19 21:56:21 +00001424 const SDNodeInfo &NodeInfo,
1425 unsigned &ResNo) {
1426 unsigned NumResults = NodeInfo.getNumResults();
1427 if (OpNo < NumResults) {
1428 ResNo = OpNo;
1429 return N;
1430 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001431
Chris Lattner2db7aba2010-03-19 21:56:21 +00001432 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001433
Florian Hahn6b1db822018-06-14 20:32:58 +00001434 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001435 std::string S;
1436 raw_string_ostream OS(S);
1437 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001438 << (OpNo+NumResults) << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001439 N->print(OS);
James Y Knighte452e272015-05-11 22:17:13 +00001440 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001441 }
1442
Florian Hahn6b1db822018-06-14 20:32:58 +00001443 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001444}
1445
1446/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1447/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001448/// change, false otherwise. If a type contradiction is found, flag an error.
Florian Hahn6b1db822018-06-14 20:32:58 +00001449bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
Chris Lattner8cab0212008-01-05 22:25:12 +00001450 const SDNodeInfo &NodeInfo,
1451 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001452 if (TP.hasError())
1453 return false;
1454
Chris Lattner2db7aba2010-03-19 21:56:21 +00001455 unsigned ResNo = 0; // The result number being referenced.
Florian Hahn6b1db822018-06-14 20:32:58 +00001456 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001457 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001458
Chris Lattner8cab0212008-01-05 22:25:12 +00001459 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001460 case SDTCisVT:
1461 // Operand must be a particular type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001462 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001463 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001464 // Operand must be same as target pointer type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001465 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001466 case SDTCisInt:
1467 // Require it to be one of the legal integer VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001468 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001469 case SDTCisFP:
1470 // Require it to be one of the legal fp VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001471 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001472 case SDTCisVec:
1473 // Require it to be one of the legal vector VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001474 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001475 case SDTCisSameAs: {
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.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001479 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1480 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001481 }
1482 case SDTCisVTSmallerThanOp: {
1483 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1484 // have an integer type that is smaller than the VT.
Florian Hahn6b1db822018-06-14 20:32:58 +00001485 if (!NodeToApply->isLeaf() ||
1486 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1487 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001488 ->isSubClassOf("ValueType")) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001489 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001490 return false;
1491 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001492 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001493 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1494 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1495 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001496
Chris Lattner2db7aba2010-03-19 21:56:21 +00001497 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001498 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001499 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1500 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001501
Florian Hahn6b1db822018-06-14 20:32:58 +00001502 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001503 }
1504 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001505 unsigned BResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001506 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001507 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1508 BResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001509 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1510 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001511 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001512 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001513 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001514 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001515 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1516 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001517 // Filter vector types out of VecOperand that don't have the right element
1518 // type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001519 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1520 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001521 }
David Greene127fd1d2011-01-24 20:53:18 +00001522 case SDTCisSubVecOfVec: {
1523 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001524 TreePatternNode *BigVecOperand =
David Greene127fd1d2011-01-24 20:53:18 +00001525 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1526 VResNo);
1527
1528 // Filter vector types out of BigVecOperand that don't have the
1529 // right subvector type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001530 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1531 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001532 }
Craig Topper0be34582015-03-05 07:11:34 +00001533 case SDTCVecEltisVT: {
Florian Hahn6b1db822018-06-14 20:32:58 +00001534 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001535 }
1536 case SDTCisSameNumEltsAs: {
1537 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001538 TreePatternNode *OtherNode =
Craig Topper0be34582015-03-05 07:11:34 +00001539 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1540 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001541 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1542 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001543 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001544 case SDTCisSameSizeAs: {
1545 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001546 TreePatternNode *OtherNode =
Craig Topper9a44b3f2015-11-26 07:02:18 +00001547 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1548 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001549 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1550 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001551 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001552 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001553 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001554}
1555
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001556// Update the node type to match an instruction operand or result as specified
1557// in the ins or outs lists on the instruction definition. Return true if the
1558// type was actually changed.
1559bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1560 Record *Operand,
1561 TreePattern &TP) {
1562 // The 'unknown' operand indicates that types should be inferred from the
1563 // context.
1564 if (Operand->isSubClassOf("unknown_class"))
1565 return false;
1566
1567 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001568 if (Operand->isSubClassOf("Operand")) {
1569 Record *R = Operand->getValueAsDef("Type");
1570 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1571 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1572 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001573
1574 // PointerLikeRegClass has a type that is determined at runtime.
1575 if (Operand->isSubClassOf("PointerLikeRegClass"))
1576 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1577
1578 // Both RegisterClass and RegisterOperand operands derive their types from a
1579 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001580 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001581 if (Operand->isSubClassOf("RegisterClass"))
1582 RC = Operand;
1583 else if (Operand->isSubClassOf("RegisterOperand"))
1584 RC = Operand->getValueAsDef("RegClass");
1585
1586 assert(RC && "Unknown operand type");
1587 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1588 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1589}
1590
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001591bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1592 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1593 if (!TP.getInfer().isConcrete(Types[i], true))
1594 return true;
1595 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001596 if (getChild(i)->ContainsUnresolvedType(TP))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001597 return true;
1598 return false;
1599}
1600
1601bool TreePatternNode::hasProperTypeByHwMode() const {
1602 for (const TypeSetByHwMode &S : Types)
1603 if (!S.isDefaultOnly())
1604 return true;
Florian Hahn75e87c32018-05-30 21:00:18 +00001605 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001606 if (C->hasProperTypeByHwMode())
1607 return true;
1608 return false;
1609}
1610
1611bool TreePatternNode::hasPossibleType() const {
1612 for (const TypeSetByHwMode &S : Types)
1613 if (!S.isPossible())
1614 return false;
Florian Hahn75e87c32018-05-30 21:00:18 +00001615 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001616 if (!C->hasPossibleType())
1617 return false;
1618 return true;
1619}
1620
1621bool TreePatternNode::setDefaultMode(unsigned Mode) {
1622 for (TypeSetByHwMode &S : Types) {
1623 S.makeSimple(Mode);
1624 // Check if the selected mode had a type conflict.
1625 if (S.get(DefaultMode).empty())
1626 return false;
1627 }
Florian Hahn75e87c32018-05-30 21:00:18 +00001628 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001629 if (!C->setDefaultMode(Mode))
1630 return false;
1631 return true;
1632}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001633
Chris Lattner8cab0212008-01-05 22:25:12 +00001634//===----------------------------------------------------------------------===//
1635// SDNodeInfo implementation
1636//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001637SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001638 EnumName = R->getValueAsString("Opcode");
1639 SDClassName = R->getValueAsString("SDClass");
1640 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1641 NumResults = TypeProfile->getValueAsInt("NumResults");
1642 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001643
Chris Lattner8cab0212008-01-05 22:25:12 +00001644 // Parse the properties.
Matt Arsenault303327d2017-12-20 19:36:28 +00001645 Properties = parseSDPatternOperatorProperties(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001646
Chris Lattner8cab0212008-01-05 22:25:12 +00001647 // Parse the type constraints.
1648 std::vector<Record*> ConstraintList =
1649 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001650 for (Record *R : ConstraintList)
1651 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001652}
1653
Chris Lattner99e53b32010-02-28 00:22:30 +00001654/// getKnownType - If the type constraints on this node imply a fixed type
1655/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001656/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001657MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001658 unsigned NumResults = getNumResults();
1659 assert(NumResults <= 1 &&
1660 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001661 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001662
Craig Topper306cb122015-11-22 20:46:24 +00001663 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001664 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001665 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001666 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001667
Craig Topper306cb122015-11-22 20:46:24 +00001668 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001669 default: break;
1670 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001671 if (Constraint.VVT.isSimple())
1672 return Constraint.VVT.getSimple().SimpleTy;
1673 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001674 case SDTypeConstraint::SDTCisPtrTy:
1675 return MVT::iPTR;
1676 }
1677 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001678 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001679}
1680
Chris Lattner8cab0212008-01-05 22:25:12 +00001681//===----------------------------------------------------------------------===//
1682// TreePatternNode implementation
1683//
1684
Chris Lattnerf1447252010-03-19 21:37:09 +00001685static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1686 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001687 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001688 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001689
Chris Lattner2109cb42010-03-22 20:56:36 +00001690 if (Operator->isSubClassOf("Intrinsic"))
1691 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001692
Chris Lattnerf1447252010-03-19 21:37:09 +00001693 if (Operator->isSubClassOf("SDNode"))
1694 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001695
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001696 if (Operator->isSubClassOf("PatFrags")) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001697 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1698 // the forward reference case where one pattern fragment references another
1699 // before it is processed.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001700 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1701 // The number of results of a fragment with alternative records is the
1702 // maximum number of results across all alternatives.
1703 unsigned NumResults = 0;
1704 for (auto T : PFRec->getTrees())
1705 NumResults = std::max(NumResults, T->getNumTypes());
1706 return NumResults;
1707 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001708
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001709 ListInit *LI = Operator->getValueAsListInit("Fragments");
1710 assert(LI && "Invalid Fragment");
1711 unsigned NumResults = 0;
1712 for (Init *I : LI->getValues()) {
1713 Record *Op = nullptr;
1714 if (DagInit *Dag = dyn_cast<DagInit>(I))
1715 if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1716 Op = DI->getDef();
1717 assert(Op && "Invalid Fragment");
1718 NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1719 }
1720 return NumResults;
Chris Lattnerf1447252010-03-19 21:37:09 +00001721 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001722
Chris Lattnerf1447252010-03-19 21:37:09 +00001723 if (Operator->isSubClassOf("Instruction")) {
1724 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001725
Craig Topper3a8eb892015-03-20 05:09:06 +00001726 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1727
1728 // Subtract any defaulted outputs.
1729 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1730 Record *OperandNode = InstInfo.Operands[i].Rec;
1731
1732 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1733 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1734 --NumDefsToAdd;
1735 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001736
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001737 // Add on one implicit def if it has a resolvable type.
1738 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1739 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001740 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001741 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001742
Chris Lattnerf1447252010-03-19 21:37:09 +00001743 if (Operator->isSubClassOf("SDNodeXForm"))
1744 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001745
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001746 if (Operator->isSubClassOf("ValueType"))
1747 return 1; // A type-cast of one result.
1748
Tim Northoverc807a172014-05-20 11:52:46 +00001749 if (Operator->isSubClassOf("ComplexPattern"))
1750 return 1;
1751
Matthias Braun8c209aa2017-01-28 02:02:38 +00001752 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001753 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001754}
1755
1756void TreePatternNode::print(raw_ostream &OS) const {
1757 if (isLeaf())
1758 OS << *getLeafValue();
1759 else
1760 OS << '(' << getOperator()->getName();
1761
Zachary Turner249dc142017-09-20 18:01:40 +00001762 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1763 OS << ':';
1764 getExtType(i).writeToStream(OS);
1765 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001766
1767 if (!isLeaf()) {
1768 if (getNumChildren() != 0) {
1769 OS << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001770 getChild(0)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001771 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1772 OS << ", ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001773 getChild(i)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001774 }
1775 }
1776 OS << ")";
1777 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001778
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001779 for (const TreePredicateCall &Pred : PredicateCalls) {
1780 OS << "<<P:";
1781 if (Pred.Scope)
1782 OS << Pred.Scope << ":";
1783 OS << Pred.Fn.getFnName() << ">>";
1784 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001785 if (TransformFn)
1786 OS << "<<X:" << TransformFn->getName() << ">>";
1787 if (!getName().empty())
1788 OS << ":$" << getName();
1789
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001790 for (const ScopedName &Name : NamesAsPredicateArg)
1791 OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
Chris Lattner8cab0212008-01-05 22:25:12 +00001792}
1793void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001794 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001795}
1796
Scott Michel94420742008-03-05 17:49:05 +00001797/// isIsomorphicTo - Return true if this node is recursively
1798/// isomorphic to the specified node. For this comparison, the node's
1799/// entire state is considered. The assigned name is ignored, since
1800/// nodes with differing names are considered isomorphic. However, if
1801/// the assigned name is present in the dependent variable set, then
1802/// the assigned name is considered significant and the node is
1803/// isomorphic if the names match.
Florian Hahn6b1db822018-06-14 20:32:58 +00001804bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
Scott Michel94420742008-03-05 17:49:05 +00001805 const MultipleUseVarSet &DepVars) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001806 if (N == this) return true;
1807 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001808 getPredicateCalls() != N->getPredicateCalls() ||
Florian Hahn6b1db822018-06-14 20:32:58 +00001809 getTransformFn() != N->getTransformFn())
Chris Lattner8cab0212008-01-05 22:25:12 +00001810 return false;
1811
1812 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001813 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001814 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001815 return ((DI->getDef() == NDI->getDef())
1816 && (DepVars.find(getName()) == DepVars.end()
Florian Hahn6b1db822018-06-14 20:32:58 +00001817 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001818 }
1819 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001820 return getLeafValue() == N->getLeafValue();
Chris Lattner8cab0212008-01-05 22:25:12 +00001821 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001822
Florian Hahn6b1db822018-06-14 20:32:58 +00001823 if (N->getOperator() != getOperator() ||
1824 N->getNumChildren() != getNumChildren()) return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001825 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001826 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001827 return false;
1828 return true;
1829}
1830
1831/// clone - Make a copy of this tree and all of its children.
1832///
Florian Hahn75e87c32018-05-30 21:00:18 +00001833TreePatternNodePtr TreePatternNode::clone() const {
1834 TreePatternNodePtr New;
Chris Lattner8cab0212008-01-05 22:25:12 +00001835 if (isLeaf()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001836 New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001837 } else {
Florian Hahn75e87c32018-05-30 21:00:18 +00001838 std::vector<TreePatternNodePtr> CChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00001839 CChildren.reserve(Children.size());
1840 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001841 CChildren.push_back(getChild(i)->clone());
Craig Topper26fc06352018-07-15 06:52:49 +00001842 New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
Florian Hahn75e87c32018-05-30 21:00:18 +00001843 getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001844 }
1845 New->setName(getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001846 New->setNamesAsPredicateArg(getNamesAsPredicateArg());
Chris Lattnerf1447252010-03-19 21:37:09 +00001847 New->Types = Types;
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001848 New->setPredicateCalls(getPredicateCalls());
Chris Lattner8cab0212008-01-05 22:25:12 +00001849 New->setTransformFn(getTransformFn());
1850 return New;
1851}
1852
Chris Lattner53c39ba2010-02-14 22:22:58 +00001853/// RemoveAllTypes - Recursively strip all the types of this tree.
1854void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001855 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001856 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001857 if (isLeaf()) return;
1858 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001859 getChild(i)->RemoveAllTypes();
Chris Lattner53c39ba2010-02-14 22:22:58 +00001860}
1861
1862
Chris Lattner8cab0212008-01-05 22:25:12 +00001863/// SubstituteFormalArguments - Replace the formal arguments in this tree
1864/// with actual values specified by ArgMap.
Florian Hahn75e87c32018-05-30 21:00:18 +00001865void TreePatternNode::SubstituteFormalArguments(
1866 std::map<std::string, TreePatternNodePtr> &ArgMap) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001867 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001868
Chris Lattner8cab0212008-01-05 22:25:12 +00001869 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001870 TreePatternNode *Child = getChild(i);
1871 if (Child->isLeaf()) {
1872 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001873 // Note that, when substituting into an output pattern, Val might be an
1874 // UnsetInit.
1875 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1876 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001877 // We found a use of a formal argument, replace it with its value.
Florian Hahn6b1db822018-06-14 20:32:58 +00001878 TreePatternNodePtr NewChild = ArgMap[Child->getName()];
Dan Gohman6e979022008-10-15 06:17:21 +00001879 assert(NewChild && "Couldn't find formal argument!");
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001880 assert((Child->getPredicateCalls().empty() ||
1881 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Dan Gohman6e979022008-10-15 06:17:21 +00001882 "Non-empty child predicate clobbered!");
Florian Hahn0a2e0b62018-06-14 11:56:19 +00001883 setChild(i, std::move(NewChild));
Chris Lattner8cab0212008-01-05 22:25:12 +00001884 }
1885 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00001886 getChild(i)->SubstituteFormalArguments(ArgMap);
Chris Lattner8cab0212008-01-05 22:25:12 +00001887 }
1888 }
1889}
1890
1891
1892/// InlinePatternFragments - If this pattern refers to any pattern
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001893/// fragments, return the set of inlined versions (this can be more than
1894/// one if a PatFrags record has multiple alternatives).
1895void TreePatternNode::InlinePatternFragments(
1896 TreePatternNodePtr T, TreePattern &TP,
1897 std::vector<TreePatternNodePtr> &OutAlternatives) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001898
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001899 if (TP.hasError())
1900 return;
1901
1902 if (isLeaf()) {
1903 OutAlternatives.push_back(T); // nothing to do.
1904 return;
1905 }
1906
Chris Lattner8cab0212008-01-05 22:25:12 +00001907 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001908
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001909 if (!Op->isSubClassOf("PatFrags")) {
1910 if (getNumChildren() == 0) {
1911 OutAlternatives.push_back(T);
1912 return;
1913 }
1914
1915 // Recursively inline children nodes.
1916 std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
1917 ChildAlternatives.resize(getNumChildren());
Dan Gohman6e979022008-10-15 06:17:21 +00001918 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001919 TreePatternNodePtr Child = getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001920 Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
1921 // If there are no alternatives for any child, there are no
1922 // alternatives for this expression as whole.
1923 if (ChildAlternatives[i].empty())
1924 return;
Dan Gohman6e979022008-10-15 06:17:21 +00001925
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001926 for (auto NewChild : ChildAlternatives[i])
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001927 assert((Child->getPredicateCalls().empty() ||
1928 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001929 "Non-empty child predicate clobbered!");
Dan Gohman6e979022008-10-15 06:17:21 +00001930 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001931
1932 // The end result is an all-pairs construction of the resultant pattern.
1933 std::vector<unsigned> Idxs;
1934 Idxs.resize(ChildAlternatives.size());
1935 bool NotDone;
1936 do {
1937 // Create the variant and add it to the output list.
1938 std::vector<TreePatternNodePtr> NewChildren;
1939 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
1940 NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
1941 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00001942 getOperator(), std::move(NewChildren), getNumTypes());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001943
1944 // Copy over properties.
1945 R->setName(getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001946 R->setNamesAsPredicateArg(getNamesAsPredicateArg());
1947 R->setPredicateCalls(getPredicateCalls());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001948 R->setTransformFn(getTransformFn());
1949 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
1950 R->setType(i, getExtType(i));
Craig Topperbd199f82018-12-05 00:47:59 +00001951 for (unsigned i = 0, e = getNumResults(); i != e; ++i)
1952 R->setResultIndex(i, getResultIndex(i));
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001953
1954 // Register alternative.
1955 OutAlternatives.push_back(R);
1956
1957 // Increment indices to the next permutation by incrementing the
1958 // indices from last index backward, e.g., generate the sequence
1959 // [0, 0], [0, 1], [1, 0], [1, 1].
1960 int IdxsIdx;
1961 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
1962 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
1963 Idxs[IdxsIdx] = 0;
1964 else
1965 break;
1966 }
1967 NotDone = (IdxsIdx >= 0);
1968 } while (NotDone);
1969
1970 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001971 }
1972
1973 // Otherwise, we found a reference to a fragment. First, look up its
1974 // TreePattern record.
1975 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001976
Chris Lattner8cab0212008-01-05 22:25:12 +00001977 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001978 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001979 TP.error("'" + Op->getName() + "' fragment requires " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001980 Twine(Frag->getNumArgs()) + " operands!");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001981 return;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001982 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001983
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001984 TreePredicateFn PredFn(Frag);
1985 unsigned Scope = 0;
1986 if (TreePredicateFn(Frag).usesOperands())
1987 Scope = TP.getDAGPatterns().allocateScope();
1988
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001989 // Compute the map of formal to actual arguments.
1990 std::map<std::string, TreePatternNodePtr> ArgMap;
1991 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001992 TreePatternNodePtr Child = getChildShared(i);
1993 if (Scope != 0) {
1994 Child = Child->clone();
1995 Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
1996 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001997 ArgMap[Frag->getArgName(i)] = Child;
Chris Lattner8cab0212008-01-05 22:25:12 +00001998 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001999
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002000 // Loop over all fragment alternatives.
2001 for (auto Alternative : Frag->getTrees()) {
2002 TreePatternNodePtr FragTree = Alternative->clone();
Dan Gohman6e979022008-10-15 06:17:21 +00002003
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002004 if (!PredFn.isAlwaysTrue())
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002005 FragTree->addPredicateCall(PredFn, Scope);
Dan Gohman6e979022008-10-15 06:17:21 +00002006
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002007 // Resolve formal arguments to their actual value.
2008 if (Frag->getNumArgs())
2009 FragTree->SubstituteFormalArguments(ArgMap);
2010
2011 // Transfer types. Note that the resolved alternative may have fewer
2012 // (but not more) results than the PatFrags node.
2013 FragTree->setName(getName());
2014 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2015 FragTree->UpdateNodeType(i, getExtType(i), TP);
2016
2017 // Transfer in the old predicates.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002018 for (const TreePredicateCall &Pred : getPredicateCalls())
2019 FragTree->addPredicateCall(Pred);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002020
2021 // The fragment we inlined could have recursive inlining that is needed. See
2022 // if there are any pattern fragments in it and inline them as needed.
2023 FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
2024 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002025}
2026
2027/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00002028/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00002029/// references from the register file information, for example.
2030///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002031/// When Unnamed is set, return the type of a DAG operand with no name, such as
2032/// the F8RC register class argument in:
2033///
2034/// (COPY_TO_REGCLASS GPR:$src, F8RC)
2035///
2036/// When Unnamed is false, return the type of a named DAG operand such as the
2037/// GPR:$src operand above.
2038///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002039static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2040 bool NotRegisters,
2041 bool Unnamed,
2042 TreePattern &TP) {
2043 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2044
Owen Andersona84be6c2011-06-27 21:06:21 +00002045 // Check to see if this is a register operand.
2046 if (R->isSubClassOf("RegisterOperand")) {
2047 assert(ResNo == 0 && "Regoperand ref only has one result!");
2048 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002049 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00002050 Record *RegClass = R->getValueAsDef("RegClass");
2051 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002052 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00002053 }
2054
Chris Lattnercabe0372010-03-15 06:00:16 +00002055 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00002056 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002057 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002058 // An unnamed register class represents itself as an i32 immediate, for
2059 // example on a COPY_TO_REGCLASS instruction.
2060 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002061 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002062
2063 // In a named operand, the register class provides the possible set of
2064 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002065 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002066 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00002067 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002068 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00002069 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002070
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002071 if (R->isSubClassOf("PatFrags")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002072 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002073 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002074 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00002075 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002076
Chris Lattner6070ee22010-03-23 23:50:31 +00002077 if (R->isSubClassOf("Register")) {
2078 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002079 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002080 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002081 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002082 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00002083 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002084
2085 if (R->isSubClassOf("SubRegIndex")) {
2086 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002087 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002088 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002089
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002090 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002091 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002092 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2093 //
2094 // (sext_inreg GPR:$src, i16)
2095 // ~~~
2096 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002097 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002098 // With a name, the ValueType simply provides the type of the named
2099 // variable.
2100 //
2101 // (sext_inreg i32:$src, i16)
2102 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002103 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002104 return TypeSetByHwMode(); // Unknown.
2105 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2106 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002107 }
2108
2109 if (R->isSubClassOf("CondCode")) {
2110 assert(ResNo == 0 && "This node only has one result!");
2111 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002112 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00002113 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002114
Chris Lattner6070ee22010-03-23 23:50:31 +00002115 if (R->isSubClassOf("ComplexPattern")) {
2116 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002117 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002118 return TypeSetByHwMode(); // Unknown.
2119 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00002120 }
2121 if (R->isSubClassOf("PointerLikeRegClass")) {
2122 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002123 TypeSetByHwMode VTS(MVT::iPTR);
2124 TP.getInfer().expandOverloads(VTS);
2125 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00002126 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002127
Chris Lattner6070ee22010-03-23 23:50:31 +00002128 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2129 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002130 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002131 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002132 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002133
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002134 if (R->isSubClassOf("Operand")) {
2135 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2136 Record *T = R->getValueAsDef("Type");
2137 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2138 }
Tim Northoverc807a172014-05-20 11:52:46 +00002139
Chris Lattner8cab0212008-01-05 22:25:12 +00002140 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002141 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00002142}
2143
Chris Lattner89c65662008-01-06 05:36:50 +00002144
2145/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2146/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2147const CodeGenIntrinsic *TreePatternNode::
2148getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2149 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2150 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2151 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00002152 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002153
Florian Hahn6b1db822018-06-14 20:32:58 +00002154 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00002155 return &CDP.getIntrinsicInfo(IID);
2156}
2157
Chris Lattner53c39ba2010-02-14 22:22:58 +00002158/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2159/// return the ComplexPattern information, otherwise return null.
2160const ComplexPattern *
2161TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00002162 Record *Rec;
2163 if (isLeaf()) {
2164 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2165 if (!DI)
2166 return nullptr;
2167 Rec = DI->getDef();
2168 } else
2169 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002170
Tim Northoverc807a172014-05-20 11:52:46 +00002171 if (!Rec->isSubClassOf("ComplexPattern"))
2172 return nullptr;
2173 return &CGP.getComplexPattern(Rec);
2174}
2175
2176unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2177 // A ComplexPattern specifically declares how many results it fills in.
2178 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2179 return CP->getNumOperands();
2180
2181 // If MIOperandInfo is specified, that gives the count.
2182 if (isLeaf()) {
2183 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2184 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2185 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2186 if (MIOps->getNumArgs())
2187 return MIOps->getNumArgs();
2188 }
2189 }
2190
2191 // Otherwise there is just one result.
2192 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00002193}
2194
2195/// NodeHasProperty - Return true if this node has the specified property.
2196bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002197 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002198 if (isLeaf()) {
2199 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2200 return CP->hasProperty(Property);
Matt Arsenault303327d2017-12-20 19:36:28 +00002201
Chris Lattner53c39ba2010-02-14 22:22:58 +00002202 return false;
2203 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002204
Matt Arsenault303327d2017-12-20 19:36:28 +00002205 if (Property != SDNPHasChain) {
2206 // The chain proprety is already present on the different intrinsic node
2207 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2208 // on the intrinsic. Anything else is specific to the individual intrinsic.
2209 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2210 return Int->hasProperty(Property);
2211 }
2212
2213 if (!Operator->isSubClassOf("SDPatternOperator"))
2214 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002215
Chris Lattner53c39ba2010-02-14 22:22:58 +00002216 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2217}
2218
2219
2220
2221
2222/// TreeHasProperty - Return true if any node in this tree has the specified
2223/// property.
2224bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002225 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002226 if (NodeHasProperty(Property, CGP))
2227 return true;
2228 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002229 if (getChild(i)->TreeHasProperty(Property, CGP))
Chris Lattner53c39ba2010-02-14 22:22:58 +00002230 return true;
2231 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002232}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002233
Evan Cheng49bad4c2008-06-16 20:29:38 +00002234/// isCommutativeIntrinsic - Return true if the node corresponds to a
2235/// commutative intrinsic.
2236bool
2237TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2238 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2239 return Int->isCommutative;
2240 return false;
2241}
2242
Florian Hahn6b1db822018-06-14 20:32:58 +00002243static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2244 if (!N->isLeaf())
2245 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002246
Florian Hahn6b1db822018-06-14 20:32:58 +00002247 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
Matt Arsenaulteb492162014-11-02 23:46:51 +00002248 if (DI && DI->getDef()->isSubClassOf(Class))
2249 return true;
2250
2251 return false;
2252}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002253
2254static void emitTooManyOperandsError(TreePattern &TP,
2255 StringRef InstName,
2256 unsigned Expected,
2257 unsigned Actual) {
2258 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2259 " operands but expected only " + Twine(Expected) + "!");
2260}
2261
2262static void emitTooFewOperandsError(TreePattern &TP,
2263 StringRef InstName,
2264 unsigned Actual) {
2265 TP.error("Instruction '" + InstName +
2266 "' expects more than the provided " + Twine(Actual) + " operands!");
2267}
2268
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002269/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002270/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002271/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002272bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002273 if (TP.hasError())
2274 return false;
2275
Chris Lattnerab3242f2008-01-06 01:10:31 +00002276 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002277 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002278 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002279 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002280 bool MadeChange = false;
2281 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2282 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002283 NotRegisters,
2284 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002285 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002286 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002287
Sean Silvafb509ed2012-10-10 20:24:43 +00002288 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002289 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002290
Chris Lattnerf1447252010-03-19 21:37:09 +00002291 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002292 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002293
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002294 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002295 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002296
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002297 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2298 for (auto &P : VVT) {
2299 MVT::SimpleValueType VT = P.second.SimpleTy;
2300 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2301 continue;
2302 unsigned Size = MVT(VT).getSizeInBits();
2303 // Make sure that the value is representable for this type.
2304 if (Size >= 32)
2305 continue;
2306 // Check that the value doesn't use more bits than we have. It must
2307 // either be a sign- or zero-extended equivalent of the original.
2308 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2309 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2310 SignBitAndAbove == 1)
2311 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002312
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002313 TP.error("Integer value '" + Twine(II->getValue()) +
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002314 "' is out of range for type '" + getEnumName(VT) + "'!");
2315 break;
2316 }
2317 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002318 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002319
Chris Lattner8cab0212008-01-05 22:25:12 +00002320 return false;
2321 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002322
Chris Lattneree820ac2010-02-23 05:51:07 +00002323 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002324 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002325
Chris Lattner8cab0212008-01-05 22:25:12 +00002326 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002327 unsigned NumRetVTs = Int->IS.RetVTs.size();
2328 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002329
Bill Wendling91821472008-11-13 09:08:33 +00002330 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002331 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002332
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002333 if (getNumChildren() != NumParamVTs + 1) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002334 TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2335 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002336 return false;
2337 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002338
2339 // Apply type info to the intrinsic ID.
Florian Hahn6b1db822018-06-14 20:32:58 +00002340 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002341
Chris Lattnerf1447252010-03-19 21:37:09 +00002342 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002343 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002344
Chris Lattnerf1447252010-03-19 21:37:09 +00002345 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
Florian Hahn6b1db822018-06-14 20:32:58 +00002346 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2347 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002348 }
2349 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002350 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002351
Chris Lattneree820ac2010-02-23 05:51:07 +00002352 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002353 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002354
Chris Lattner135091b2010-03-28 08:48:47 +00002355 // Check that the number of operands is sane. Negative operands -> varargs.
2356 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002357 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002358 TP.error(getOperator()->getName() + " node requires exactly " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002359 Twine(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002360 return false;
2361 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002362
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002363 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002364 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002365 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2366 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002367 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002368 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002369
Chris Lattneree820ac2010-02-23 05:51:07 +00002370 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002371 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002372 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002373 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002374
Chris Lattnerd44966f2010-03-27 19:15:02 +00002375 bool MadeChange = false;
2376
2377 // Apply the result types to the node, these come from the things in the
2378 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002379 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2380 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002381 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2382 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002383
Chris Lattnerd44966f2010-03-27 19:15:02 +00002384 // If the instruction has implicit defs, we apply the first one as a result.
2385 // FIXME: This sucks, it should apply all implicit defs.
2386 if (!InstInfo.ImplicitDefs.empty()) {
2387 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002388
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002389 // FIXME: Generalize to multiple possible types and multiple possible
2390 // ImplicitDefs.
2391 MVT::SimpleValueType VT =
2392 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002393
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002394 if (VT != MVT::Other)
2395 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002396 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002397
Chris Lattnercabe0372010-03-15 06:00:16 +00002398 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2399 // be the same.
2400 if (getOperator()->getName() == "INSERT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00002401 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2402 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2403 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002404 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2405 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2406 // variadic.
2407
2408 unsigned NChild = getNumChildren();
2409 if (NChild < 3) {
2410 TP.error("REG_SEQUENCE requires at least 3 operands!");
2411 return false;
2412 }
2413
2414 if (NChild % 2 == 0) {
2415 TP.error("REG_SEQUENCE requires an odd number of operands!");
2416 return false;
2417 }
2418
2419 if (!isOperandClass(getChild(0), "RegisterClass")) {
2420 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2421 return false;
2422 }
2423
2424 for (unsigned I = 1; I < NChild; I += 2) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002425 TreePatternNode *SubIdxChild = getChild(I + 1);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002426 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2427 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002428 Twine(I + 1) + "!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00002429 return false;
2430 }
2431 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002432 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002433
2434 unsigned ChildNo = 0;
2435 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2436 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002437
Chris Lattner8cab0212008-01-05 22:25:12 +00002438 // If the instruction expects a predicate or optional def operand, we
2439 // codegen this by setting the operand to it's default value if it has a
2440 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002441 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002442 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2443 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002444
Chris Lattner8cab0212008-01-05 22:25:12 +00002445 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002446 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002447 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002448 return false;
2449 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002450
Florian Hahn6b1db822018-06-14 20:32:58 +00002451 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002452 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002453
2454 // If the operand has sub-operands, they may be provided by distinct
2455 // child patterns, so attempt to match each sub-operand separately.
2456 if (OperandNode->isSubClassOf("Operand")) {
2457 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2458 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2459 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002460 // a single ComplexPattern-related Operand.
2461
2462 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002463 // Match first sub-operand against the child we already have.
2464 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2465 MadeChange |=
2466 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2467
2468 // And the remaining sub-operands against subsequent children.
2469 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2470 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002471 emitTooFewOperandsError(TP, getOperator()->getName(),
2472 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002473 return false;
2474 }
Florian Hahn6b1db822018-06-14 20:32:58 +00002475 Child = getChild(ChildNo++);
Ulrich Weigande618abd2013-03-19 19:51:09 +00002476
2477 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2478 MadeChange |=
2479 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2480 }
2481 continue;
2482 }
2483 }
2484 }
2485
2486 // If we didn't match by pieces above, attempt to match the whole
2487 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002488 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002489 }
Christopher Lamba7312392008-03-11 09:33:47 +00002490
Matt Arsenaulteb492162014-11-02 23:46:51 +00002491 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002492 emitTooManyOperandsError(TP, getOperator()->getName(),
2493 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002494 return false;
2495 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002496
Ulrich Weigande618abd2013-03-19 19:51:09 +00002497 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002498 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002499 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002500 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002501
Tim Northoverc807a172014-05-20 11:52:46 +00002502 if (getOperator()->isSubClassOf("ComplexPattern")) {
2503 bool MadeChange = false;
2504
2505 for (unsigned i = 0; i < getNumChildren(); ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002506 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Tim Northoverc807a172014-05-20 11:52:46 +00002507
2508 return MadeChange;
2509 }
2510
Chris Lattneree820ac2010-02-23 05:51:07 +00002511 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002512
Chris Lattneree820ac2010-02-23 05:51:07 +00002513 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002514 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002515 TP.error("Node transform '" + getOperator()->getName() +
2516 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002517 return false;
2518 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002519
Florian Hahn6b1db822018-06-14 20:32:58 +00002520 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002521 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002522}
2523
2524/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2525/// RHS of a commutative operation, not the on LHS.
Florian Hahn6b1db822018-06-14 20:32:58 +00002526static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2527 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
Chris Lattner8cab0212008-01-05 22:25:12 +00002528 return true;
Florian Hahn6b1db822018-06-14 20:32:58 +00002529 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002530 return true;
2531 return false;
2532}
2533
2534
2535/// canPatternMatch - If it is impossible for this pattern to match on this
2536/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002537/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002538/// that can never possibly work), and to prevent the pattern permuter from
2539/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002540bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002541 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002542 if (isLeaf()) return true;
2543
2544 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002545 if (!getChild(i)->canPatternMatch(Reason, CDP))
Chris Lattner8cab0212008-01-05 22:25:12 +00002546 return false;
2547
2548 // If this is an intrinsic, handle cases that would make it not match. For
2549 // example, if an operand is required to be an immediate.
2550 if (getOperator()->isSubClassOf("Intrinsic")) {
2551 // TODO:
2552 return true;
2553 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002554
Tim Northoverc807a172014-05-20 11:52:46 +00002555 if (getOperator()->isSubClassOf("ComplexPattern"))
2556 return true;
2557
Chris Lattner8cab0212008-01-05 22:25:12 +00002558 // If this node is a commutative operator, check that the LHS isn't an
2559 // immediate.
2560 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002561 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2562 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002563 // Scan all of the operands of the node and make sure that only the last one
2564 // is a constant node, unless the RHS also is.
2565 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002566 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002567 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002568 if (OnlyOnRHSOfCommutative(getChild(i))) {
2569 Reason="Immediate value must be on the RHS of commutative operators!";
2570 return false;
2571 }
2572 }
2573 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002574
Chris Lattner8cab0212008-01-05 22:25:12 +00002575 return true;
2576}
2577
2578//===----------------------------------------------------------------------===//
2579// TreePattern implementation
2580//
2581
David Greeneaf8ee2c2011-07-29 22:43:06 +00002582TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002583 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002584 isInputPattern(isInput), HasError(false),
2585 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002586 for (Init *I : RawPat->getValues())
2587 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002588}
2589
David Greeneaf8ee2c2011-07-29 22:43:06 +00002590TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002591 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002592 isInputPattern(isInput), HasError(false),
2593 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002594 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002595}
2596
Florian Hahn75e87c32018-05-30 21:00:18 +00002597TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2598 CodeGenDAGPatterns &cdp)
2599 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2600 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002601 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002602}
2603
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002604void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002605 if (HasError)
2606 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002607 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002608 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2609 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002610}
2611
Chris Lattnercabe0372010-03-15 06:00:16 +00002612void TreePattern::ComputeNamedNodes() {
Florian Hahn6b1db822018-06-14 20:32:58 +00002613 for (TreePatternNodePtr &Tree : Trees)
2614 ComputeNamedNodes(Tree.get());
Chris Lattnercabe0372010-03-15 06:00:16 +00002615}
2616
Florian Hahn6b1db822018-06-14 20:32:58 +00002617void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002618 if (!N->getName().empty())
Florian Hahn6b1db822018-06-14 20:32:58 +00002619 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002620
Chris Lattnercabe0372010-03-15 06:00:16 +00002621 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002622 ComputeNamedNodes(N->getChild(i));
Chris Lattnercabe0372010-03-15 06:00:16 +00002623}
2624
Florian Hahn75e87c32018-05-30 21:00:18 +00002625TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2626 StringRef OpName) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002627 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002628 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002629
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002630 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002631 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002632 /// (foo GPR, imm) -> (foo GPR, (imm))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002633 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
David Greenee32ebf22011-07-29 19:07:07 +00002634 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002635 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002636 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002637 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002638
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002639 // Input argument?
Florian Hahn75e87c32018-05-30 21:00:18 +00002640 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002641 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002642 if (OpName.empty())
2643 error("'node' argument requires a name to match with operand list");
2644 Args.push_back(OpName);
2645 }
2646
2647 Res->setName(OpName);
2648 return Res;
2649 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002650
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002651 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002652 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002653 if (OpName.empty())
2654 error("'?' argument requires a name to match with operand list");
Florian Hahn75e87c32018-05-30 21:00:18 +00002655 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002656 Args.push_back(OpName);
2657 Res->setName(OpName);
2658 return Res;
2659 }
2660
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002661 if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002662 if (!OpName.empty())
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002663 error("Constant int or bit argument should not have a name!");
2664 if (isa<BitInit>(TheInit))
2665 TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2666 return std::make_shared<TreePatternNode>(TheInit, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002667 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002668
Sean Silvafb509ed2012-10-10 20:24:43 +00002669 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002670 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002671 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002672 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002673 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002674 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002675 }
2676
Sean Silvafb509ed2012-10-10 20:24:43 +00002677 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002678 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002679 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002680 error("Pattern has unexpected init kind!");
2681 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002682 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002683 if (!OpDef) error("Pattern has unexpected operator type!");
2684 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002685
Chris Lattner8cab0212008-01-05 22:25:12 +00002686 if (Operator->isSubClassOf("ValueType")) {
2687 // If the operator is a ValueType, then this must be "type cast" of a leaf
2688 // node.
2689 if (Dag->getNumArgs() != 1)
2690 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002691
Florian Hahn75e87c32018-05-30 21:00:18 +00002692 TreePatternNodePtr New =
2693 ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002694
Chris Lattner8cab0212008-01-05 22:25:12 +00002695 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002696 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002697 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2698 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002699
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002700 if (!OpName.empty())
2701 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002702 return New;
2703 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002704
Chris Lattner8cab0212008-01-05 22:25:12 +00002705 // Verify that this is something that makes sense for an operator.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002706 if (!Operator->isSubClassOf("PatFrags") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002707 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002708 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002709 !Operator->isSubClassOf("SDNodeXForm") &&
2710 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002711 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002712 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002713 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002714 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002715
Chris Lattner8cab0212008-01-05 22:25:12 +00002716 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002717 if (isInputPattern) {
2718 if (Operator->isSubClassOf("Instruction") ||
2719 Operator->isSubClassOf("SDNodeXForm"))
2720 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2721 } else {
2722 if (Operator->isSubClassOf("Intrinsic"))
2723 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002724
Chris Lattner2e9eae12010-03-28 06:57:56 +00002725 if (Operator->isSubClassOf("SDNode") &&
2726 Operator->getName() != "imm" &&
2727 Operator->getName() != "fpimm" &&
2728 Operator->getName() != "tglobaltlsaddr" &&
2729 Operator->getName() != "tconstpool" &&
2730 Operator->getName() != "tjumptable" &&
2731 Operator->getName() != "tframeindex" &&
2732 Operator->getName() != "texternalsym" &&
2733 Operator->getName() != "tblockaddress" &&
2734 Operator->getName() != "tglobaladdr" &&
2735 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002736 Operator->getName() != "vt" &&
2737 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002738 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2739 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002740
Florian Hahn75e87c32018-05-30 21:00:18 +00002741 std::vector<TreePatternNodePtr> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002742
2743 // Parse all the operands.
2744 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002745 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002746
Hal Finkel8b4bdfdb2018-01-03 11:35:09 +00002747 // Get the actual number of results before Operator is converted to an intrinsic
2748 // node (which is hard-coded to have either zero or one result).
2749 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2750
Fangrui Song956ee792018-03-30 22:22:31 +00002751 // If the operator is an intrinsic, then this is just syntactic sugar for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002752 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002753 // convert the intrinsic name to a number.
2754 if (Operator->isSubClassOf("Intrinsic")) {
2755 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2756 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2757
2758 // If this intrinsic returns void, it must have side-effects and thus a
2759 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002760 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002761 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002762 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002763 // Has side-effects, requires chain.
2764 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002765 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002766 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002767
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002768 Children.insert(Children.begin(),
2769 std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
Chris Lattner8cab0212008-01-05 22:25:12 +00002770 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002771
Tim Northoverc807a172014-05-20 11:52:46 +00002772 if (Operator->isSubClassOf("ComplexPattern")) {
2773 for (unsigned i = 0; i < Children.size(); ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002774 TreePatternNodePtr Child = Children[i];
Tim Northoverc807a172014-05-20 11:52:46 +00002775
2776 if (Child->getName().empty())
2777 error("All arguments to a ComplexPattern must be named");
2778
2779 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2780 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2781 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2782 auto OperandId = std::make_pair(Operator, i);
2783 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2784 if (PrevOp != ComplexPatternOperands.end()) {
2785 if (PrevOp->getValue() != OperandId)
2786 error("All ComplexPattern operands must appear consistently: "
2787 "in the same order in just one ComplexPattern instance.");
2788 } else
2789 ComplexPatternOperands[Child->getName()] = OperandId;
2790 }
2791 }
2792
Florian Hahn6b1db822018-06-14 20:32:58 +00002793 TreePatternNodePtr Result =
Craig Topper26fc06352018-07-15 06:52:49 +00002794 std::make_shared<TreePatternNode>(Operator, std::move(Children),
2795 NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002796 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002797
Matthias Braun7cf3b112016-12-05 06:00:41 +00002798 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002799 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002800 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002801 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002802 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002803}
2804
Chris Lattnera787c9e2010-03-28 08:38:32 +00002805/// SimplifyTree - See if we can simplify this tree to eliminate something that
2806/// will never match in favor of something obvious that will. This is here
2807/// strictly as a convenience to target authors because it allows them to write
2808/// more type generic things and have useless type casts fold away.
2809///
2810/// This returns true if any change is made.
Florian Hahn75e87c32018-05-30 21:00:18 +00002811static bool SimplifyTree(TreePatternNodePtr &N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002812 if (N->isLeaf())
2813 return false;
2814
2815 // If we have a bitconvert with a resolved type and if the source and
2816 // destination types are the same, then the bitconvert is useless, remove it.
2817 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002818 N->getExtType(0).isValueTypeByHwMode(false) &&
Florian Hahn6b1db822018-06-14 20:32:58 +00002819 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002820 N->getName().empty()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002821 N = N->getChildShared(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002822 SimplifyTree(N);
2823 return true;
2824 }
2825
2826 // Walk all children.
2827 bool MadeChange = false;
2828 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002829 TreePatternNodePtr Child = N->getChildShared(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002830 MadeChange |= SimplifyTree(Child);
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002831 N->setChild(i, std::move(Child));
Chris Lattnera787c9e2010-03-28 08:38:32 +00002832 }
2833 return MadeChange;
2834}
2835
2836
2837
Chris Lattner8cab0212008-01-05 22:25:12 +00002838/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002839/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002840/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002841bool TreePattern::
2842InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2843 if (NamedNodes.empty())
2844 ComputeNamedNodes();
2845
Chris Lattner8cab0212008-01-05 22:25:12 +00002846 bool MadeChange = true;
2847 while (MadeChange) {
2848 MadeChange = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002849 for (TreePatternNodePtr &Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002850 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2851 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002852 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002853
2854 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002855 for (auto &Entry : NamedNodes) {
2856 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002857
Chris Lattnercabe0372010-03-15 06:00:16 +00002858 // If we have input named node types, propagate their types to the named
2859 // values here.
2860 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002861 if (!InNamedTypes->count(Entry.getKey())) {
2862 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002863 "' in output pattern but not input pattern");
2864 return true;
2865 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002866
2867 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002868 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002869
2870 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002871 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002872 // If this node is a register class, and it is the root of the pattern
2873 // then we're mapping something onto an input register. We allow
2874 // changing the type of the input register in this case. This allows
2875 // us to match things like:
2876 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Florian Hahn75e87c32018-05-30 21:00:18 +00002877 if (Node == Trees[0].get() && Node->isLeaf()) {
Craig Topper306cb122015-11-22 20:46:24 +00002878 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002879 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2880 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002881 continue;
2882 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002883
Craig Topper306cb122015-11-22 20:46:24 +00002884 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002885 InNodes[0]->getNumTypes() == 1 &&
2886 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002887 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2888 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002889 }
2890 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002891
Chris Lattnercabe0372010-03-15 06:00:16 +00002892 // If there are multiple nodes with the same name, they must all have the
2893 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002894 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002895 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002896 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002897 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002898 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002899
Chris Lattnerf1447252010-03-19 21:37:09 +00002900 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2901 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002902 }
2903 }
2904 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002905 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002906
Chris Lattner8cab0212008-01-05 22:25:12 +00002907 bool HasUnresolvedTypes = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002908 for (const TreePatternNodePtr &Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002909 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002910 return !HasUnresolvedTypes;
2911}
2912
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002913void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002914 OS << getRecord()->getName();
2915 if (!Args.empty()) {
2916 OS << "(" << Args[0];
2917 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2918 OS << ", " << Args[i];
2919 OS << ")";
2920 }
2921 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002922
Chris Lattner8cab0212008-01-05 22:25:12 +00002923 if (Trees.size() > 1)
2924 OS << "[\n";
Florian Hahn75e87c32018-05-30 21:00:18 +00002925 for (const TreePatternNodePtr &Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002926 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002927 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002928 OS << "\n";
2929 }
2930
2931 if (Trees.size() > 1)
2932 OS << "]\n";
2933}
2934
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002935void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002936
2937//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002938// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002939//
2940
Daniel Sanders7e523672017-11-11 03:23:44 +00002941CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2942 PatternRewriterFn PatternRewriter)
2943 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2944 PatternRewriter(PatternRewriter) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002945
Justin Bogner92a8c612016-07-15 16:31:37 +00002946 Intrinsics = CodeGenIntrinsicTable(Records, false);
2947 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002948 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002949 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002950 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002951 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002952 ParseDefaultOperands();
2953 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002954 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002955 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002956
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002957 // Break patterns with parameterized types into a series of patterns,
2958 // where each one has a fixed type and is predicated on the conditions
2959 // of the associated HW mode.
2960 ExpandHwModeBasedTypes();
2961
Chris Lattner8cab0212008-01-05 22:25:12 +00002962 // Generate variants. For example, commutative patterns can match
2963 // multiple ways. Add them to PatternsToMatch as well.
2964 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002965
2966 // Infer instruction flags. For example, we can detect loads,
2967 // stores, and side effects in many cases by examining an
2968 // instruction's pattern.
2969 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002970
2971 // Verify that instruction flags match the patterns.
2972 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002973}
2974
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00002975Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002976 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002977 if (!N || !N->isSubClassOf("SDNode"))
2978 PrintFatalError("Error getting SDNode '" + Name + "'!");
2979
Chris Lattner8cab0212008-01-05 22:25:12 +00002980 return N;
2981}
2982
2983// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002984void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002985 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002986 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2987
Chris Lattner8cab0212008-01-05 22:25:12 +00002988 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002989 Record *R = Nodes.back();
2990 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002991 Nodes.pop_back();
2992 }
2993
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002994 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002995 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2996 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2997 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2998}
2999
3000/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3001/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003002void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003003 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
3004 while (!Xforms.empty()) {
3005 Record *XFormNode = Xforms.back();
3006 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00003007 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00003008 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00003009
3010 Xforms.pop_back();
3011 }
3012}
3013
Chris Lattnerab3242f2008-01-06 01:10:31 +00003014void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003015 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
3016 while (!AMs.empty()) {
3017 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
3018 AMs.pop_back();
3019 }
3020}
3021
3022
3023/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3024/// file, building up the PatternFragments map. After we've collected them all,
3025/// inline fragments together as necessary, so that there are no references left
3026/// inside a pattern fragment to a pattern fragment.
3027///
Hal Finkel2756dc12014-02-28 00:26:56 +00003028void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003029 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003030
Chris Lattnere7170df2008-01-05 22:43:57 +00003031 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00003032 for (Record *Frag : Fragments) {
3033 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003034 continue;
3035
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003036 ListInit *LI = Frag->getValueAsListInit("Fragments");
Hal Finkel2756dc12014-02-28 00:26:56 +00003037 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00003038 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003039 Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00003040 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003041
Chris Lattnere7170df2008-01-05 22:43:57 +00003042 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00003043 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00003044 // Copy the args so we can take StringRefs to them.
3045 auto ArgsCopy = Args;
3046 SmallDenseSet<StringRef, 4> OperandsSet;
3047 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003048
Chris Lattnere7170df2008-01-05 22:43:57 +00003049 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00003050 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003051
Chris Lattner8cab0212008-01-05 22:25:12 +00003052 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00003053 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00003054 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00003055 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003056 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00003057 if (!OpsOp ||
3058 (OpsOp->getDef()->getName() != "ops" &&
3059 OpsOp->getDef()->getName() != "outs" &&
3060 OpsOp->getDef()->getName() != "ins"))
3061 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003062
3063 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00003064 Args.clear();
3065 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003066 if (!isa<DefInit>(OpsList->getArg(j)) ||
3067 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00003068 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00003069 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00003070 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00003071 StringRef ArgNameStr = OpsList->getArgNameStr(j);
3072 if (!OperandsSet.count(ArgNameStr))
3073 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00003074 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00003075 OperandsSet.erase(ArgNameStr);
3076 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003077 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003078
Chris Lattnere7170df2008-01-05 22:43:57 +00003079 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003080 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00003081 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003082
Chris Lattner8cab0212008-01-05 22:25:12 +00003083 // If there is a node transformation corresponding to this, keep track of
3084 // it.
Craig Topper306cb122015-11-22 20:46:24 +00003085 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00003086 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003087 for (auto T : P->getTrees())
3088 T->setTransformFn(Transform);
Chris Lattner8cab0212008-01-05 22:25:12 +00003089 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003090
Chris Lattner8cab0212008-01-05 22:25:12 +00003091 // Now that we've parsed all of the tree fragments, do a closure on them so
3092 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00003093 for (Record *Frag : Fragments) {
3094 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003095 continue;
3096
Craig Topper306cb122015-11-22 20:46:24 +00003097 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00003098 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003099
Chris Lattner8cab0212008-01-05 22:25:12 +00003100 // Infer as many types as possible. Don't worry about it if we don't infer
Ulrich Weigand22b1af82018-07-13 16:42:15 +00003101 // all of them, some may depend on the inputs of the pattern. Also, don't
3102 // validate type sets; validation may cause spurious failures e.g. if a
3103 // fragment needs floating-point types but the current target does not have
3104 // any (this is only an error if that fragment is ever used!).
3105 {
3106 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3107 ThePat.InferAllTypes();
3108 ThePat.resetError();
3109 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003110
Chris Lattner8cab0212008-01-05 22:25:12 +00003111 // If debugging, print out the pattern fragment result.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003112 LLVM_DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003113 }
3114}
3115
Chris Lattnerab3242f2008-01-06 01:10:31 +00003116void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00003117 std::vector<Record*> DefaultOps;
3118 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00003119
3120 // Find some SDNode.
3121 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00003122 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003123
Tom Stellardb7246a72012-09-06 14:15:52 +00003124 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3125 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003126
Tom Stellardb7246a72012-09-06 14:15:52 +00003127 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3128 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00003129 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00003130 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3131 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3132 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00003133 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003134
Tom Stellardb7246a72012-09-06 14:15:52 +00003135 // Create a TreePattern to parse this.
3136 TreePattern P(DefaultOps[i], DI, false, *this);
3137 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003138
Tom Stellardb7246a72012-09-06 14:15:52 +00003139 // Copy the operands over into a DAGDefaultOperand.
3140 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003141
Florian Hahn75e87c32018-05-30 21:00:18 +00003142 const TreePatternNodePtr &T = P.getTree(0);
Tom Stellardb7246a72012-09-06 14:15:52 +00003143 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
Florian Hahn75e87c32018-05-30 21:00:18 +00003144 TreePatternNodePtr TPN = T->getChildShared(op);
Tom Stellardb7246a72012-09-06 14:15:52 +00003145 while (TPN->ApplyTypeConstraints(P, false))
3146 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003147
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003148 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00003149 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3150 DefaultOps[i]->getName() +
3151 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003152 }
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003153 DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
Chris Lattner8cab0212008-01-05 22:25:12 +00003154 }
Tom Stellardb7246a72012-09-06 14:15:52 +00003155
3156 // Insert it into the DefaultOperands map so we can find it later.
3157 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00003158 }
3159}
3160
3161/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3162/// instruction input. Return true if this is a real use.
David Blaikie19b22d42018-06-11 22:14:43 +00003163static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003164 std::map<std::string, TreePatternNodePtr> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003165 // No name -> not interesting.
3166 if (Pat->getName().empty()) {
3167 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003168 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00003169 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3170 DI->getDef()->isSubClassOf("RegisterOperand")))
David Blaikie19b22d42018-06-11 22:14:43 +00003171 I.error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003172 }
3173 return false;
3174 }
3175
3176 Record *Rec;
3177 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003178 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
David Blaikie19b22d42018-06-11 22:14:43 +00003179 if (!DI)
3180 I.error("Input $" + Pat->getName() + " must be an identifier!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003181 Rec = DI->getDef();
3182 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003183 Rec = Pat->getOperator();
3184 }
3185
3186 // SRCVALUE nodes are ignored.
3187 if (Rec->getName() == "srcvalue")
3188 return false;
3189
Florian Hahn75e87c32018-05-30 21:00:18 +00003190 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
Chris Lattner8cab0212008-01-05 22:25:12 +00003191 if (!Slot) {
3192 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003193 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00003194 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003195 Record *SlotRec;
3196 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003197 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003198 } else {
3199 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3200 SlotRec = Slot->getOperator();
3201 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003202
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003203 // Ensure that the inputs agree if we've already seen this input.
3204 if (Rec != SlotRec)
David Blaikie19b22d42018-06-11 22:14:43 +00003205 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003206 // Ensure that the types can agree as well.
3207 Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3208 Pat->UpdateNodeType(0, Slot->getExtType(0), I);
Chris Lattnerf1447252010-03-19 21:37:09 +00003209 if (Slot->getExtTypes() != Pat->getExtTypes())
David Blaikie19b22d42018-06-11 22:14:43 +00003210 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003211 return true;
3212}
3213
3214/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3215/// part of "I", the instruction), computing the set of inputs and outputs of
3216/// the pattern. Report errors if we see anything naughty.
Florian Hahn75e87c32018-05-30 21:00:18 +00003217void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
Florian Hahn6b1db822018-06-14 20:32:58 +00003218 TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003219 std::map<std::string, TreePatternNodePtr> &InstInputs,
Craig Topperbd199f82018-12-05 00:47:59 +00003220 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3221 &InstResults,
Florian Hahn75e87c32018-05-30 21:00:18 +00003222 std::vector<Record *> &InstImpResults) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003223
3224 // The instruction pattern still has unresolved fragments. For *named*
3225 // nodes we must resolve those here. This may not result in multiple
3226 // alternatives.
3227 if (!Pat->getName().empty()) {
3228 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3229 SrcPattern.InlinePatternFragments();
3230 SrcPattern.InferAllTypes();
3231 Pat = SrcPattern.getOnlyTree();
3232 }
3233
Chris Lattner8cab0212008-01-05 22:25:12 +00003234 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003235 bool isUse = HandleUse(I, Pat, InstInputs);
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 Lattnerf2d70992010-02-17 06:53:36 +00003241 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003242 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003243 TreePatternNode *Dest = Pat->getChild(i);
3244 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003245 I.error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003246
Florian Hahn6b1db822018-06-14 20:32:58 +00003247 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003248 if (!Val || !Val->getDef()->isSubClassOf("Register"))
David Blaikie19b22d42018-06-11 22:14:43 +00003249 I.error("implicitly defined value should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003250 InstImpResults.push_back(Val->getDef());
3251 }
3252 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003253 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003254
Chris Lattnerf2d70992010-02-17 06:53:36 +00003255 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003256 // If this is not a set, verify that the children nodes are not void typed,
3257 // and recurse.
3258 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003259 if (Pat->getChild(i)->getNumTypes() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003260 I.error("Cannot have void nodes inside of patterns!");
Florian Hahn75e87c32018-05-30 21:00:18 +00003261 FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3262 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003263 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003264
Chris Lattner8cab0212008-01-05 22:25:12 +00003265 // If this is a non-leaf node with no children, treat it basically as if
3266 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003267 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003268
Chris Lattner8cab0212008-01-05 22:25:12 +00003269 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003270 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003271 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003272 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003273
Chris Lattner8cab0212008-01-05 22:25:12 +00003274 // Otherwise, this is a set, validate and collect instruction results.
3275 if (Pat->getNumChildren() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003276 I.error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003277
Chris Lattner8cab0212008-01-05 22:25:12 +00003278 if (Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003279 I.error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003280
Chris Lattner8cab0212008-01-05 22:25:12 +00003281 // Check the set destinations.
3282 unsigned NumDests = Pat->getNumChildren()-1;
3283 for (unsigned i = 0; i != NumDests; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003284 TreePatternNodePtr Dest = Pat->getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003285 // For set destinations we also must resolve fragments here.
3286 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3287 DestPattern.InlinePatternFragments();
3288 DestPattern.InferAllTypes();
3289 Dest = DestPattern.getOnlyTree();
3290
Chris Lattner8cab0212008-01-05 22:25:12 +00003291 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003292 I.error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003293
Sean Silvafb509ed2012-10-10 20:24:43 +00003294 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003295 if (!Val) {
David Blaikie19b22d42018-06-11 22:14:43 +00003296 I.error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003297 continue;
3298 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003299
3300 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003301 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003302 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003303 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003304 if (Dest->getName().empty())
David Blaikie19b22d42018-06-11 22:14:43 +00003305 I.error("set destination must have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003306 if (InstResults.count(Dest->getName()))
David Blaikie19b22d42018-06-11 22:14:43 +00003307 I.error("cannot set '" + Dest->getName() + "' multiple times");
Chris Lattner8cab0212008-01-05 22:25:12 +00003308 InstResults[Dest->getName()] = Dest;
3309 } else if (Val->getDef()->isSubClassOf("Register")) {
3310 InstImpResults.push_back(Val->getDef());
3311 } else {
David Blaikie19b22d42018-06-11 22:14:43 +00003312 I.error("set destination should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003313 }
3314 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003315
Chris Lattner8cab0212008-01-05 22:25:12 +00003316 // Verify and collect info from the computation.
Florian Hahn75e87c32018-05-30 21:00:18 +00003317 FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3318 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003319}
3320
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003321//===----------------------------------------------------------------------===//
3322// Instruction Analysis
3323//===----------------------------------------------------------------------===//
3324
3325class InstAnalyzer {
3326 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003327public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003328 bool hasSideEffects;
3329 bool mayStore;
3330 bool mayLoad;
3331 bool isBitcast;
3332 bool isVariadic;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003333 bool hasChain;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003334
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003335 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3336 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003337 isBitcast(false), isVariadic(false), hasChain(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003338
Craig Topper2a053a92017-06-20 16:34:37 +00003339 void Analyze(const PatternToMatch &Pat) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003340 const TreePatternNode *N = Pat.getSrcPattern();
3341 AnalyzeNode(N);
3342 // These properties are detected only on the root node.
3343 isBitcast = IsNodeBitcast(N);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003344 }
3345
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003346private:
Florian Hahn6b1db822018-06-14 20:32:58 +00003347 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003348 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003349 return false;
3350
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003351 if (N->isLeaf())
3352 return false;
3353 if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
Evan Cheng880e299d2011-03-15 05:09:26 +00003354 return false;
3355
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003356 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
Evan Cheng880e299d2011-03-15 05:09:26 +00003357 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3358 return false;
3359 return OpInfo.getEnumName() == "ISD::BITCAST";
3360 }
3361
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003362public:
Florian Hahn6b1db822018-06-14 20:32:58 +00003363 void AnalyzeNode(const TreePatternNode *N) {
3364 if (N->isLeaf()) {
3365 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003366 Record *LeafRec = DI->getDef();
3367 // Handle ComplexPattern leaves.
3368 if (LeafRec->isSubClassOf("ComplexPattern")) {
3369 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3370 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3371 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003372 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003373 }
3374 }
3375 return;
3376 }
3377
3378 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003379 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3380 AnalyzeNode(N->getChild(i));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003381
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003382 // Notice properties of the node.
Florian Hahn6b1db822018-06-14 20:32:58 +00003383 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3384 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3385 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3386 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003387 if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003388
Florian Hahn6b1db822018-06-14 20:32:58 +00003389 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003390 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003391 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003392 mayLoad = true;// These may load memory.
3393
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003394 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003395 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3396
Matt Arsenault868af922017-04-28 21:01:46 +00003397 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3398 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003399 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003400 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003401 }
3402 }
3403
3404};
3405
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003406static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003407 const InstAnalyzer &PatInfo,
3408 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003409 bool Error = false;
3410
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003411 // Remember where InstInfo got its flags.
3412 if (InstInfo.hasUndefFlags())
3413 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003414
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003415 // Check explicitly set flags for consistency.
3416 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3417 !InstInfo.hasSideEffects_Unset) {
3418 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3419 // the pattern has no side effects. That could be useful for div/rem
3420 // instructions that may trap.
3421 if (!InstInfo.hasSideEffects) {
3422 Error = true;
3423 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3424 Twine(InstInfo.hasSideEffects));
3425 }
3426 }
3427
3428 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3429 Error = true;
3430 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3431 Twine(InstInfo.mayStore));
3432 }
3433
3434 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3435 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003436 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003437 if (!InstInfo.mayLoad) {
3438 Error = true;
3439 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3440 Twine(InstInfo.mayLoad));
3441 }
3442 }
3443
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003444 // Transfer inferred flags.
3445 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3446 InstInfo.mayStore |= PatInfo.mayStore;
3447 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003448
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003449 // These flags are silently added without any verification.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003450 // FIXME: To match historical behavior of TableGen, for now add those flags
3451 // only when we're inferring from the primary instruction pattern.
3452 if (PatDef->isSubClassOf("Instruction")) {
3453 InstInfo.isBitcast |= PatInfo.isBitcast;
3454 InstInfo.hasChain |= PatInfo.hasChain;
3455 InstInfo.hasChain_Inferred = true;
3456 }
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003457
3458 // Don't infer isVariadic. This flag means something different on SDNodes and
3459 // instructions. For example, a CALL SDNode is variadic because it has the
3460 // call arguments as operands, but a CALL instruction is not variadic - it
3461 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003462
3463 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003464}
3465
Jim Grosbach514410b2012-07-17 00:47:06 +00003466/// hasNullFragReference - Return true if the DAG has any reference to the
3467/// null_frag operator.
3468static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003469 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003470 if (!OpDef) return false;
3471 Record *Operator = OpDef->getDef();
3472
3473 // If this is the null fragment, return true.
3474 if (Operator->getName() == "null_frag") return true;
3475 // If any of the arguments reference the null fragment, return true.
3476 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003477 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003478 if (Arg && hasNullFragReference(Arg))
3479 return true;
3480 }
3481
3482 return false;
3483}
3484
3485/// hasNullFragReference - Return true if any DAG in the list references
3486/// the null_frag operator.
3487static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003488 for (Init *I : LI->getValues()) {
3489 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003490 assert(DI && "non-dag in an instruction Pattern list?!");
3491 if (hasNullFragReference(DI))
3492 return true;
3493 }
3494 return false;
3495}
3496
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003497/// Get all the instructions in a tree.
3498static void
Florian Hahn6b1db822018-06-14 20:32:58 +00003499getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3500 if (Tree->isLeaf())
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003501 return;
Florian Hahn6b1db822018-06-14 20:32:58 +00003502 if (Tree->getOperator()->isSubClassOf("Instruction"))
3503 Instrs.push_back(Tree->getOperator());
3504 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3505 getInstructionsInTree(Tree->getChild(i), Instrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003506}
3507
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003508/// Check the class of a pattern leaf node against the instruction operand it
3509/// represents.
3510static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3511 Record *Leaf) {
3512 if (OI.Rec == Leaf)
3513 return true;
3514
3515 // Allow direct value types to be used in instruction set patterns.
3516 // The type will be checked later.
3517 if (Leaf->isSubClassOf("ValueType"))
3518 return true;
3519
3520 // Patterns can also be ComplexPattern instances.
3521 if (Leaf->isSubClassOf("ComplexPattern"))
3522 return true;
3523
3524 return false;
3525}
3526
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003527void CodeGenDAGPatterns::parseInstructionPattern(
Ahmed Bougacha14107512013-10-28 18:07:21 +00003528 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003529
Craig Topper0d1fb902015-03-10 03:25:04 +00003530 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003531
Craig Topper0d1fb902015-03-10 03:25:04 +00003532 // Parse the instruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003533 TreePattern I(CGI.TheDef, Pat, true, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003534
Craig Topper0d1fb902015-03-10 03:25:04 +00003535 // InstInputs - Keep track of all of the inputs of the instruction, along
3536 // with the record they are declared as.
Florian Hahn75e87c32018-05-30 21:00:18 +00003537 std::map<std::string, TreePatternNodePtr> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003538
Craig Topper0d1fb902015-03-10 03:25:04 +00003539 // InstResults - Keep track of all the virtual registers that are 'set'
3540 // in the instruction, including what reg class they are.
Craig Topperbd199f82018-12-05 00:47:59 +00003541 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3542 InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003543
Craig Topper0d1fb902015-03-10 03:25:04 +00003544 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003545
Craig Topper0d1fb902015-03-10 03:25:04 +00003546 // Verify that the top-level forms in the instruction are of void type, and
3547 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003548 SmallString<32> TypesString;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003549 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003550 TypesString.clear();
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003551 TreePatternNodePtr Pat = I.getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003552 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003553 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003554 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3555 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003556 OS << ", ";
3557 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003558 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003559 I.error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003560 " void types, has types " +
3561 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003562 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003563
Craig Topper0d1fb902015-03-10 03:25:04 +00003564 // Find inputs and outputs, and verify the structure of the uses/defs.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003565 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Craig Topper0d1fb902015-03-10 03:25:04 +00003566 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003567 }
3568
Craig Topper0d1fb902015-03-10 03:25:04 +00003569 // Now that we have inputs and outputs of the pattern, inspect the operands
3570 // list for the instruction. This determines the order that operands are
3571 // added to the machine instruction the node corresponds to.
3572 unsigned NumResults = InstResults.size();
3573
3574 // Parse the operands list from the (ops) list, validating it.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003575 assert(I.getArgList().empty() && "Args list should still be empty here!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003576
3577 // Check that all of the results occur first in the list.
3578 std::vector<Record*> Results;
Craig Topperbd199f82018-12-05 00:47:59 +00003579 std::vector<unsigned> ResultIndices;
Florian Hahn75e87c32018-05-30 21:00:18 +00003580 SmallVector<TreePatternNodePtr, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003581 for (unsigned i = 0; i != NumResults; ++i) {
Craig Topperbd199f82018-12-05 00:47:59 +00003582 if (i == CGI.Operands.size()) {
3583 const std::string &OpName =
3584 std::find_if(InstResults.begin(), InstResults.end(),
3585 [](const std::pair<std::string, TreePatternNodePtr> &P) {
3586 return P.second;
3587 })
3588 ->first;
3589
3590 I.error("'" + OpName + "' set but does not appear in operand list!");
3591 }
3592
Craig Topper0d1fb902015-03-10 03:25:04 +00003593 const std::string &OpName = CGI.Operands[i].Name;
3594
3595 // Check that it exists in InstResults.
Craig Topperbd199f82018-12-05 00:47:59 +00003596 auto InstResultIter = InstResults.find(OpName);
3597 if (InstResultIter == InstResults.end() || !InstResultIter->second)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003598 I.error("Operand $" + OpName + " does not exist in operand list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003599
Craig Topperbd199f82018-12-05 00:47:59 +00003600 TreePatternNodePtr RNode = InstResultIter->second;
Craig Topper0d1fb902015-03-10 03:25:04 +00003601 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003602 ResNodes.push_back(std::move(RNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003603 if (!R)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003604 I.error("Operand $" + OpName + " should be a set destination: all "
Craig Topper0d1fb902015-03-10 03:25:04 +00003605 "outputs must occur before inputs in operand list!");
3606
3607 if (!checkOperandClass(CGI.Operands[i], R))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003608 I.error("Operand $" + OpName + " class mismatch!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003609
3610 // Remember the return type.
3611 Results.push_back(CGI.Operands[i].Rec);
3612
Craig Topperbd199f82018-12-05 00:47:59 +00003613 // Remember the result index.
3614 ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
3615
Craig Topper0d1fb902015-03-10 03:25:04 +00003616 // Okay, this one checks out.
Craig Topperbd199f82018-12-05 00:47:59 +00003617 InstResultIter->second = nullptr;
Craig Topper0d1fb902015-03-10 03:25:04 +00003618 }
3619
Craig Topper765b9202018-07-15 06:52:48 +00003620 // Loop over the inputs next.
Florian Hahn75e87c32018-05-30 21:00:18 +00003621 std::vector<TreePatternNodePtr> ResultNodeOperands;
Craig Topper0d1fb902015-03-10 03:25:04 +00003622 std::vector<Record*> Operands;
3623 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3624 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3625 const std::string &OpName = Op.Name;
3626 if (OpName.empty())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003627 I.error("Operand #" + Twine(i) + " in operands list has no name!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003628
Craig Topper765b9202018-07-15 06:52:48 +00003629 if (!InstInputs.count(OpName)) {
Craig Topper0d1fb902015-03-10 03:25:04 +00003630 // If this is an operand with a DefaultOps set filled in, we can ignore
3631 // this. When we codegen it, we will do so as always executed.
3632 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3633 // Does it have a non-empty DefaultOps field? If so, ignore this
3634 // operand.
3635 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3636 continue;
3637 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003638 I.error("Operand $" + OpName +
Craig Topper0d1fb902015-03-10 03:25:04 +00003639 " does not appear in the instruction pattern");
3640 }
Craig Topper765b9202018-07-15 06:52:48 +00003641 TreePatternNodePtr InVal = InstInputs[OpName];
3642 InstInputs.erase(OpName); // It occurred, remove from map.
Craig Topper0d1fb902015-03-10 03:25:04 +00003643
3644 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3645 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3646 if (!checkOperandClass(Op, InRec))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003647 I.error("Operand $" + OpName + "'s register class disagrees"
Craig Topper0d1fb902015-03-10 03:25:04 +00003648 " between the operand and pattern");
3649 }
3650 Operands.push_back(Op.Rec);
3651
3652 // Construct the result for the dest-pattern operand list.
Florian Hahn75e87c32018-05-30 21:00:18 +00003653 TreePatternNodePtr OpNode = InVal->clone();
Craig Topper0d1fb902015-03-10 03:25:04 +00003654
3655 // No predicate is useful on the result.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003656 OpNode->clearPredicateCalls();
Craig Topper0d1fb902015-03-10 03:25:04 +00003657
3658 // Promote the xform function to be an explicit node if set.
3659 if (Record *Xform = OpNode->getTransformFn()) {
3660 OpNode->setTransformFn(nullptr);
Florian Hahn75e87c32018-05-30 21:00:18 +00003661 std::vector<TreePatternNodePtr> Children;
Craig Topper0d1fb902015-03-10 03:25:04 +00003662 Children.push_back(OpNode);
Craig Topper26fc06352018-07-15 06:52:49 +00003663 OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
Florian Hahn6b1db822018-06-14 20:32:58 +00003664 OpNode->getNumTypes());
Craig Topper0d1fb902015-03-10 03:25:04 +00003665 }
3666
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003667 ResultNodeOperands.push_back(std::move(OpNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003668 }
3669
Craig Topper765b9202018-07-15 06:52:48 +00003670 if (!InstInputs.empty())
3671 I.error("Input operand $" + InstInputs.begin()->first +
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003672 " occurs in pattern but not in operands list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003673
Florian Hahn6b1db822018-06-14 20:32:58 +00003674 TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00003675 I.getRecord(), std::move(ResultNodeOperands),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003676 GetNumNodeResults(I.getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003677 // Copy fully inferred output node types to instruction result pattern.
3678 for (unsigned i = 0; i != NumResults; ++i) {
3679 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3680 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
Craig Topperbd199f82018-12-05 00:47:59 +00003681 ResultPattern->setResultIndex(i, ResultIndices[i]);
Craig Topper3a8eb892015-03-20 05:09:06 +00003682 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003683
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003684 // FIXME: Assume only the first tree is the pattern. The others are clobber
3685 // nodes.
3686 TreePatternNodePtr Pattern = I.getTree(0);
3687 TreePatternNodePtr SrcPattern;
3688 if (Pattern->getOperator()->getName() == "set") {
3689 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3690 } else{
3691 // Not a set (store or something?)
3692 SrcPattern = Pattern;
3693 }
3694
Craig Topper0d1fb902015-03-10 03:25:04 +00003695 // Create and insert the instruction.
3696 // FIXME: InstImpResults should not be part of DAGInstruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003697 Record *R = I.getRecord();
3698 DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3699 std::forward_as_tuple(Results, Operands, InstImpResults,
3700 SrcPattern, ResultPattern));
Craig Topper0d1fb902015-03-10 03:25:04 +00003701
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003702 LLVM_DEBUG(I.dump());
Craig Topper0d1fb902015-03-10 03:25:04 +00003703}
3704
Ahmed Bougacha14107512013-10-28 18:07:21 +00003705/// ParseInstructions - Parse all of the instructions, inlining and resolving
3706/// any fragments involved. This populates the Instructions list with fully
3707/// resolved instructions.
3708void CodeGenDAGPatterns::ParseInstructions() {
3709 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3710
Craig Topper306cb122015-11-22 20:46:24 +00003711 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003712 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003713
Craig Topper306cb122015-11-22 20:46:24 +00003714 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3715 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003716
3717 // If there is no pattern, only collect minimal information about the
3718 // instruction for its operand list. We have to assume that there is one
3719 // result, as we have no detailed info. A pattern which references the
3720 // null_frag operator is as-if no pattern were specified. Normally this
3721 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3722 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003723 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003724 std::vector<Record*> Results;
3725 std::vector<Record*> Operands;
3726
Craig Topper306cb122015-11-22 20:46:24 +00003727 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003728
3729 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003730 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3731 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003732
Craig Topper3a8eb892015-03-20 05:09:06 +00003733 // The rest are inputs.
3734 for (unsigned j = InstInfo.Operands.NumDefs,
3735 e = InstInfo.Operands.size(); j < e; ++j)
3736 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003737 }
3738
3739 // Create and insert the instruction.
3740 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003741 Instructions.insert(std::make_pair(Instr,
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003742 DAGInstruction(Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003743 continue; // no pattern.
3744 }
3745
Craig Topper306cb122015-11-22 20:46:24 +00003746 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003747 parseInstructionPattern(CGI, LI, Instructions);
Chris Lattner8cab0212008-01-05 22:25:12 +00003748 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003749
Chris Lattner8cab0212008-01-05 22:25:12 +00003750 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003751 for (auto &Entry : Instructions) {
Craig Topper306cb122015-11-22 20:46:24 +00003752 Record *Instr = Entry.first;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003753 DAGInstruction &TheInst = Entry.second;
3754 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3755 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3756
3757 if (SrcPattern && ResultPattern) {
3758 TreePattern Pattern(Instr, SrcPattern, true, *this);
3759 TreePattern Result(Instr, ResultPattern, false, *this);
3760 ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3761 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003762 }
3763}
3764
Florian Hahn6b1db822018-06-14 20:32:58 +00003765typedef std::pair<TreePatternNode *, unsigned> NameRecord;
Chris Lattnera7722b62010-02-23 06:55:24 +00003766
Florian Hahn6b1db822018-06-14 20:32:58 +00003767static void FindNames(TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003768 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003769 TreePattern *PatternTop) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003770 if (!P->getName().empty()) {
3771 NameRecord &Rec = Names[P->getName()];
Chris Lattnera7722b62010-02-23 06:55:24 +00003772 // If this is the first instance of the name, remember the node.
3773 if (Rec.second++ == 0)
Florian Hahn6b1db822018-06-14 20:32:58 +00003774 Rec.first = P;
3775 else if (Rec.first->getExtTypes() != P->getExtTypes())
3776 PatternTop->error("repetition of value: $" + P->getName() +
Chris Lattner5b0e2492010-02-23 07:22:28 +00003777 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003778 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003779
Florian Hahn6b1db822018-06-14 20:32:58 +00003780 if (!P->isLeaf()) {
3781 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3782 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003783 }
3784}
3785
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003786std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3787 std::vector<Predicate> Preds;
3788 for (Init *I : L->getValues()) {
3789 if (DefInit *Pred = dyn_cast<DefInit>(I))
3790 Preds.push_back(Pred->getDef());
3791 else
3792 llvm_unreachable("Non-def on the list");
3793 }
3794
3795 // Sort so that different orders get canonicalized to the same string.
Fangrui Song0cac7262018-09-27 02:13:45 +00003796 llvm::sort(Preds);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003797 return Preds;
3798}
3799
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003800void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003801 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003802 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003803 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003804 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3805 PrintWarning(Pattern->getRecord()->getLoc(),
3806 Twine("Pattern can never match: ") + Reason);
3807 return;
3808 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003809
Chris Lattner1e634e32010-03-01 22:29:19 +00003810 // If the source pattern's root is a complex pattern, that complex pattern
3811 // must specify the nodes it can potentially match.
3812 if (const ComplexPattern *CP =
3813 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3814 if (CP->getRootNodes().empty())
3815 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3816 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003817
3818
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003819 // Find all of the named values in the input and output, ensure they have the
3820 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003821 std::map<std::string, NameRecord> SrcNames, DstNames;
Florian Hahn6b1db822018-06-14 20:32:58 +00003822 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3823 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003824
3825 // Scan all of the named values in the destination pattern, rejecting them if
3826 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003827 for (const auto &Entry : DstNames) {
3828 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003829 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003830 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003831 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003832
Chris Lattnera7722b62010-02-23 06:55:24 +00003833 // Scan all of the named values in the source pattern, rejecting them if the
3834 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003835 for (const auto &Entry : SrcNames)
3836 if (DstNames[Entry.first].first == nullptr &&
3837 SrcNames[Entry.first].second == 1)
3838 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003839
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003840 PatternsToMatch.push_back(PTM);
Chris Lattner0c0baa92010-02-23 06:16:51 +00003841}
3842
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003843void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003844 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003845 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003846
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003847 unsigned Errors = 0;
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003848
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003849 // Try to infer flags from all patterns in PatternToMatch. These include
3850 // both the primary instruction patterns (which always come first) and
3851 // patterns defined outside the instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003852 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003853 // We can only infer from single-instruction patterns, otherwise we won't
3854 // know which instruction should get the flags.
3855 SmallVector<Record*, 8> PatInstrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003856 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003857 if (PatInstrs.size() != 1)
3858 continue;
3859
3860 // Get the single instruction.
3861 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3862
3863 // Only infer properties from the first pattern. We'll verify the others.
3864 if (InstInfo.InferredFrom)
3865 continue;
3866
3867 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003868 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003869 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3870 }
3871
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003872 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003873 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003874
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003875 // If requested by the target, guess any undefined properties.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003876 if (Target.guessInstructionProperties()) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003877 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3878 CodeGenInstruction *InstInfo =
3879 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003880 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003881 continue;
3882 // The mayLoad and mayStore flags default to false.
3883 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003884 if (InstInfo->hasSideEffects_Unset)
3885 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003886 }
3887 return;
3888 }
3889
3890 // Complain about any flags that are still undefined.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003891 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3892 CodeGenInstruction *InstInfo =
3893 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003894 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003895 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003896 if (InstInfo->hasSideEffects_Unset)
3897 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003898 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003899 if (InstInfo->mayStore_Unset)
3900 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003901 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003902 if (InstInfo->mayLoad_Unset)
3903 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003904 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003905 }
3906}
3907
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003908
3909/// Verify instruction flags against pattern node properties.
3910void CodeGenDAGPatterns::VerifyInstructionFlags() {
3911 unsigned Errors = 0;
3912 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3913 const PatternToMatch &PTM = *I;
3914 SmallVector<Record*, 8> Instrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003915 getInstructionsInTree(PTM.getDstPattern(), Instrs);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003916 if (Instrs.empty())
3917 continue;
3918
3919 // Count the number of instructions with each flag set.
3920 unsigned NumSideEffects = 0;
3921 unsigned NumStores = 0;
3922 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003923 for (const Record *Instr : Instrs) {
3924 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003925 NumSideEffects += InstInfo.hasSideEffects;
3926 NumStores += InstInfo.mayStore;
3927 NumLoads += InstInfo.mayLoad;
3928 }
3929
3930 // Analyze the source pattern.
3931 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003932 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003933
3934 // Collect error messages.
3935 SmallVector<std::string, 4> Msgs;
3936
3937 // Check for missing flags in the output.
3938 // Permit extra flags for now at least.
3939 if (PatInfo.hasSideEffects && !NumSideEffects)
3940 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3941
3942 // Don't verify store flags on instructions with side effects. At least for
3943 // intrinsics, side effects implies mayStore.
3944 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3945 Msgs.push_back("pattern may store, but mayStore isn't set");
3946
3947 // Similarly, mayStore implies mayLoad on intrinsics.
3948 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3949 Msgs.push_back("pattern may load, but mayLoad isn't set");
3950
3951 // Print error messages.
3952 if (Msgs.empty())
3953 continue;
3954 ++Errors;
3955
Craig Topper306cb122015-11-22 20:46:24 +00003956 for (const std::string &Msg : Msgs)
3957 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003958 (Instrs.size() == 1 ?
3959 "instruction" : "output instructions"));
3960 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003961 for (const Record *Instr : Instrs) {
3962 if (Instr != PTM.getSrcRecord())
3963 PrintError(Instr->getLoc(), "defined here");
3964 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003965 if (InstInfo.InferredFrom &&
3966 InstInfo.InferredFrom != InstInfo.TheDef &&
3967 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003968 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003969 }
3970 }
3971 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003972 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003973}
3974
Chris Lattnercabe0372010-03-15 06:00:16 +00003975/// Given a pattern result with an unresolved type, see if we can find one
3976/// instruction with an unresolved result type. Force this result type to an
3977/// arbitrary element if it's possible types to converge results.
Florian Hahn6b1db822018-06-14 20:32:58 +00003978static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3979 if (N->isLeaf())
Chris Lattnercabe0372010-03-15 06:00:16 +00003980 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003981
Chris Lattnercabe0372010-03-15 06:00:16 +00003982 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003983 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3984 if (ForceArbitraryInstResultType(N->getChild(i), TP))
Chris Lattnercabe0372010-03-15 06:00:16 +00003985 return true;
3986
Florian Hahn6b1db822018-06-14 20:32:58 +00003987 if (!N->getOperator()->isSubClassOf("Instruction"))
Chris Lattnercabe0372010-03-15 06:00:16 +00003988 return false;
3989
3990 // If this type is already concrete or completely unknown we can't do
3991 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003992 TypeInfer &TI = TP.getInfer();
Florian Hahn6b1db822018-06-14 20:32:58 +00003993 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3994 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003995 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003996
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003997 // Otherwise, force its type to an arbitrary choice.
Florian Hahn6b1db822018-06-14 20:32:58 +00003998 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003999 return true;
4000 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004001
Chris Lattnerf1447252010-03-19 21:37:09 +00004002 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00004003}
4004
Ulrich Weigand58a97862018-08-01 11:57:58 +00004005// Promote xform function to be an explicit node wherever set.
4006static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4007 if (Record *Xform = N->getTransformFn()) {
4008 N->setTransformFn(nullptr);
4009 std::vector<TreePatternNodePtr> Children;
4010 Children.push_back(PromoteXForms(N));
4011 return std::make_shared<TreePatternNode>(Xform, std::move(Children),
4012 N->getNumTypes());
4013 }
4014
4015 if (!N->isLeaf())
4016 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4017 TreePatternNodePtr Child = N->getChildShared(i);
Ulrich Weigandf989cd72018-08-01 12:07:32 +00004018 N->setChild(i, PromoteXForms(Child));
Ulrich Weigand58a97862018-08-01 11:57:58 +00004019 }
4020 return N;
4021}
4022
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004023void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
4024 TreePattern &Pattern, TreePattern &Result,
4025 const std::vector<Record *> &InstImpResults) {
4026
4027 // Inline pattern fragments and expand multiple alternatives.
4028 Pattern.InlinePatternFragments();
4029 Result.InlinePatternFragments();
4030
4031 if (Result.getNumTrees() != 1)
4032 Result.error("Cannot use multi-alternative fragments in result pattern!");
4033
4034 // Infer types.
4035 bool IterateInference;
4036 bool InferredAllPatternTypes, InferredAllResultTypes;
4037 do {
4038 // Infer as many types as possible. If we cannot infer all of them, we
4039 // can never do anything with this pattern: report it to the user.
4040 InferredAllPatternTypes =
4041 Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
4042
4043 // Infer as many types as possible. If we cannot infer all of them, we
4044 // can never do anything with this pattern: report it to the user.
4045 InferredAllResultTypes =
4046 Result.InferAllTypes(&Pattern.getNamedNodesMap());
4047
4048 IterateInference = false;
4049
4050 // Apply the type of the result to the source pattern. This helps us
4051 // resolve cases where the input type is known to be a pointer type (which
4052 // is considered resolved), but the result knows it needs to be 32- or
4053 // 64-bits. Infer the other way for good measure.
4054 for (auto T : Pattern.getTrees())
4055 for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4056 T->getNumTypes());
4057 i != e; ++i) {
4058 IterateInference |= T->UpdateNodeType(
4059 i, Result.getOnlyTree()->getExtType(i), Result);
4060 IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4061 i, T->getExtType(i), Result);
4062 }
4063
4064 // If our iteration has converged and the input pattern's types are fully
4065 // resolved but the result pattern is not fully resolved, we may have a
4066 // situation where we have two instructions in the result pattern and
4067 // the instructions require a common register class, but don't care about
4068 // what actual MVT is used. This is actually a bug in our modelling:
4069 // output patterns should have register classes, not MVTs.
4070 //
4071 // In any case, to handle this, we just go through and disambiguate some
4072 // arbitrary types to the result pattern's nodes.
4073 if (!IterateInference && InferredAllPatternTypes &&
4074 !InferredAllResultTypes)
4075 IterateInference =
4076 ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4077 } while (IterateInference);
4078
4079 // Verify that we inferred enough types that we can do something with the
4080 // pattern and result. If these fire the user has to add type casts.
4081 if (!InferredAllPatternTypes)
4082 Pattern.error("Could not infer all types in pattern!");
4083 if (!InferredAllResultTypes) {
4084 Pattern.dump();
4085 Result.error("Could not infer all types in pattern result!");
4086 }
4087
Ulrich Weigand58a97862018-08-01 11:57:58 +00004088 // Promote xform function to be an explicit node wherever set.
4089 TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004090
4091 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4092 Temp.InferAllTypes();
4093
4094 ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4095 int Complexity = TheDef->getValueAsInt("AddedComplexity");
4096
4097 if (PatternRewriter)
4098 PatternRewriter(&Pattern);
4099
4100 // A pattern may end up with an "impossible" type, i.e. a situation
4101 // where all types have been eliminated for some node in this pattern.
4102 // This could occur for intrinsics that only make sense for a specific
4103 // value type, and use a specific register class. If, for some mode,
4104 // that register class does not accept that type, the type inference
4105 // will lead to a contradiction, which is not an error however, but
4106 // a sign that this pattern will simply never match.
4107 if (Temp.getOnlyTree()->hasPossibleType())
4108 for (auto T : Pattern.getTrees())
4109 if (T->hasPossibleType())
4110 AddPatternToMatch(&Pattern,
4111 PatternToMatch(TheDef, makePredList(Preds),
4112 T, Temp.getOnlyTree(),
4113 InstImpResults, Complexity,
4114 TheDef->getID()));
4115}
4116
Chris Lattnerab3242f2008-01-06 01:10:31 +00004117void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00004118 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4119
Craig Topper306cb122015-11-22 20:46:24 +00004120 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00004121 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00004122
4123 // If the pattern references the null_frag, there's nothing to do.
4124 if (hasNullFragReference(Tree))
4125 continue;
4126
Florian Hahn75e87c32018-05-30 21:00:18 +00004127 TreePattern Pattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00004128
David Greeneaf8ee2c2011-07-29 22:43:06 +00004129 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00004130 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004131
Chris Lattner8cab0212008-01-05 22:25:12 +00004132 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004133 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004134
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004135 if (Result.getNumTrees() != 1)
4136 Result.error("Cannot handle instructions producing instructions "
4137 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004138
Chris Lattner8cab0212008-01-05 22:25:12 +00004139 // Validate that the input pattern is correct.
Florian Hahn75e87c32018-05-30 21:00:18 +00004140 std::map<std::string, TreePatternNodePtr> InstInputs;
Craig Topperbd199f82018-12-05 00:47:59 +00004141 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
4142 InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00004143 std::vector<Record*> InstImpResults;
Florian Hahn75e87c32018-05-30 21:00:18 +00004144 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
David Blaikie19b22d42018-06-11 22:14:43 +00004145 FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
Florian Hahn75e87c32018-05-30 21:00:18 +00004146 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004147
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004148 ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004149 }
4150}
4151
Florian Hahn6b1db822018-06-14 20:32:58 +00004152static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004153 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4154 for (const auto &I : VTS)
4155 Modes.insert(I.first);
4156
4157 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00004158 collectModes(Modes, N->getChild(i));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004159}
4160
4161void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4162 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4163 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4164 std::vector<PatternToMatch> Copy = PatternsToMatch;
4165 PatternsToMatch.clear();
4166
Florian Hahn75e87c32018-05-30 21:00:18 +00004167 auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4168 TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4169 TreePatternNodePtr NewDst = P.DstPattern->clone();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004170 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004171 return;
4172 }
4173
4174 std::vector<Predicate> Preds = P.Predicates;
4175 const std::vector<Predicate> &MC = ModeChecks[Mode];
4176 Preds.insert(Preds.end(), MC.begin(), MC.end());
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004177 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4178 std::move(NewDst), P.getDstRegs(),
4179 P.getAddedComplexity(), Record::getNewUID(),
4180 Mode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004181 };
4182
4183 for (PatternToMatch &P : Copy) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004184 TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
Florian Hahn6b1db822018-06-14 20:32:58 +00004185 if (P.SrcPattern->hasProperTypeByHwMode())
4186 SrcP = P.SrcPattern;
4187 if (P.DstPattern->hasProperTypeByHwMode())
4188 DstP = P.DstPattern;
4189 if (!SrcP && !DstP) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004190 PatternsToMatch.push_back(P);
4191 continue;
4192 }
4193
4194 std::set<unsigned> Modes;
Florian Hahn6b1db822018-06-14 20:32:58 +00004195 if (SrcP)
4196 collectModes(Modes, SrcP.get());
4197 if (DstP)
4198 collectModes(Modes, DstP.get());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004199
4200 // The predicate for the default mode needs to be constructed for each
4201 // pattern separately.
4202 // Since not all modes must be present in each pattern, if a mode m is
4203 // absent, then there is no point in constructing a check for m. If such
4204 // a check was created, it would be equivalent to checking the default
4205 // mode, except not all modes' predicates would be a part of the checking
4206 // code. The subsequently generated check for the default mode would then
4207 // have the exact same patterns, but a different predicate code. To avoid
4208 // duplicated patterns with different predicate checks, construct the
4209 // default check as a negation of all predicates that are actually present
4210 // in the source/destination patterns.
4211 std::vector<Predicate> DefaultPred;
4212
4213 for (unsigned M : Modes) {
4214 if (M == DefaultMode)
4215 continue;
4216 if (ModeChecks.find(M) != ModeChecks.end())
4217 continue;
4218
4219 // Fill the map entry for this mode.
4220 const HwMode &HM = CGH.getMode(M);
4221 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4222
4223 // Add negations of the HM's predicates to the default predicate.
4224 DefaultPred.emplace_back(Predicate(HM.Features, false));
4225 }
4226
4227 for (unsigned M : Modes) {
4228 if (M == DefaultMode)
4229 continue;
4230 AppendPattern(P, M);
4231 }
4232
4233 bool HasDefault = Modes.count(DefaultMode);
4234 if (HasDefault)
4235 AppendPattern(P, DefaultMode);
4236 }
4237}
4238
4239/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004240typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004241
Florian Hahn6b1db822018-06-14 20:32:58 +00004242static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4243 if (N->isLeaf()) {
4244 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4245 DepMap[N->getName()]++;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004246 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00004247 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4248 FindDepVarsOf(N->getChild(i), DepMap);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004249 }
4250}
4251
4252/// Find dependent variables within child patterns
Florian Hahn6b1db822018-06-14 20:32:58 +00004253static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004254 DepVarMap depcounts;
4255 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004256 for (const auto &Pair : depcounts) {
4257 if (Pair.getValue() > 1)
4258 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004259 }
4260}
4261
4262#ifndef NDEBUG
4263/// Dump the dependent variable set:
4264static void DumpDepVars(MultipleUseVarSet &DepVars) {
4265 if (DepVars.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004266 LLVM_DEBUG(errs() << "<empty set>");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004267 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004268 LLVM_DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004269 for (const auto &DepVar : DepVars) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004270 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004271 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004272 LLVM_DEBUG(errs() << "]");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004273 }
4274}
4275#endif
4276
4277
Chris Lattner8cab0212008-01-05 22:25:12 +00004278/// CombineChildVariants - Given a bunch of permutations of each child of the
4279/// 'operator' node, put them together in all possible ways.
Florian Hahn75e87c32018-05-30 21:00:18 +00004280static void CombineChildVariants(
Florian Hahn6b1db822018-06-14 20:32:58 +00004281 TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004282 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4283 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4284 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004285 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004286 for (const auto &Variants : ChildVariants)
4287 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004288 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004289
Chris Lattner8cab0212008-01-05 22:25:12 +00004290 // The end result is an all-pairs construction of the resultant pattern.
4291 std::vector<unsigned> Idxs;
4292 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004293 bool NotDone;
4294 do {
4295#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004296 LLVM_DEBUG(if (!Idxs.empty()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004297 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004298 for (unsigned Idx : Idxs) {
4299 errs() << Idx << " ";
4300 }
4301 errs() << "]\n";
4302 });
Scott Michel94420742008-03-05 17:49:05 +00004303#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004304 // Create the variant and add it to the output list.
Florian Hahn75e87c32018-05-30 21:00:18 +00004305 std::vector<TreePatternNodePtr> NewChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004306 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4307 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Florian Hahn75e87c32018-05-30 21:00:18 +00004308 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00004309 Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004310
Chris Lattner8cab0212008-01-05 22:25:12 +00004311 // Copy over properties.
Florian Hahn6b1db822018-06-14 20:32:58 +00004312 R->setName(Orig->getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00004313 R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4314 R->setPredicateCalls(Orig->getPredicateCalls());
Florian Hahn6b1db822018-06-14 20:32:58 +00004315 R->setTransformFn(Orig->getTransformFn());
4316 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4317 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004318
Scott Michel94420742008-03-05 17:49:05 +00004319 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004320 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004321 // Scan to see if this pattern has already been emitted. We can get
4322 // duplication due to things like commuting:
4323 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4324 // which are the same pattern. Ignore the dups.
4325 if (R->canPatternMatch(ErrString, CDP) &&
Florian Hahn75e87c32018-05-30 21:00:18 +00004326 none_of(OutVariants, [&](TreePatternNodePtr Variant) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004327 return R->isIsomorphicTo(Variant.get(), DepVars);
David Majnemer0a16c222016-08-11 21:15:00 +00004328 }))
Florian Hahn75e87c32018-05-30 21:00:18 +00004329 OutVariants.push_back(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004330
Scott Michel94420742008-03-05 17:49:05 +00004331 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004332 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004333 // [0, 0], [0, 1], [1, 0], [1, 1].
4334 int IdxsIdx;
4335 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4336 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4337 Idxs[IdxsIdx] = 0;
4338 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004339 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004340 }
Scott Michel94420742008-03-05 17:49:05 +00004341 NotDone = (IdxsIdx >= 0);
4342 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004343}
4344
4345/// CombineChildVariants - A helper function for binary operators.
4346///
Florian Hahn6b1db822018-06-14 20:32:58 +00004347static void CombineChildVariants(TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004348 const std::vector<TreePatternNodePtr> &LHS,
4349 const std::vector<TreePatternNodePtr> &RHS,
4350 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004351 CodeGenDAGPatterns &CDP,
4352 const MultipleUseVarSet &DepVars) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004353 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004354 ChildVariants.push_back(LHS);
4355 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004356 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004357}
Chris Lattner8cab0212008-01-05 22:25:12 +00004358
Florian Hahn75e87c32018-05-30 21:00:18 +00004359static void
Florian Hahn6b1db822018-06-14 20:32:58 +00004360GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004361 std::vector<TreePatternNodePtr> &Children) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004362 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4363 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004364
Chris Lattner8cab0212008-01-05 22:25:12 +00004365 // Only permit raw nodes.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00004366 if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004367 N->getTransformFn()) {
4368 Children.push_back(N);
4369 return;
4370 }
4371
Florian Hahn6b1db822018-06-14 20:32:58 +00004372 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004373 Children.push_back(N->getChildShared(0));
Chris Lattner8cab0212008-01-05 22:25:12 +00004374 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004375 GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004376
Florian Hahn6b1db822018-06-14 20:32:58 +00004377 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004378 Children.push_back(N->getChildShared(1));
Chris Lattner8cab0212008-01-05 22:25:12 +00004379 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004380 GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004381}
4382
4383/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4384/// the (potentially recursive) pattern by using algebraic laws.
4385///
Florian Hahn6b1db822018-06-14 20:32:58 +00004386static void GenerateVariantsOf(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004387 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004388 CodeGenDAGPatterns &CDP,
4389 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004390 // We cannot permute leaves or ComplexPattern uses.
4391 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004392 OutVariants.push_back(N);
4393 return;
4394 }
4395
4396 // Look up interesting info about the node.
4397 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4398
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004399 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004400 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004401 // Re-associate by pulling together all of the linked operators
Florian Hahn75e87c32018-05-30 21:00:18 +00004402 std::vector<TreePatternNodePtr> MaximalChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004403 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4404
4405 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4406 // permutations.
4407 if (MaximalChildren.size() == 3) {
4408 // Find the variants of all of our maximal children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004409 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004410 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4411 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4412 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004413
Chris Lattner8cab0212008-01-05 22:25:12 +00004414 // There are only two ways we can permute the tree:
4415 // (A op B) op C and A op (B op C)
4416 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004417
Chris Lattner8cab0212008-01-05 22:25:12 +00004418 // Generate legal pair permutations of A/B/C.
Florian Hahn75e87c32018-05-30 21:00:18 +00004419 std::vector<TreePatternNodePtr> ABVariants;
4420 std::vector<TreePatternNodePtr> BAVariants;
4421 std::vector<TreePatternNodePtr> ACVariants;
4422 std::vector<TreePatternNodePtr> CAVariants;
4423 std::vector<TreePatternNodePtr> BCVariants;
4424 std::vector<TreePatternNodePtr> CBVariants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004425 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4426 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4427 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4428 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4429 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4430 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004431
4432 // Combine those into the result: (x op x) op x
Florian Hahn6b1db822018-06-14 20:32:58 +00004433 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4434 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4435 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4436 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4437 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4438 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004439
4440 // Combine those into the result: x op (x op x)
Florian Hahn6b1db822018-06-14 20:32:58 +00004441 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4442 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4443 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4444 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4445 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4446 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004447 return;
4448 }
4449 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004450
Chris Lattner8cab0212008-01-05 22:25:12 +00004451 // Compute permutations of all children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004452 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004453 ChildVariants.resize(N->getNumChildren());
4454 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn75e87c32018-05-30 21:00:18 +00004455 GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004456
4457 // Build all permutations based on how the children were formed.
Florian Hahn6b1db822018-06-14 20:32:58 +00004458 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004459
4460 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004461 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4462 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004463 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004464 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004465 // Don't count children which are actually register references.
4466 unsigned NC = 0;
4467 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004468 TreePatternNode *Child = N->getChild(i);
4469 if (Child->isLeaf())
4470 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004471 Record *RR = DI->getDef();
4472 if (RR->isSubClassOf("Register"))
4473 continue;
4474 }
4475 NC++;
4476 }
4477 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004478 if (isCommIntrinsic) {
4479 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4480 // operands are the commutative operands, and there might be more operands
4481 // after those.
4482 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004483 "Commutative intrinsic should have at least 3 children!");
Florian Hahn75e87c32018-05-30 21:00:18 +00004484 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004485 Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4486 Variants.push_back(std::move(ChildVariants[2]));
4487 Variants.push_back(std::move(ChildVariants[1]));
Evan Cheng49bad4c2008-06-16 20:29:38 +00004488 for (unsigned i = 3; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004489 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004490 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004491 } else if (NC == N->getNumChildren()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004492 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004493 Variants.push_back(std::move(ChildVariants[1]));
4494 Variants.push_back(std::move(ChildVariants[0]));
Craig Topper98a96282017-09-04 03:44:33 +00004495 for (unsigned i = 2; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004496 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004497 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004498 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004499 }
4500}
4501
4502
4503// GenerateVariants - Generate variants. For example, commutative patterns can
4504// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004505void CodeGenDAGPatterns::GenerateVariants() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004506 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004507
Chris Lattner8cab0212008-01-05 22:25:12 +00004508 // Loop over all of the patterns we've collected, checking to see if we can
4509 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004510 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004511 // the .td file having to contain tons of variants of instructions.
4512 //
4513 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4514 // intentionally do not reconsider these. Any variants of added patterns have
4515 // already been added.
4516 //
Simon Pilgrim0621f562018-09-18 11:30:30 +00004517 const unsigned NumOriginalPatterns = PatternsToMatch.size();
4518 BitVector MatchedPatterns(NumOriginalPatterns);
4519 std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
4520 BitVector(NumOriginalPatterns));
4521
4522 typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
4523 DepsAndVariants;
4524 std::map<unsigned, DepsAndVariants> PatternsWithVariants;
4525
4526 // Collect patterns with more than one variant.
4527 for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
4528 MultipleUseVarSet DepVars;
Florian Hahn75e87c32018-05-30 21:00:18 +00004529 std::vector<TreePatternNodePtr> Variants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004530 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004531 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4532 LLVM_DEBUG(DumpDepVars(DepVars));
4533 LLVM_DEBUG(errs() << "\n");
Florian Hahn75e87c32018-05-30 21:00:18 +00004534 GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4535 *this, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004536
4537 assert(!Variants.empty() && "Must create at least original variant!");
Simon Pilgrim0621f562018-09-18 11:30:30 +00004538 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004539 continue;
4540
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004541 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4542 PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004543
Simon Pilgrim0621f562018-09-18 11:30:30 +00004544 PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
4545
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004546 // Cache matching predicates.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004547 if (MatchedPatterns[i])
4548 continue;
4549
4550 const std::vector<Predicate> &Predicates =
4551 PatternsToMatch[i].getPredicates();
4552
4553 BitVector &Matches = MatchedPredicates[i];
Simon Pilgrim6d706772018-09-19 12:23:50 +00004554 MatchedPatterns.set(i);
4555 Matches.set(i);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004556
4557 // Don't test patterns that have already been cached - it won't match.
4558 for (unsigned p = 0; p != NumOriginalPatterns; ++p)
4559 if (!MatchedPatterns[p])
4560 Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
4561
4562 // Copy this to all the matching patterns.
4563 for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
Simon Pilgrime3c6f8d2018-09-18 12:01:25 +00004564 if (p != (int)i) {
Simon Pilgrim6d706772018-09-19 12:23:50 +00004565 MatchedPatterns.set(p);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004566 MatchedPredicates[p] = Matches;
4567 }
4568 }
4569
4570 for (auto it : PatternsWithVariants) {
4571 unsigned i = it.first;
4572 const MultipleUseVarSet &DepVars = it.second.first;
4573 const std::vector<TreePatternNodePtr> &Variants = it.second.second;
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004574
Chris Lattner8cab0212008-01-05 22:25:12 +00004575 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004576 TreePatternNodePtr Variant = Variants[v];
Simon Pilgrim0621f562018-09-18 11:30:30 +00004577 BitVector &Matches = MatchedPredicates[i];
Chris Lattner8cab0212008-01-05 22:25:12 +00004578
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004579 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4580 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004581
Chris Lattner8cab0212008-01-05 22:25:12 +00004582 // Scan to see if an instruction or explicit pattern already matches this.
4583 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004584 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004585 // Skip if the top level predicates do not match.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004586 if (!Matches[p])
Evan Cheng34c8c742009-06-26 05:59:16 +00004587 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004588 // Check to see if this variant already exists.
Florian Hahn6b1db822018-06-14 20:32:58 +00004589 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004590 DepVars)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004591 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004592 AlreadyExists = true;
4593 break;
4594 }
4595 }
4596 // If we already have it, ignore the variant.
4597 if (AlreadyExists) continue;
4598
4599 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004600 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004601 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
Florian Hahn75e87c32018-05-30 21:00:18 +00004602 Variant, PatternsToMatch[i].getDstPatternShared(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004603 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004604 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Simon Pilgrim0621f562018-09-18 11:30:30 +00004605 MatchedPredicates.push_back(Matches);
4606
Simon Pilgrimb2444352018-09-18 14:05:07 +00004607 // Add a new match the same as this pattern.
Simon Pilgrimb2444352018-09-18 14:05:07 +00004608 for (auto &P : MatchedPredicates)
Simon Pilgrim429df292018-09-19 11:18:49 +00004609 P.push_back(P[i]);
Chris Lattner8cab0212008-01-05 22:25:12 +00004610 }
4611
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004612 LLVM_DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004613 }
4614}