blob: 703cd515a071b353e79d606cc51357236931a3f7 [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"
Graham Hunter3f08ad62019-08-14 11:48:39 +010026#include "llvm/Support/TypeSize.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000027#include "llvm/TableGen/Error.h"
28#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000029#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000030#include <cstdio>
Craig Topperbd199f82018-12-05 00:47:59 +000031#include <iterator>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000032#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000033using namespace llvm;
34
Chandler Carruthe96dd892014-04-21 22:55:11 +000035#define DEBUG_TYPE "dag-patterns"
36
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000037static inline bool isIntegerOrPtr(MVT VT) {
38 return VT.isInteger() || VT == MVT::iPTR;
Duncan Sands13237ac2008-06-06 12:08:01 +000039}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000040static inline bool isFloatingPoint(MVT VT) {
41 return VT.isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000042}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000043static inline bool isVector(MVT VT) {
44 return VT.isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000045}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000046static inline bool isScalar(MVT VT) {
47 return !VT.isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000048}
Duncan Sands13237ac2008-06-06 12:08:01 +000049
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000050template <typename Predicate>
51static bool berase_if(MachineValueTypeSet &S, Predicate P) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000052 bool Erased = false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000053 // It is ok to iterate over MachineValueTypeSet and remove elements from it
54 // at the same time.
55 for (MVT T : S) {
56 if (!P(T))
57 continue;
58 Erased = true;
59 S.erase(T);
Chris Lattnercabe0372010-03-15 06:00:16 +000060 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000061 return Erased;
Chris Lattner8cab0212008-01-05 22:25:12 +000062}
63
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000064// --- TypeSetByHwMode
Chris Lattnercabe0372010-03-15 06:00:16 +000065
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000066// This is a parameterized type-set class. For each mode there is a list
67// of types that are currently possible for a given tree node. Type
68// inference will apply to each mode separately.
Jim Grosbach65586fe2010-12-21 16:16:00 +000069
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000070TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
Tom Stellard9ad714f2019-02-20 19:43:47 +000071 for (const ValueTypeByHwMode &VVT : VTList) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000072 insert(VVT);
Tom Stellard9ad714f2019-02-20 19:43:47 +000073 AddrSpaces.push_back(VVT.PtrAddrSpace);
74 }
Chris Lattner8cab0212008-01-05 22:25:12 +000075}
76
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000077bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
78 for (const auto &I : *this) {
79 if (I.second.size() > 1)
80 return false;
81 if (!AllowEmpty && I.second.empty())
82 return false;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000083 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000084 return true;
85}
Chris Lattnercabe0372010-03-15 06:00:16 +000086
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000087ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
88 assert(isValueTypeByHwMode(true) &&
89 "The type set has multiple types for at least one HW mode");
90 ValueTypeByHwMode VVT;
Tom Stellard9ad714f2019-02-20 19:43:47 +000091 auto ASI = AddrSpaces.begin();
92
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000093 for (const auto &I : *this) {
94 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
95 VVT.getOrCreateTypeForMode(I.first, T);
Tom Stellard9ad714f2019-02-20 19:43:47 +000096 if (ASI != AddrSpaces.end())
97 VVT.PtrAddrSpace = *ASI++;
Chris Lattnercabe0372010-03-15 06:00:16 +000098 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000099 return VVT;
Bob Wilson2cd5da82009-08-11 01:14:02 +0000100}
Chris Lattnercabe0372010-03-15 06:00:16 +0000101
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000102bool TypeSetByHwMode::isPossible() const {
103 for (const auto &I : *this)
104 if (!I.second.empty())
105 return true;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000106 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000107}
108
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000109bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
110 bool Changed = false;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000111 bool ContainsDefault = false;
112 MVT DT = MVT::Other;
113
Zachary Turner249dc142017-09-20 18:01:40 +0000114 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000115 for (const auto &P : VVT) {
116 unsigned M = P.first;
117 Modes.insert(M);
118 // Make sure there exists a set for each specific mode from VVT.
119 Changed |= getOrCreate(M).insert(P.second).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000120 // Cache VVT's default mode.
121 if (DefaultMode == M) {
122 ContainsDefault = true;
123 DT = P.second;
124 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000125 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000126
127 // If VVT has a default mode, add the corresponding type to all
128 // modes in "this" that do not exist in VVT.
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000129 if (ContainsDefault)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000130 for (auto &I : *this)
131 if (!Modes.count(I.first))
132 Changed |= I.second.insert(DT).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000133
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000134 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000135}
136
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000137// Constrain the type set to be the intersection with VTS.
138bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
139 bool Changed = false;
140 if (hasDefault()) {
141 for (const auto &I : VTS) {
142 unsigned M = I.first;
143 if (M == DefaultMode || hasMode(M))
144 continue;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000145 Map.insert({M, Map.at(DefaultMode)});
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000146 Changed = true;
147 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000148 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000149
150 for (auto &I : *this) {
151 unsigned M = I.first;
152 SetType &S = I.second;
153 if (VTS.hasMode(M) || VTS.hasDefault()) {
154 Changed |= intersect(I.second, VTS.get(M));
155 } else if (!S.empty()) {
156 S.clear();
157 Changed = true;
158 }
159 }
160 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000161}
162
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000163template <typename Predicate>
164bool TypeSetByHwMode::constrain(Predicate P) {
165 bool Changed = false;
166 for (auto &I : *this)
Benjamin Kramere57308e2017-09-17 11:19:53 +0000167 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000168 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000169}
170
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000171template <typename Predicate>
172bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
173 assert(empty());
174 for (const auto &I : VTS) {
175 SetType &S = getOrCreate(I.first);
176 for (auto J : I.second)
177 if (P(J))
178 S.insert(J);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000179 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000180 return !empty();
Chris Lattnercabe0372010-03-15 06:00:16 +0000181}
182
Zachary Turner249dc142017-09-20 18:01:40 +0000183void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
184 SmallVector<unsigned, 4> Modes;
185 Modes.reserve(Map.size());
Chris Lattnercabe0372010-03-15 06:00:16 +0000186
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000187 for (const auto &I : *this)
188 Modes.push_back(I.first);
Zachary Turner249dc142017-09-20 18:01:40 +0000189 if (Modes.empty()) {
190 OS << "{}";
191 return;
192 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000193 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000194
Zachary Turner249dc142017-09-20 18:01:40 +0000195 OS << '{';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000196 for (unsigned M : Modes) {
Zachary Turner249dc142017-09-20 18:01:40 +0000197 OS << ' ' << getModeName(M) << ':';
198 writeToStream(get(M), OS);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000199 }
Zachary Turner249dc142017-09-20 18:01:40 +0000200 OS << " }";
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000201}
202
Zachary Turner249dc142017-09-20 18:01:40 +0000203void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
204 SmallVector<MVT, 4> Types(S.begin(), S.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000205 array_pod_sort(Types.begin(), Types.end());
206
Zachary Turner249dc142017-09-20 18:01:40 +0000207 OS << '[';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000208 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
Zachary Turner249dc142017-09-20 18:01:40 +0000209 OS << ValueTypeByHwMode::getMVTName(Types[i]);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000210 if (i != e-1)
Zachary Turner249dc142017-09-20 18:01:40 +0000211 OS << ' ';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000212 }
Zachary Turner249dc142017-09-20 18:01:40 +0000213 OS << ']';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000214}
215
216bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
Simon Pilgrim0e181332018-08-16 16:16:28 +0000217 // The isSimple call is much quicker than hasDefault - check this first.
218 bool IsSimple = isSimple();
219 bool VTSIsSimple = VTS.isSimple();
220 if (IsSimple && VTSIsSimple)
221 return *begin() == *VTS.begin();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000222
Simon Pilgrim0e181332018-08-16 16:16:28 +0000223 // Speedup: We have a default if the set is simple.
224 bool HaveDefault = IsSimple || hasDefault();
225 bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
226 if (HaveDefault != VTSHaveDefault)
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000227 return false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000228
Zachary Turner249dc142017-09-20 18:01:40 +0000229 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000230 for (auto &I : *this)
231 Modes.insert(I.first);
232 for (const auto &I : VTS)
233 Modes.insert(I.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000234
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000235 if (HaveDefault) {
236 // Both sets have default mode.
237 for (unsigned M : Modes) {
238 if (get(M) != VTS.get(M))
David Majnemerc7004902016-08-12 04:32:37 +0000239 return false;
Craig Topper5712d462015-11-24 08:20:47 +0000240 }
Scott Michel94420742008-03-05 17:49:05 +0000241 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000242 // Neither set has default mode.
243 for (unsigned M : Modes) {
244 // If there is no default mode, an empty set is equivalent to not having
245 // the corresponding mode.
246 bool NoModeThis = !hasMode(M) || get(M).empty();
247 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
248 if (NoModeThis != NoModeVTS)
249 return false;
250 if (!NoModeThis)
251 if (get(M) != VTS.get(M))
252 return false;
253 }
Scott Michel94420742008-03-05 17:49:05 +0000254 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000255
256 return true;
Scott Michel94420742008-03-05 17:49:05 +0000257}
258
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000259namespace llvm {
260 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
261 T.writeToStream(OS);
262 return OS;
263 }
264}
265
Krzysztof Parzyszek426bf362017-09-12 15:31:26 +0000266LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000267void TypeSetByHwMode::dump() const {
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000268 dbgs() << *this << '\n';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000269}
270
271bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
272 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
273 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
274
275 if (OutP == InP)
276 return berase_if(Out, Int);
277
278 // Compute the intersection of scalars separately to account for only
279 // one set containing iPTR.
280 // The itersection of iPTR with a set of integer scalar types that does not
281 // include iPTR will result in the most specific scalar type:
282 // - iPTR is more specific than any set with two elements or more
283 // - iPTR is less specific than any single integer scalar type.
284 // For example
285 // { iPTR } * { i32 } -> { i32 }
286 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000287 // and
288 // { iPTR i32 } * { i32 } -> { i32 }
289 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
290 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000291
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000292 // Compute the difference between the two sets in such a way that the
293 // iPTR is in the set that is being subtracted. This is to see if there
294 // are any extra scalars in the set without iPTR that are not in the
295 // set containing iPTR. Then the iPTR could be considered a "wildcard"
296 // matching these scalars. If there is only one such scalar, it would
297 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000298 SetType Diff;
299 if (InP) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000300 Diff = Out;
301 berase_if(Diff, [&In](MVT T) { return In.count(T); });
302 // Pre-remove these elements and rely only on InP/OutP to determine
303 // whether a change has been made.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000304 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000305 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000306 Diff = In;
307 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000308 Out.erase(MVT::iPTR);
309 }
310
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000311 // The actual intersection.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000312 bool Changed = berase_if(Out, Int);
313 unsigned NumD = Diff.size();
314 if (NumD == 0)
315 return Changed;
316
317 if (NumD == 1) {
318 Out.insert(*Diff.begin());
319 // This is a change only if Out was the one with iPTR (which is now
320 // being replaced).
321 Changed |= OutP;
322 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000323 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000324 Out.insert(MVT::iPTR);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000325 Changed |= !OutP;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000326 }
327 return Changed;
328}
329
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000330bool TypeSetByHwMode::validate() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000331#ifndef NDEBUG
332 if (empty())
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000333 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000334 bool AllEmpty = true;
335 for (const auto &I : *this)
336 AllEmpty &= I.second.empty();
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000337 return !AllEmpty;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000338#endif
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000339 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000340}
341
342// --- TypeInfer
343
344bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
345 const TypeSetByHwMode &In) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000346 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000347 In.validate();
348 if (In.empty() || Out == In || TP.hasError())
349 return false;
350 if (Out.empty()) {
351 Out = In;
352 return true;
353 }
354
355 bool Changed = Out.constrain(In);
356 if (Changed && Out.empty())
357 TP.error("Type contradiction");
358
359 return Changed;
360}
361
362bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000363 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000364 if (TP.hasError())
365 return false;
366 assert(!Out.empty() && "cannot pick from an empty set");
367
368 bool Changed = false;
369 for (auto &I : Out) {
370 TypeSetByHwMode::SetType &S = I.second;
371 if (S.size() <= 1)
372 continue;
373 MVT T = *S.begin(); // Pick the first element.
374 S.clear();
375 S.insert(T);
376 Changed = true;
377 }
378 return Changed;
379}
380
381bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000382 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000383 if (TP.hasError())
384 return false;
385 if (!Out.empty())
386 return Out.constrain(isIntegerOrPtr);
387
388 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
389}
390
391bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000392 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000393 if (TP.hasError())
394 return false;
395 if (!Out.empty())
396 return Out.constrain(isFloatingPoint);
397
398 return Out.assign_if(getLegalTypes(), isFloatingPoint);
399}
400
401bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000402 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000403 if (TP.hasError())
404 return false;
405 if (!Out.empty())
406 return Out.constrain(isScalar);
407
408 return Out.assign_if(getLegalTypes(), isScalar);
409}
410
411bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000412 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000413 if (TP.hasError())
414 return false;
415 if (!Out.empty())
416 return Out.constrain(isVector);
417
418 return Out.assign_if(getLegalTypes(), isVector);
419}
420
421bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000422 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000423 if (TP.hasError() || !Out.empty())
424 return false;
425
426 Out = getLegalTypes();
427 return true;
428}
429
430template <typename Iter, typename Pred, typename Less>
431static Iter min_if(Iter B, Iter E, Pred P, Less L) {
432 if (B == E)
433 return E;
434 Iter Min = E;
435 for (Iter I = B; I != E; ++I) {
436 if (!P(*I))
437 continue;
438 if (Min == E || L(*I, *Min))
439 Min = I;
440 }
441 return Min;
442}
443
444template <typename Iter, typename Pred, typename Less>
445static Iter max_if(Iter B, Iter E, Pred P, Less L) {
446 if (B == E)
447 return E;
448 Iter Max = E;
449 for (Iter I = B; I != E; ++I) {
450 if (!P(*I))
451 continue;
452 if (Max == E || L(*Max, *I))
453 Max = I;
454 }
455 return Max;
456}
457
458/// Make sure that for each type in Small, there exists a larger type in Big.
459bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
460 TypeSetByHwMode &Big) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000461 ValidateOnExit _1(Small, *this), _2(Big, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000462 if (TP.hasError())
463 return false;
464 bool Changed = false;
465
466 if (Small.empty())
467 Changed |= EnforceAny(Small);
468 if (Big.empty())
469 Changed |= EnforceAny(Big);
470
471 assert(Small.hasDefault() && Big.hasDefault());
472
473 std::vector<unsigned> Modes = union_modes(Small, Big);
474
475 // 1. Only allow integer or floating point types and make sure that
476 // both sides are both integer or both floating point.
477 // 2. Make sure that either both sides have vector types, or neither
478 // of them does.
479 for (unsigned M : Modes) {
480 TypeSetByHwMode::SetType &S = Small.get(M);
481 TypeSetByHwMode::SetType &B = Big.get(M);
482
Dávid Bolvanskýfe1a1d52019-11-02 19:02:33 +0100483 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000484 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Simon Pilgrim2b2adef2019-11-02 22:38:07 +0000485 Changed |= berase_if(S, NotInt);
486 Changed |= berase_if(B, NotInt);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000487 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000488 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Simon Pilgrim2b2adef2019-11-02 22:38:07 +0000489 Changed |= berase_if(S, NotFP);
490 Changed |= berase_if(B, NotFP);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000491 } else if (S.empty() || B.empty()) {
492 Changed = !S.empty() || !B.empty();
493 S.clear();
494 B.clear();
495 } else {
496 TP.error("Incompatible types");
497 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000498 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000499
500 if (none_of(S, isVector) || none_of(B, isVector)) {
Simon Pilgrim2b2adef2019-11-02 22:38:07 +0000501 Changed |= berase_if(S, isVector);
502 Changed |= berase_if(B, isVector);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000503 }
504 }
505
506 auto LT = [](MVT A, MVT B) -> bool {
Graham Hunter3f08ad62019-08-14 11:48:39 +0100507 // Always treat non-scalable MVTs as smaller than scalable MVTs for the
508 // purposes of ordering.
509 auto ASize = std::make_tuple(A.isScalableVector(), A.getScalarSizeInBits(),
510 A.getSizeInBits());
511 auto BSize = std::make_tuple(B.isScalableVector(), B.getScalarSizeInBits(),
512 B.getSizeInBits());
513 return ASize < BSize;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000514 };
Graham Hunter3f08ad62019-08-14 11:48:39 +0100515 auto SameKindLE = [](MVT A, MVT B) -> bool {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000516 // This function is used when removing elements: when a vector is compared
Graham Hunter3f08ad62019-08-14 11:48:39 +0100517 // to a non-vector or a scalable vector to any non-scalable MVT, it should
518 // return false (to avoid removal).
519 if (std::make_tuple(A.isVector(), A.isScalableVector()) !=
520 std::make_tuple(B.isVector(), B.isScalableVector()))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000521 return false;
522
Graham Hunter3f08ad62019-08-14 11:48:39 +0100523 return std::make_tuple(A.getScalarSizeInBits(), A.getSizeInBits()) <=
524 std::make_tuple(B.getScalarSizeInBits(), B.getSizeInBits());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000525 };
526
527 for (unsigned M : Modes) {
528 TypeSetByHwMode::SetType &S = Small.get(M);
529 TypeSetByHwMode::SetType &B = Big.get(M);
530 // MinS = min scalar in Small, remove all scalars from Big that are
531 // smaller-or-equal than MinS.
532 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000533 if (MinS != S.end())
Graham Hunter3f08ad62019-08-14 11:48:39 +0100534 Changed |= berase_if(B, std::bind(SameKindLE,
535 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())
Graham Hunter3f08ad62019-08-14 11:48:39 +0100541 Changed |= berase_if(S, std::bind(SameKindLE,
542 *MaxS, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000543
544 // MinV = min vector in Small, remove all vectors from Big that are
545 // smaller-or-equal than MinV.
546 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000547 if (MinV != S.end())
Graham Hunter3f08ad62019-08-14 11:48:39 +0100548 Changed |= berase_if(B, std::bind(SameKindLE,
549 std::placeholders::_1, *MinV));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000550
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000551 // MaxV = max vector in Big, remove all vectors from Small that are
552 // larger than MaxV.
553 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000554 if (MaxV != B.end())
Graham Hunter3f08ad62019-08-14 11:48:39 +0100555 Changed |= berase_if(S, std::bind(SameKindLE,
556 *MaxV, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000557 }
558
559 return Changed;
560}
561
562/// 1. Ensure that for each type T in Vec, T is a vector type, and that
563/// for each type U in Elem, U is a scalar type.
564/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
565/// type T in Vec, such that U is the element type of T.
566bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
567 TypeSetByHwMode &Elem) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000568 ValidateOnExit _1(Vec, *this), _2(Elem, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000569 if (TP.hasError())
570 return false;
571 bool Changed = false;
572
573 if (Vec.empty())
574 Changed |= EnforceVector(Vec);
575 if (Elem.empty())
576 Changed |= EnforceScalar(Elem);
577
578 for (unsigned M : union_modes(Vec, Elem)) {
579 TypeSetByHwMode::SetType &V = Vec.get(M);
580 TypeSetByHwMode::SetType &E = Elem.get(M);
581
582 Changed |= berase_if(V, isScalar); // Scalar = !vector
583 Changed |= berase_if(E, isVector); // Vector = !scalar
584 assert(!V.empty() && !E.empty());
585
586 SmallSet<MVT,4> VT, ST;
587 // Collect element types from the "vector" set.
588 for (MVT T : V)
589 VT.insert(T.getVectorElementType());
590 // Collect scalar types from the "element" set.
591 for (MVT T : E)
592 ST.insert(T);
593
594 // Remove from V all (vector) types whose element type is not in S.
595 Changed |= berase_if(V, [&ST](MVT T) -> bool {
596 return !ST.count(T.getVectorElementType());
597 });
598 // Remove from E all (scalar) types, for which there is no corresponding
599 // type in V.
600 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000601 }
602
603 return Changed;
604}
605
606bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
607 const ValueTypeByHwMode &VVT) {
608 TypeSetByHwMode Tmp(VVT);
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000609 ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000610 return EnforceVectorEltTypeIs(Vec, Tmp);
611}
612
613/// Ensure that for each type T in Sub, T is a vector type, and there
614/// exists a type U in Vec such that U is a vector type with the same
615/// element type as T and at least as many elements as T.
616bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
617 TypeSetByHwMode &Sub) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000618 ValidateOnExit _1(Vec, *this), _2(Sub, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000619 if (TP.hasError())
620 return false;
621
622 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
623 auto IsSubVec = [](MVT B, MVT P) -> bool {
624 if (!B.isVector() || !P.isVector())
625 return false;
Florian Hahn603c6452017-11-07 10:43:56 +0000626 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
627 // but until there are obvious use-cases for this, keep the
628 // types separate.
629 if (B.isScalableVector() != P.isScalableVector())
630 return false;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000631 if (B.getVectorElementType() != P.getVectorElementType())
632 return false;
633 return B.getVectorNumElements() < P.getVectorNumElements();
634 };
635
636 /// Return true if S has no element (vector type) that T is a sub-vector of,
637 /// i.e. has the same element type as T and more elements.
638 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
Mark de Wevere8d448e2019-12-22 18:58:32 +0100639 for (auto I : S)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000640 if (IsSubVec(T, I))
641 return false;
642 return true;
643 };
644
645 /// Return true if S has no element (vector type) that T is a super-vector
646 /// of, i.e. has the same element type as T and fewer elements.
647 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
Mark de Wevere8d448e2019-12-22 18:58:32 +0100648 for (auto I : S)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000649 if (IsSubVec(I, T))
650 return false;
651 return true;
652 };
653
654 bool Changed = false;
655
656 if (Vec.empty())
657 Changed |= EnforceVector(Vec);
658 if (Sub.empty())
659 Changed |= EnforceVector(Sub);
660
661 for (unsigned M : union_modes(Vec, Sub)) {
662 TypeSetByHwMode::SetType &S = Sub.get(M);
663 TypeSetByHwMode::SetType &V = Vec.get(M);
664
665 Changed |= berase_if(S, isScalar);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000666
667 // Erase all types from S that are not sub-vectors of a type in V.
668 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000669
670 // Erase all types from V that are not super-vectors of a type in S.
671 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000672 }
673
674 return Changed;
675}
676
677/// 1. Ensure that V has a scalar type iff W has a scalar type.
678/// 2. Ensure that for each vector type T in V, there exists a vector
679/// type U in W, such that T and U have the same number of elements.
680/// 3. Ensure that for each vector type U in W, there exists a vector
681/// type T in V, such that T and U have the same number of elements
682/// (reverse of 2).
683bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000684 ValidateOnExit _1(V, *this), _2(W, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000685 if (TP.hasError())
686 return false;
687
688 bool Changed = false;
689 if (V.empty())
690 Changed |= EnforceAny(V);
691 if (W.empty())
692 Changed |= EnforceAny(W);
693
694 // An actual vector type cannot have 0 elements, so we can treat scalars
695 // as zero-length vectors. This way both vectors and scalars can be
696 // processed identically.
697 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
698 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
699 };
700
701 for (unsigned M : union_modes(V, W)) {
702 TypeSetByHwMode::SetType &VS = V.get(M);
703 TypeSetByHwMode::SetType &WS = W.get(M);
704
705 SmallSet<unsigned,2> VN, WN;
706 for (MVT T : VS)
707 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
708 for (MVT T : WS)
709 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
710
711 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
712 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
713 }
714 return Changed;
715}
716
717/// 1. Ensure that for each type T in A, there exists a type U in B,
718/// such that T and U have equal size in bits.
719/// 2. Ensure that for each type U in B, there exists a type T in A
720/// such that T and U have equal size in bits (reverse of 1).
721bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000722 ValidateOnExit _1(A, *this), _2(B, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000723 if (TP.hasError())
724 return false;
725 bool Changed = false;
726 if (A.empty())
727 Changed |= EnforceAny(A);
728 if (B.empty())
729 Changed |= EnforceAny(B);
730
731 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
732 return !Sizes.count(T.getSizeInBits());
733 };
734
735 for (unsigned M : union_modes(A, B)) {
736 TypeSetByHwMode::SetType &AS = A.get(M);
737 TypeSetByHwMode::SetType &BS = B.get(M);
738 SmallSet<unsigned,2> AN, BN;
739
740 for (MVT T : AS)
741 AN.insert(T.getSizeInBits());
742 for (MVT T : BS)
743 BN.insert(T.getSizeInBits());
744
745 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
746 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
747 }
748
749 return Changed;
750}
751
752void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000753 ValidateOnExit _1(VTS, *this);
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000754 const TypeSetByHwMode &Legal = getLegalTypes();
755 assert(Legal.isDefaultOnly() && "Default-mode only expected");
756 const TypeSetByHwMode::SetType &LegalTypes = Legal.get(DefaultMode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000757
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000758 for (auto &I : VTS)
759 expandOverloads(I.second, LegalTypes);
Scott Michel94420742008-03-05 17:49:05 +0000760}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000761
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000762void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
763 const TypeSetByHwMode::SetType &Legal) {
764 std::set<MVT> Ovs;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000765 for (MVT T : Out) {
766 if (!T.isOverloaded())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000767 continue;
Zachary Turner249dc142017-09-20 18:01:40 +0000768
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000769 Ovs.insert(T);
770 // MachineValueTypeSet allows iteration and erasing.
771 Out.erase(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000772 }
773
774 for (MVT Ov : Ovs) {
775 switch (Ov.SimpleTy) {
776 case MVT::iPTRAny:
777 Out.insert(MVT::iPTR);
778 return;
779 case MVT::iAny:
780 for (MVT T : MVT::integer_valuetypes())
781 if (Legal.count(T))
782 Out.insert(T);
Graham Hunter1a9195d2019-09-17 10:19:23 +0000783 for (MVT T : MVT::integer_fixedlen_vector_valuetypes())
784 if (Legal.count(T))
785 Out.insert(T);
786 for (MVT T : MVT::integer_scalable_vector_valuetypes())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000787 if (Legal.count(T))
788 Out.insert(T);
789 return;
790 case MVT::fAny:
791 for (MVT T : MVT::fp_valuetypes())
792 if (Legal.count(T))
793 Out.insert(T);
Graham Hunter1a9195d2019-09-17 10:19:23 +0000794 for (MVT T : MVT::fp_fixedlen_vector_valuetypes())
795 if (Legal.count(T))
796 Out.insert(T);
797 for (MVT T : MVT::fp_scalable_vector_valuetypes())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000798 if (Legal.count(T))
799 Out.insert(T);
800 return;
801 case MVT::vAny:
802 for (MVT T : MVT::vector_valuetypes())
803 if (Legal.count(T))
804 Out.insert(T);
805 return;
806 case MVT::Any:
807 for (MVT T : MVT::all_valuetypes())
808 if (Legal.count(T))
809 Out.insert(T);
810 return;
811 default:
812 break;
813 }
814 }
815}
816
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000817const TypeSetByHwMode &TypeInfer::getLegalTypes() {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000818 if (!LegalTypesCached) {
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000819 TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000820 // Stuff all types from all modes into the default mode.
821 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
822 for (const auto &I : LTS)
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000823 LegalTypes.insert(I.second);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000824 LegalTypesCached = true;
825 }
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000826 assert(LegalCache.isDefaultOnly() && "Default-mode only expected");
827 return LegalCache;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000828}
Chris Lattner514e2922011-04-17 21:38:24 +0000829
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000830#ifndef NDEBUG
831TypeInfer::ValidateOnExit::~ValidateOnExit() {
Ulrich Weigand22b1af82018-07-13 16:42:15 +0000832 if (Infer.Validate && !VTS.validate()) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000833 dbgs() << "Type set is empty for each HW mode:\n"
834 "possible type contradiction in the pattern below "
835 "(use -print-records with llvm-tblgen to see all "
836 "expanded records).\n";
837 Infer.TP.dump();
838 llvm_unreachable(nullptr);
839 }
840}
841#endif
842
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000843
844//===----------------------------------------------------------------------===//
845// ScopedName Implementation
846//===----------------------------------------------------------------------===//
847
848bool ScopedName::operator==(const ScopedName &o) const {
849 return Scope == o.Scope && Identifier == o.Identifier;
850}
851
852bool ScopedName::operator!=(const ScopedName &o) const {
853 return !(*this == o);
854}
855
856
Chris Lattner514e2922011-04-17 21:38:24 +0000857//===----------------------------------------------------------------------===//
858// TreePredicateFn Implementation
859//===----------------------------------------------------------------------===//
860
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000861/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
862TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000863 assert(
864 (!hasPredCode() || !hasImmCode()) &&
865 ".td file corrupt: can't have a node predicate *and* an imm predicate");
866}
867
868bool TreePredicateFn::hasPredCode() const {
Daniel Sanders87d196c2017-11-13 22:26:13 +0000869 return isLoad() || isStore() || isAtomic() ||
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000870 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000871}
872
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000873std::string TreePredicateFn::getPredCode() const {
874 std::string Code = "";
875
Daniel Sanders87d196c2017-11-13 22:26:13 +0000876 if (!isLoad() && !isStore() && !isAtomic()) {
877 Record *MemoryVT = getMemoryVT();
878
879 if (MemoryVT)
880 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
881 "MemoryVT requires IsLoad or IsStore");
882 }
883
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000884 if (!isLoad() && !isStore()) {
885 if (isUnindexed())
886 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
887 "IsUnindexed requires IsLoad or IsStore");
888
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000889 Record *ScalarMemoryVT = getScalarMemoryVT();
890
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000891 if (ScalarMemoryVT)
892 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
893 "ScalarMemoryVT requires IsLoad or IsStore");
894 }
895
Daniel Sanders87d196c2017-11-13 22:26:13 +0000896 if (isLoad() + isStore() + isAtomic() > 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000897 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
Daniel Sanders87d196c2017-11-13 22:26:13 +0000898 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000899
900 if (isLoad()) {
901 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
902 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
Matt Arsenault52c26242019-07-31 00:14:43 +0000903 getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
904 getMinAlignment() < 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000905 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
906 "IsLoad cannot be used by itself");
907 } else {
908 if (isNonExtLoad())
909 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
910 "IsNonExtLoad requires IsLoad");
911 if (isAnyExtLoad())
912 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
913 "IsAnyExtLoad requires IsLoad");
914 if (isSignExtLoad())
915 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
916 "IsSignExtLoad requires IsLoad");
917 if (isZeroExtLoad())
918 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
919 "IsZeroExtLoad requires IsLoad");
920 }
921
922 if (isStore()) {
923 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
Matt Arsenault52c26242019-07-31 00:14:43 +0000924 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&
925 getAddressSpaces() == nullptr && getMinAlignment() < 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000926 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
927 "IsStore cannot be used by itself");
928 } else {
929 if (isNonTruncStore())
930 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
931 "IsNonTruncStore requires IsStore");
932 if (isTruncStore())
933 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
934 "IsTruncStore requires IsStore");
935 }
936
Daniel Sanders87d196c2017-11-13 22:26:13 +0000937 if (isAtomic()) {
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000938 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
Matt Arsenaultebbd6e42019-09-09 16:02:07 +0000939 getAddressSpaces() == nullptr &&
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000940 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
941 !isAtomicOrderingAcquireRelease() &&
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000942 !isAtomicOrderingSequentiallyConsistent() &&
943 !isAtomicOrderingAcquireOrStronger() &&
944 !isAtomicOrderingReleaseOrStronger() &&
945 !isAtomicOrderingWeakerThanAcquire() &&
946 !isAtomicOrderingWeakerThanRelease())
Daniel Sanders87d196c2017-11-13 22:26:13 +0000947 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
948 "IsAtomic cannot be used by itself");
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000949 } else {
950 if (isAtomicOrderingMonotonic())
951 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
952 "IsAtomicOrderingMonotonic requires IsAtomic");
953 if (isAtomicOrderingAcquire())
954 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
955 "IsAtomicOrderingAcquire requires IsAtomic");
956 if (isAtomicOrderingRelease())
957 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
958 "IsAtomicOrderingRelease requires IsAtomic");
959 if (isAtomicOrderingAcquireRelease())
960 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
961 "IsAtomicOrderingAcquireRelease requires IsAtomic");
962 if (isAtomicOrderingSequentiallyConsistent())
963 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
964 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000965 if (isAtomicOrderingAcquireOrStronger())
966 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
967 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
968 if (isAtomicOrderingReleaseOrStronger())
969 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
970 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
971 if (isAtomicOrderingWeakerThanAcquire())
972 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
973 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
Daniel Sanders87d196c2017-11-13 22:26:13 +0000974 }
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000975
Daniel Sanders87d196c2017-11-13 22:26:13 +0000976 if (isLoad() || isStore() || isAtomic()) {
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000977 if (ListInit *AddressSpaces = getAddressSpaces()) {
978 Code += "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
979 " if (";
980
981 bool First = true;
982 for (Init *Val : AddressSpaces->getValues()) {
983 if (First)
984 First = false;
985 else
986 Code += " && ";
987
988 IntInit *IntVal = dyn_cast<IntInit>(Val);
989 if (!IntVal) {
990 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
991 "AddressSpaces element must be integer");
992 }
993
994 Code += "AddrSpace != " + utostr(IntVal->getValue());
995 }
996
997 Code += ")\nreturn false;\n";
998 }
Daniel Sanders87d196c2017-11-13 22:26:13 +0000999
Matt Arsenault52c26242019-07-31 00:14:43 +00001000 int64_t MinAlign = getMinAlignment();
1001 if (MinAlign > 0) {
1002 Code += "if (cast<MemSDNode>(N)->getAlignment() < ";
1003 Code += utostr(MinAlign);
1004 Code += ")\nreturn false;\n";
1005 }
1006
Daniel Sanders87d196c2017-11-13 22:26:13 +00001007 Record *MemoryVT = getMemoryVT();
1008
1009 if (MemoryVT)
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001010 Code += ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
Daniel Sanders87d196c2017-11-13 22:26:13 +00001011 MemoryVT->getName() + ") return false;\n")
1012 .str();
1013 }
1014
Daniel Sanders6d9d30a2017-11-13 23:03:47 +00001015 if (isAtomic() && isAtomicOrderingMonotonic())
1016 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1017 "AtomicOrdering::Monotonic) return false;\n";
1018 if (isAtomic() && isAtomicOrderingAcquire())
1019 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1020 "AtomicOrdering::Acquire) return false;\n";
1021 if (isAtomic() && isAtomicOrderingRelease())
1022 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1023 "AtomicOrdering::Release) return false;\n";
1024 if (isAtomic() && isAtomicOrderingAcquireRelease())
1025 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1026 "AtomicOrdering::AcquireRelease) return false;\n";
1027 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
1028 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1029 "AtomicOrdering::SequentiallyConsistent) return false;\n";
1030
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001031 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
1032 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1033 "return false;\n";
1034 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
1035 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1036 "return false;\n";
1037
1038 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
1039 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1040 "return false;\n";
1041 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
1042 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1043 "return false;\n";
1044
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001045 if (isLoad() || isStore()) {
1046 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
1047
1048 if (isUnindexed())
1049 Code += ("if (cast<" + SDNodeName +
1050 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1051 "return false;\n")
1052 .str();
1053
1054 if (isLoad()) {
1055 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1056 isZeroExtLoad()) > 1)
1057 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1058 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1059 "IsZeroExtLoad are mutually exclusive");
1060 if (isNonExtLoad())
1061 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1062 "ISD::NON_EXTLOAD) return false;\n";
1063 if (isAnyExtLoad())
1064 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1065 "return false;\n";
1066 if (isSignExtLoad())
1067 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1068 "return false;\n";
1069 if (isZeroExtLoad())
1070 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1071 "return false;\n";
1072 } else {
1073 if ((isNonTruncStore() + isTruncStore()) > 1)
1074 PrintFatalError(
1075 getOrigPatFragRecord()->getRecord()->getLoc(),
1076 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1077 if (isNonTruncStore())
1078 Code +=
1079 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1080 if (isTruncStore())
1081 Code +=
1082 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1083 }
1084
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001085 Record *ScalarMemoryVT = getScalarMemoryVT();
1086
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001087 if (ScalarMemoryVT)
1088 Code += ("if (cast<" + SDNodeName +
1089 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1090 ScalarMemoryVT->getName() + ") return false;\n")
1091 .str();
1092 }
1093
Benjamin Krameradcd0262020-01-28 20:23:46 +01001094 std::string PredicateCode =
1095 std::string(PatFragRec->getRecord()->getValueAsString("PredicateCode"));
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001096
1097 Code += PredicateCode;
1098
1099 if (PredicateCode.empty() && !Code.empty())
1100 Code += "return true;\n";
1101
1102 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +00001103}
1104
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001105bool TreePredicateFn::hasImmCode() const {
1106 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1107}
1108
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001109std::string TreePredicateFn::getImmCode() const {
Benjamin Krameradcd0262020-01-28 20:23:46 +01001110 return std::string(
1111 PatFragRec->getRecord()->getValueAsString("ImmediateCode"));
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001112}
1113
Daniel Sanders649c5852017-10-13 20:42:18 +00001114bool TreePredicateFn::immCodeUsesAPInt() const {
1115 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1116}
1117
1118bool TreePredicateFn::immCodeUsesAPFloat() const {
1119 bool Unset;
1120 // The return value will be false when IsAPFloat is unset.
1121 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1122 Unset);
1123}
1124
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001125bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1126 bool Value) const {
1127 bool Unset;
1128 bool Result =
1129 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1130 if (Unset)
1131 return false;
1132 return Result == Value;
1133}
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001134bool TreePredicateFn::usesOperands() const {
1135 return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1136}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001137bool TreePredicateFn::isLoad() const {
1138 return isPredefinedPredicateEqualTo("IsLoad", true);
1139}
1140bool TreePredicateFn::isStore() const {
1141 return isPredefinedPredicateEqualTo("IsStore", true);
1142}
Daniel Sanders87d196c2017-11-13 22:26:13 +00001143bool TreePredicateFn::isAtomic() const {
1144 return isPredefinedPredicateEqualTo("IsAtomic", true);
1145}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001146bool TreePredicateFn::isUnindexed() const {
1147 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1148}
1149bool TreePredicateFn::isNonExtLoad() const {
1150 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1151}
1152bool TreePredicateFn::isAnyExtLoad() const {
1153 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1154}
1155bool TreePredicateFn::isSignExtLoad() const {
1156 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1157}
1158bool TreePredicateFn::isZeroExtLoad() const {
1159 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1160}
1161bool TreePredicateFn::isNonTruncStore() const {
1162 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1163}
1164bool TreePredicateFn::isTruncStore() const {
1165 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1166}
Daniel Sanders6d9d30a2017-11-13 23:03:47 +00001167bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1168 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1169}
1170bool TreePredicateFn::isAtomicOrderingAcquire() const {
1171 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1172}
1173bool TreePredicateFn::isAtomicOrderingRelease() const {
1174 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1175}
1176bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1177 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1178}
1179bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1180 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1181 true);
1182}
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001183bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1184 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1185}
1186bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1187 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1188}
1189bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1190 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1191}
1192bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1193 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1194}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001195Record *TreePredicateFn::getMemoryVT() const {
1196 Record *R = getOrigPatFragRecord()->getRecord();
1197 if (R->isValueUnset("MemoryVT"))
1198 return nullptr;
1199 return R->getValueAsDef("MemoryVT");
1200}
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001201
1202ListInit *TreePredicateFn::getAddressSpaces() const {
1203 Record *R = getOrigPatFragRecord()->getRecord();
1204 if (R->isValueUnset("AddressSpaces"))
1205 return nullptr;
1206 return R->getValueAsListInit("AddressSpaces");
1207}
1208
Matt Arsenault52c26242019-07-31 00:14:43 +00001209int64_t TreePredicateFn::getMinAlignment() const {
1210 Record *R = getOrigPatFragRecord()->getRecord();
1211 if (R->isValueUnset("MinAlignment"))
1212 return 0;
1213 return R->getValueAsInt("MinAlignment");
1214}
1215
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001216Record *TreePredicateFn::getScalarMemoryVT() const {
1217 Record *R = getOrigPatFragRecord()->getRecord();
1218 if (R->isValueUnset("ScalarMemoryVT"))
1219 return nullptr;
1220 return R->getValueAsDef("ScalarMemoryVT");
1221}
Daniel Sanders8ead1292018-06-15 23:13:43 +00001222bool TreePredicateFn::hasGISelPredicateCode() const {
1223 return !PatFragRec->getRecord()
1224 ->getValueAsString("GISelPredicateCode")
1225 .empty();
1226}
1227std::string TreePredicateFn::getGISelPredicateCode() const {
Benjamin Krameradcd0262020-01-28 20:23:46 +01001228 return std::string(
1229 PatFragRec->getRecord()->getValueAsString("GISelPredicateCode"));
Daniel Sanders8ead1292018-06-15 23:13:43 +00001230}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001231
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001232StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001233 if (immCodeUsesAPInt())
1234 return "const APInt &";
1235 if (immCodeUsesAPFloat())
1236 return "const APFloat &";
1237 return "int64_t";
1238}
Chris Lattner514e2922011-04-17 21:38:24 +00001239
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001240StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001241 if (immCodeUsesAPInt())
1242 return "APInt";
1243 else if (immCodeUsesAPFloat())
1244 return "APFloat";
1245 return "I64";
1246}
1247
Chris Lattner514e2922011-04-17 21:38:24 +00001248/// isAlwaysTrue - Return true if this is a noop predicate.
1249bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001250 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001251}
1252
1253/// Return the name to use in the generated code to reference this, this is
1254/// "Predicate_foo" if from a pattern fragment "foo".
1255std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001256 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001257}
1258
1259/// getCodeToRunOnSDNode - Return the code for the function body that
1260/// evaluates this predicate. The argument is expected to be in "Node",
1261/// not N. This handles casting and conversion to a concrete node type as
1262/// appropriate.
1263std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001264 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001265 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001266 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001267 if (isLoad())
1268 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1269 "IsLoad cannot be used with ImmLeaf or its subclasses");
1270 if (isStore())
1271 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1272 "IsStore cannot be used with ImmLeaf or its subclasses");
1273 if (isUnindexed())
1274 PrintFatalError(
1275 getOrigPatFragRecord()->getRecord()->getLoc(),
1276 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1277 if (isNonExtLoad())
1278 PrintFatalError(
1279 getOrigPatFragRecord()->getRecord()->getLoc(),
1280 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1281 if (isAnyExtLoad())
1282 PrintFatalError(
1283 getOrigPatFragRecord()->getRecord()->getLoc(),
1284 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1285 if (isSignExtLoad())
1286 PrintFatalError(
1287 getOrigPatFragRecord()->getRecord()->getLoc(),
1288 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1289 if (isZeroExtLoad())
1290 PrintFatalError(
1291 getOrigPatFragRecord()->getRecord()->getLoc(),
1292 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1293 if (isNonTruncStore())
1294 PrintFatalError(
1295 getOrigPatFragRecord()->getRecord()->getLoc(),
1296 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1297 if (isTruncStore())
1298 PrintFatalError(
1299 getOrigPatFragRecord()->getRecord()->getLoc(),
1300 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1301 if (getMemoryVT())
1302 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1303 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1304 if (getScalarMemoryVT())
1305 PrintFatalError(
1306 getOrigPatFragRecord()->getRecord()->getLoc(),
1307 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1308
1309 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001310 if (immCodeUsesAPFloat())
1311 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1312 else if (immCodeUsesAPInt())
1313 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1314 else
1315 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001316 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001317 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001318
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001319 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001320 assert(hasPredCode() && "Don't have any predicate code!");
Matt Arsenault94d08fe2019-12-30 12:05:25 -05001321
1322 // If this is using PatFrags, there are multiple trees to search. They should
1323 // all have the same class. FIXME: Is there a way to find a common
1324 // superclass?
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001325 StringRef ClassName;
Matt Arsenault94d08fe2019-12-30 12:05:25 -05001326 for (const auto &Tree : PatFragRec->getTrees()) {
1327 StringRef TreeClassName;
1328 if (Tree->isLeaf())
1329 TreeClassName = "SDNode";
1330 else {
1331 Record *Op = Tree->getOperator();
1332 const SDNodeInfo &Info = PatFragRec->getDAGPatterns().getSDNodeInfo(Op);
1333 TreeClassName = Info.getSDClassName();
1334 }
1335
1336 if (ClassName.empty())
1337 ClassName = TreeClassName;
1338 else if (ClassName != TreeClassName) {
1339 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1340 "PatFrags trees do not have consistent class");
1341 }
Chris Lattner514e2922011-04-17 21:38:24 +00001342 }
Matt Arsenault94d08fe2019-12-30 12:05:25 -05001343
Chris Lattner514e2922011-04-17 21:38:24 +00001344 std::string Result;
1345 if (ClassName == "SDNode")
1346 Result = " SDNode *N = Node;\n";
1347 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001348 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001349
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001350 return (Twine(Result) + " (void)N;\n" + getPredCode()).str();
Scott Michel94420742008-03-05 17:49:05 +00001351}
1352
Chris Lattner8cab0212008-01-05 22:25:12 +00001353//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001354// PatternToMatch implementation
1355//
1356
Craig Topper1a872f22019-03-10 05:21:52 +00001357static bool isImmAllOnesAllZerosMatch(const TreePatternNode *P) {
1358 if (!P->isLeaf())
1359 return false;
1360 DefInit *DI = dyn_cast<DefInit>(P->getLeafValue());
1361 if (!DI)
1362 return false;
1363
1364 Record *R = DI->getDef();
1365 return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";
1366}
1367
Chris Lattner05925fe2010-03-29 01:40:38 +00001368/// getPatternSize - Return the 'size' of this pattern. We want to match large
1369/// patterns before small ones. This is used to determine the size of a
1370/// pattern.
Florian Hahn6b1db822018-06-14 20:32:58 +00001371static unsigned getPatternSize(const TreePatternNode *P,
Chris Lattner05925fe2010-03-29 01:40:38 +00001372 const CodeGenDAGPatterns &CGP) {
1373 unsigned Size = 3; // The node itself.
1374 // If the root node is a ConstantSDNode, increases its size.
1375 // e.g. (set R32:$dst, 0).
Florian Hahn6b1db822018-06-14 20:32:58 +00001376 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001377 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001378
Florian Hahn6b1db822018-06-14 20:32:58 +00001379 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001380 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001381 // We don't want to count any children twice, so return early.
1382 return Size;
1383 }
1384
Chris Lattner05925fe2010-03-29 01:40:38 +00001385 // If this node has some predicate function that must match, it adds to the
1386 // complexity of this node.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001387 if (!P->getPredicateCalls().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001388 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001389
Chris Lattner05925fe2010-03-29 01:40:38 +00001390 // Count children in the count if they are also nodes.
Florian Hahn6b1db822018-06-14 20:32:58 +00001391 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1392 const TreePatternNode *Child = P->getChild(i);
1393 if (!Child->isLeaf() && Child->getNumTypes()) {
Simon Pilgrimc3c14412018-08-15 20:41:19 +00001394 const TypeSetByHwMode &T0 = Child->getExtType(0);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001395 // At this point, all variable type sets should be simple, i.e. only
1396 // have a default mode.
1397 if (T0.getMachineValueType() != MVT::Other) {
1398 Size += getPatternSize(Child, CGP);
1399 continue;
1400 }
1401 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001402 if (Child->isLeaf()) {
1403 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001404 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Florian Hahn6b1db822018-06-14 20:32:58 +00001405 else if (Child->getComplexPatternInfo(CGP))
Chris Lattner05925fe2010-03-29 01:40:38 +00001406 Size += getPatternSize(Child, CGP);
Craig Topper1a872f22019-03-10 05:21:52 +00001407 else if (isImmAllOnesAllZerosMatch(Child))
1408 Size += 4; // Matches a build_vector(+3) and a predicate (+1).
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001409 else if (!Child->getPredicateCalls().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001410 ++Size;
1411 }
1412 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001413
Chris Lattner05925fe2010-03-29 01:40:38 +00001414 return Size;
1415}
1416
1417/// Compute the complexity metric for the input pattern. This roughly
1418/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001419int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001420getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001421 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
Chris Lattner05925fe2010-03-29 01:40:38 +00001422}
1423
Dan Gohman49e19e92008-08-22 00:20:26 +00001424/// getPredicateCheck - Return a single string containing all of this
1425/// pattern's predicates concatenated with "&&" operators.
1426///
1427std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001428 SmallVector<const Predicate*,4> PredList;
Matt Arsenault57ef94f2019-07-30 15:56:43 +00001429 for (const Predicate &P : Predicates) {
1430 if (!P.getCondString().empty())
1431 PredList.push_back(&P);
1432 }
Benjamin Kramerd5aecb92019-08-22 17:31:59 +00001433 llvm::sort(PredList, deref<std::less<>>());
Craig Topper8985efe2015-11-27 05:44:04 +00001434
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001435 std::string Check;
1436 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1437 if (i != 0)
1438 Check += " && ";
1439 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001440 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001441 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001442}
1443
1444//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001445// SDTypeConstraint implementation
1446//
1447
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001448SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001449 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001450
Chris Lattner8cab0212008-01-05 22:25:12 +00001451 if (R->isSubClassOf("SDTCisVT")) {
1452 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001453 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1454 for (const auto &P : VVT)
1455 if (P.second == MVT::isVoid)
1456 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001457 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1458 ConstraintType = SDTCisPtrTy;
1459 } else if (R->isSubClassOf("SDTCisInt")) {
1460 ConstraintType = SDTCisInt;
1461 } else if (R->isSubClassOf("SDTCisFP")) {
1462 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001463 } else if (R->isSubClassOf("SDTCisVec")) {
1464 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001465 } else if (R->isSubClassOf("SDTCisSameAs")) {
1466 ConstraintType = SDTCisSameAs;
1467 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1468 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1469 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001470 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001471 R->getValueAsInt("OtherOperandNum");
1472 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1473 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001474 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001475 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001476 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1477 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001478 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001479 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1480 ConstraintType = SDTCisSubVecOfVec;
1481 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1482 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001483 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1484 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001485 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1486 for (const auto &P : VVT) {
1487 MVT T = P.second;
1488 if (T.isVector())
1489 PrintFatalError(R->getLoc(),
1490 "Cannot use vector type as SDTCVecEltisVT");
1491 if (!T.isInteger() && !T.isFloatingPoint())
1492 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1493 "as SDTCVecEltisVT");
1494 }
Craig Topper0be34582015-03-05 07:11:34 +00001495 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1496 ConstraintType = SDTCisSameNumEltsAs;
1497 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1498 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001499 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1500 ConstraintType = SDTCisSameSizeAs;
1501 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1502 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001503 } else {
Daniel Sandersdff673b2019-02-12 17:36:57 +00001504 PrintFatalError(R->getLoc(),
1505 "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001506 }
1507}
1508
1509/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001510/// N, and the result number in ResNo.
Florian Hahn6b1db822018-06-14 20:32:58 +00001511static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
Chris Lattner2db7aba2010-03-19 21:56:21 +00001512 const SDNodeInfo &NodeInfo,
1513 unsigned &ResNo) {
1514 unsigned NumResults = NodeInfo.getNumResults();
1515 if (OpNo < NumResults) {
1516 ResNo = OpNo;
1517 return N;
1518 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001519
Chris Lattner2db7aba2010-03-19 21:56:21 +00001520 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001521
Florian Hahn6b1db822018-06-14 20:32:58 +00001522 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001523 std::string S;
1524 raw_string_ostream OS(S);
1525 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001526 << (OpNo+NumResults) << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001527 N->print(OS);
James Y Knighte452e272015-05-11 22:17:13 +00001528 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001529 }
1530
Florian Hahn6b1db822018-06-14 20:32:58 +00001531 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001532}
1533
1534/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1535/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001536/// change, false otherwise. If a type contradiction is found, flag an error.
Florian Hahn6b1db822018-06-14 20:32:58 +00001537bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
Chris Lattner8cab0212008-01-05 22:25:12 +00001538 const SDNodeInfo &NodeInfo,
1539 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001540 if (TP.hasError())
1541 return false;
1542
Chris Lattner2db7aba2010-03-19 21:56:21 +00001543 unsigned ResNo = 0; // The result number being referenced.
Florian Hahn6b1db822018-06-14 20:32:58 +00001544 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001545 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001546
Chris Lattner8cab0212008-01-05 22:25:12 +00001547 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001548 case SDTCisVT:
1549 // Operand must be a particular type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001550 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001551 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001552 // Operand must be same as target pointer type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001553 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001554 case SDTCisInt:
1555 // Require it to be one of the legal integer VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001556 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001557 case SDTCisFP:
1558 // Require it to be one of the legal fp VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001559 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001560 case SDTCisVec:
1561 // Require it to be one of the legal vector VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001562 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001563 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001564 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001565 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001566 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001567 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1568 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001569 }
1570 case SDTCisVTSmallerThanOp: {
1571 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1572 // have an integer type that is smaller than the VT.
Florian Hahn6b1db822018-06-14 20:32:58 +00001573 if (!NodeToApply->isLeaf() ||
1574 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1575 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001576 ->isSubClassOf("ValueType")) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001577 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001578 return false;
1579 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001580 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001581 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1582 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1583 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001584
Chris Lattner2db7aba2010-03-19 21:56:21 +00001585 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001586 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001587 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1588 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001589
Florian Hahn6b1db822018-06-14 20:32:58 +00001590 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001591 }
1592 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001593 unsigned BResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001594 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001595 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1596 BResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001597 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1598 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001599 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001600 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001601 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001602 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001603 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1604 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001605 // Filter vector types out of VecOperand that don't have the right element
1606 // type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001607 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1608 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001609 }
David Greene127fd1d2011-01-24 20:53:18 +00001610 case SDTCisSubVecOfVec: {
1611 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001612 TreePatternNode *BigVecOperand =
David Greene127fd1d2011-01-24 20:53:18 +00001613 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1614 VResNo);
1615
1616 // Filter vector types out of BigVecOperand that don't have the
1617 // right subvector type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001618 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1619 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001620 }
Craig Topper0be34582015-03-05 07:11:34 +00001621 case SDTCVecEltisVT: {
Florian Hahn6b1db822018-06-14 20:32:58 +00001622 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001623 }
1624 case SDTCisSameNumEltsAs: {
1625 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001626 TreePatternNode *OtherNode =
Craig Topper0be34582015-03-05 07:11:34 +00001627 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1628 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001629 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1630 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001631 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001632 case SDTCisSameSizeAs: {
1633 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001634 TreePatternNode *OtherNode =
Craig Topper9a44b3f2015-11-26 07:02:18 +00001635 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1636 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001637 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1638 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001639 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001640 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001641 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001642}
1643
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001644// Update the node type to match an instruction operand or result as specified
1645// in the ins or outs lists on the instruction definition. Return true if the
1646// type was actually changed.
1647bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1648 Record *Operand,
1649 TreePattern &TP) {
1650 // The 'unknown' operand indicates that types should be inferred from the
1651 // context.
1652 if (Operand->isSubClassOf("unknown_class"))
1653 return false;
1654
1655 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001656 if (Operand->isSubClassOf("Operand")) {
1657 Record *R = Operand->getValueAsDef("Type");
1658 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1659 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1660 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001661
1662 // PointerLikeRegClass has a type that is determined at runtime.
1663 if (Operand->isSubClassOf("PointerLikeRegClass"))
1664 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1665
1666 // Both RegisterClass and RegisterOperand operands derive their types from a
1667 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001668 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001669 if (Operand->isSubClassOf("RegisterClass"))
1670 RC = Operand;
1671 else if (Operand->isSubClassOf("RegisterOperand"))
1672 RC = Operand->getValueAsDef("RegClass");
1673
1674 assert(RC && "Unknown operand type");
1675 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1676 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1677}
1678
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001679bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1680 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1681 if (!TP.getInfer().isConcrete(Types[i], true))
1682 return true;
1683 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001684 if (getChild(i)->ContainsUnresolvedType(TP))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001685 return true;
1686 return false;
1687}
1688
1689bool TreePatternNode::hasProperTypeByHwMode() const {
1690 for (const TypeSetByHwMode &S : Types)
1691 if (!S.isDefaultOnly())
1692 return true;
Florian Hahn75e87c32018-05-30 21:00:18 +00001693 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001694 if (C->hasProperTypeByHwMode())
1695 return true;
1696 return false;
1697}
1698
1699bool TreePatternNode::hasPossibleType() const {
1700 for (const TypeSetByHwMode &S : Types)
1701 if (!S.isPossible())
1702 return false;
Florian Hahn75e87c32018-05-30 21:00:18 +00001703 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001704 if (!C->hasPossibleType())
1705 return false;
1706 return true;
1707}
1708
1709bool TreePatternNode::setDefaultMode(unsigned Mode) {
1710 for (TypeSetByHwMode &S : Types) {
1711 S.makeSimple(Mode);
1712 // Check if the selected mode had a type conflict.
1713 if (S.get(DefaultMode).empty())
1714 return false;
1715 }
Florian Hahn75e87c32018-05-30 21:00:18 +00001716 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001717 if (!C->setDefaultMode(Mode))
1718 return false;
1719 return true;
1720}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001721
Chris Lattner8cab0212008-01-05 22:25:12 +00001722//===----------------------------------------------------------------------===//
1723// SDNodeInfo implementation
1724//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001725SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001726 EnumName = R->getValueAsString("Opcode");
1727 SDClassName = R->getValueAsString("SDClass");
1728 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1729 NumResults = TypeProfile->getValueAsInt("NumResults");
1730 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001731
Chris Lattner8cab0212008-01-05 22:25:12 +00001732 // Parse the properties.
Matt Arsenault303327d2017-12-20 19:36:28 +00001733 Properties = parseSDPatternOperatorProperties(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001734
Chris Lattner8cab0212008-01-05 22:25:12 +00001735 // Parse the type constraints.
1736 std::vector<Record*> ConstraintList =
1737 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001738 for (Record *R : ConstraintList)
1739 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001740}
1741
Chris Lattner99e53b32010-02-28 00:22:30 +00001742/// getKnownType - If the type constraints on this node imply a fixed type
1743/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001744/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001745MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001746 unsigned NumResults = getNumResults();
1747 assert(NumResults <= 1 &&
1748 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001749 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001750
Craig Topper306cb122015-11-22 20:46:24 +00001751 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001752 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001753 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001754 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001755
Craig Topper306cb122015-11-22 20:46:24 +00001756 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001757 default: break;
1758 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001759 if (Constraint.VVT.isSimple())
1760 return Constraint.VVT.getSimple().SimpleTy;
1761 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001762 case SDTypeConstraint::SDTCisPtrTy:
1763 return MVT::iPTR;
1764 }
1765 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001766 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001767}
1768
Chris Lattner8cab0212008-01-05 22:25:12 +00001769//===----------------------------------------------------------------------===//
1770// TreePatternNode implementation
1771//
1772
Chris Lattnerf1447252010-03-19 21:37:09 +00001773static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1774 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001775 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001776 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001777
Chris Lattner2109cb42010-03-22 20:56:36 +00001778 if (Operator->isSubClassOf("Intrinsic"))
1779 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001780
Chris Lattnerf1447252010-03-19 21:37:09 +00001781 if (Operator->isSubClassOf("SDNode"))
1782 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001783
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001784 if (Operator->isSubClassOf("PatFrags")) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001785 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1786 // the forward reference case where one pattern fragment references another
1787 // before it is processed.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001788 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1789 // The number of results of a fragment with alternative records is the
1790 // maximum number of results across all alternatives.
1791 unsigned NumResults = 0;
1792 for (auto T : PFRec->getTrees())
1793 NumResults = std::max(NumResults, T->getNumTypes());
1794 return NumResults;
1795 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001796
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001797 ListInit *LI = Operator->getValueAsListInit("Fragments");
1798 assert(LI && "Invalid Fragment");
1799 unsigned NumResults = 0;
1800 for (Init *I : LI->getValues()) {
1801 Record *Op = nullptr;
1802 if (DagInit *Dag = dyn_cast<DagInit>(I))
1803 if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1804 Op = DI->getDef();
1805 assert(Op && "Invalid Fragment");
1806 NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1807 }
1808 return NumResults;
Chris Lattnerf1447252010-03-19 21:37:09 +00001809 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001810
Chris Lattnerf1447252010-03-19 21:37:09 +00001811 if (Operator->isSubClassOf("Instruction")) {
1812 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001813
Craig Topper3a8eb892015-03-20 05:09:06 +00001814 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1815
1816 // Subtract any defaulted outputs.
1817 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1818 Record *OperandNode = InstInfo.Operands[i].Rec;
1819
1820 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1821 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1822 --NumDefsToAdd;
1823 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001824
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001825 // Add on one implicit def if it has a resolvable type.
1826 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1827 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001828 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001829 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001830
Chris Lattnerf1447252010-03-19 21:37:09 +00001831 if (Operator->isSubClassOf("SDNodeXForm"))
1832 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001833
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001834 if (Operator->isSubClassOf("ValueType"))
1835 return 1; // A type-cast of one result.
1836
Tim Northoverc807a172014-05-20 11:52:46 +00001837 if (Operator->isSubClassOf("ComplexPattern"))
1838 return 1;
1839
Matthias Braun8c209aa2017-01-28 02:02:38 +00001840 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001841 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001842}
1843
1844void TreePatternNode::print(raw_ostream &OS) const {
1845 if (isLeaf())
1846 OS << *getLeafValue();
1847 else
1848 OS << '(' << getOperator()->getName();
1849
Zachary Turner249dc142017-09-20 18:01:40 +00001850 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1851 OS << ':';
1852 getExtType(i).writeToStream(OS);
1853 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001854
1855 if (!isLeaf()) {
1856 if (getNumChildren() != 0) {
1857 OS << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001858 getChild(0)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001859 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1860 OS << ", ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001861 getChild(i)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001862 }
1863 }
1864 OS << ")";
1865 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001866
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001867 for (const TreePredicateCall &Pred : PredicateCalls) {
1868 OS << "<<P:";
1869 if (Pred.Scope)
1870 OS << Pred.Scope << ":";
1871 OS << Pred.Fn.getFnName() << ">>";
1872 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001873 if (TransformFn)
1874 OS << "<<X:" << TransformFn->getName() << ">>";
1875 if (!getName().empty())
1876 OS << ":$" << getName();
1877
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001878 for (const ScopedName &Name : NamesAsPredicateArg)
1879 OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
Chris Lattner8cab0212008-01-05 22:25:12 +00001880}
1881void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001882 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001883}
1884
Scott Michel94420742008-03-05 17:49:05 +00001885/// isIsomorphicTo - Return true if this node is recursively
1886/// isomorphic to the specified node. For this comparison, the node's
1887/// entire state is considered. The assigned name is ignored, since
1888/// nodes with differing names are considered isomorphic. However, if
1889/// the assigned name is present in the dependent variable set, then
1890/// the assigned name is considered significant and the node is
1891/// isomorphic if the names match.
Florian Hahn6b1db822018-06-14 20:32:58 +00001892bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
Scott Michel94420742008-03-05 17:49:05 +00001893 const MultipleUseVarSet &DepVars) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001894 if (N == this) return true;
1895 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001896 getPredicateCalls() != N->getPredicateCalls() ||
Florian Hahn6b1db822018-06-14 20:32:58 +00001897 getTransformFn() != N->getTransformFn())
Chris Lattner8cab0212008-01-05 22:25:12 +00001898 return false;
1899
1900 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001901 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001902 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001903 return ((DI->getDef() == NDI->getDef())
1904 && (DepVars.find(getName()) == DepVars.end()
Florian Hahn6b1db822018-06-14 20:32:58 +00001905 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001906 }
1907 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001908 return getLeafValue() == N->getLeafValue();
Chris Lattner8cab0212008-01-05 22:25:12 +00001909 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001910
Florian Hahn6b1db822018-06-14 20:32:58 +00001911 if (N->getOperator() != getOperator() ||
1912 N->getNumChildren() != getNumChildren()) return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001913 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001914 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001915 return false;
1916 return true;
1917}
1918
1919/// clone - Make a copy of this tree and all of its children.
1920///
Florian Hahn75e87c32018-05-30 21:00:18 +00001921TreePatternNodePtr TreePatternNode::clone() const {
1922 TreePatternNodePtr New;
Chris Lattner8cab0212008-01-05 22:25:12 +00001923 if (isLeaf()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001924 New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001925 } else {
Florian Hahn75e87c32018-05-30 21:00:18 +00001926 std::vector<TreePatternNodePtr> CChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00001927 CChildren.reserve(Children.size());
1928 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001929 CChildren.push_back(getChild(i)->clone());
Craig Topper26fc06352018-07-15 06:52:49 +00001930 New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
Florian Hahn75e87c32018-05-30 21:00:18 +00001931 getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001932 }
1933 New->setName(getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001934 New->setNamesAsPredicateArg(getNamesAsPredicateArg());
Chris Lattnerf1447252010-03-19 21:37:09 +00001935 New->Types = Types;
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001936 New->setPredicateCalls(getPredicateCalls());
Chris Lattner8cab0212008-01-05 22:25:12 +00001937 New->setTransformFn(getTransformFn());
1938 return New;
1939}
1940
Chris Lattner53c39ba2010-02-14 22:22:58 +00001941/// RemoveAllTypes - Recursively strip all the types of this tree.
1942void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001943 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001944 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001945 if (isLeaf()) return;
1946 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001947 getChild(i)->RemoveAllTypes();
Chris Lattner53c39ba2010-02-14 22:22:58 +00001948}
1949
1950
Chris Lattner8cab0212008-01-05 22:25:12 +00001951/// SubstituteFormalArguments - Replace the formal arguments in this tree
1952/// with actual values specified by ArgMap.
Florian Hahn75e87c32018-05-30 21:00:18 +00001953void TreePatternNode::SubstituteFormalArguments(
1954 std::map<std::string, TreePatternNodePtr> &ArgMap) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001955 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001956
Chris Lattner8cab0212008-01-05 22:25:12 +00001957 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001958 TreePatternNode *Child = getChild(i);
1959 if (Child->isLeaf()) {
1960 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001961 // Note that, when substituting into an output pattern, Val might be an
1962 // UnsetInit.
1963 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1964 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001965 // We found a use of a formal argument, replace it with its value.
Florian Hahn6b1db822018-06-14 20:32:58 +00001966 TreePatternNodePtr NewChild = ArgMap[Child->getName()];
Dan Gohman6e979022008-10-15 06:17:21 +00001967 assert(NewChild && "Couldn't find formal argument!");
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001968 assert((Child->getPredicateCalls().empty() ||
1969 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Dan Gohman6e979022008-10-15 06:17:21 +00001970 "Non-empty child predicate clobbered!");
Florian Hahn0a2e0b62018-06-14 11:56:19 +00001971 setChild(i, std::move(NewChild));
Chris Lattner8cab0212008-01-05 22:25:12 +00001972 }
1973 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00001974 getChild(i)->SubstituteFormalArguments(ArgMap);
Chris Lattner8cab0212008-01-05 22:25:12 +00001975 }
1976 }
1977}
1978
1979
1980/// InlinePatternFragments - If this pattern refers to any pattern
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001981/// fragments, return the set of inlined versions (this can be more than
1982/// one if a PatFrags record has multiple alternatives).
1983void TreePatternNode::InlinePatternFragments(
1984 TreePatternNodePtr T, TreePattern &TP,
1985 std::vector<TreePatternNodePtr> &OutAlternatives) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001986
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001987 if (TP.hasError())
1988 return;
1989
1990 if (isLeaf()) {
1991 OutAlternatives.push_back(T); // nothing to do.
1992 return;
1993 }
1994
Chris Lattner8cab0212008-01-05 22:25:12 +00001995 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001996
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001997 if (!Op->isSubClassOf("PatFrags")) {
1998 if (getNumChildren() == 0) {
1999 OutAlternatives.push_back(T);
2000 return;
2001 }
2002
2003 // Recursively inline children nodes.
2004 std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
2005 ChildAlternatives.resize(getNumChildren());
Dan Gohman6e979022008-10-15 06:17:21 +00002006 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002007 TreePatternNodePtr Child = getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002008 Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
2009 // If there are no alternatives for any child, there are no
2010 // alternatives for this expression as whole.
2011 if (ChildAlternatives[i].empty())
2012 return;
Dan Gohman6e979022008-10-15 06:17:21 +00002013
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002014 for (auto NewChild : ChildAlternatives[i])
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002015 assert((Child->getPredicateCalls().empty() ||
2016 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002017 "Non-empty child predicate clobbered!");
Dan Gohman6e979022008-10-15 06:17:21 +00002018 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002019
2020 // The end result is an all-pairs construction of the resultant pattern.
2021 std::vector<unsigned> Idxs;
2022 Idxs.resize(ChildAlternatives.size());
2023 bool NotDone;
2024 do {
2025 // Create the variant and add it to the output list.
2026 std::vector<TreePatternNodePtr> NewChildren;
2027 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
2028 NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
2029 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00002030 getOperator(), std::move(NewChildren), getNumTypes());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002031
2032 // Copy over properties.
2033 R->setName(getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002034 R->setNamesAsPredicateArg(getNamesAsPredicateArg());
2035 R->setPredicateCalls(getPredicateCalls());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002036 R->setTransformFn(getTransformFn());
2037 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
2038 R->setType(i, getExtType(i));
Craig Topperbd199f82018-12-05 00:47:59 +00002039 for (unsigned i = 0, e = getNumResults(); i != e; ++i)
2040 R->setResultIndex(i, getResultIndex(i));
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002041
2042 // Register alternative.
2043 OutAlternatives.push_back(R);
2044
2045 // Increment indices to the next permutation by incrementing the
2046 // indices from last index backward, e.g., generate the sequence
2047 // [0, 0], [0, 1], [1, 0], [1, 1].
2048 int IdxsIdx;
2049 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2050 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
2051 Idxs[IdxsIdx] = 0;
2052 else
2053 break;
2054 }
2055 NotDone = (IdxsIdx >= 0);
2056 } while (NotDone);
2057
2058 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002059 }
2060
2061 // Otherwise, we found a reference to a fragment. First, look up its
2062 // TreePattern record.
2063 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002064
Chris Lattner8cab0212008-01-05 22:25:12 +00002065 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002066 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002067 TP.error("'" + Op->getName() + "' fragment requires " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002068 Twine(Frag->getNumArgs()) + " operands!");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002069 return;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002070 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002071
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002072 TreePredicateFn PredFn(Frag);
2073 unsigned Scope = 0;
2074 if (TreePredicateFn(Frag).usesOperands())
2075 Scope = TP.getDAGPatterns().allocateScope();
2076
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002077 // Compute the map of formal to actual arguments.
2078 std::map<std::string, TreePatternNodePtr> ArgMap;
2079 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002080 TreePatternNodePtr Child = getChildShared(i);
2081 if (Scope != 0) {
2082 Child = Child->clone();
2083 Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
2084 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002085 ArgMap[Frag->getArgName(i)] = Child;
Chris Lattner8cab0212008-01-05 22:25:12 +00002086 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002087
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002088 // Loop over all fragment alternatives.
2089 for (auto Alternative : Frag->getTrees()) {
2090 TreePatternNodePtr FragTree = Alternative->clone();
Dan Gohman6e979022008-10-15 06:17:21 +00002091
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002092 if (!PredFn.isAlwaysTrue())
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002093 FragTree->addPredicateCall(PredFn, Scope);
Dan Gohman6e979022008-10-15 06:17:21 +00002094
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002095 // Resolve formal arguments to their actual value.
2096 if (Frag->getNumArgs())
2097 FragTree->SubstituteFormalArguments(ArgMap);
2098
2099 // Transfer types. Note that the resolved alternative may have fewer
2100 // (but not more) results than the PatFrags node.
2101 FragTree->setName(getName());
2102 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2103 FragTree->UpdateNodeType(i, getExtType(i), TP);
2104
2105 // Transfer in the old predicates.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002106 for (const TreePredicateCall &Pred : getPredicateCalls())
2107 FragTree->addPredicateCall(Pred);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002108
2109 // The fragment we inlined could have recursive inlining that is needed. See
2110 // if there are any pattern fragments in it and inline them as needed.
2111 FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
2112 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002113}
2114
2115/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00002116/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00002117/// references from the register file information, for example.
2118///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002119/// When Unnamed is set, return the type of a DAG operand with no name, such as
2120/// the F8RC register class argument in:
2121///
2122/// (COPY_TO_REGCLASS GPR:$src, F8RC)
2123///
2124/// When Unnamed is false, return the type of a named DAG operand such as the
2125/// GPR:$src operand above.
2126///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002127static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2128 bool NotRegisters,
2129 bool Unnamed,
2130 TreePattern &TP) {
2131 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2132
Owen Andersona84be6c2011-06-27 21:06:21 +00002133 // Check to see if this is a register operand.
2134 if (R->isSubClassOf("RegisterOperand")) {
2135 assert(ResNo == 0 && "Regoperand ref only has one result!");
2136 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002137 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00002138 Record *RegClass = R->getValueAsDef("RegClass");
2139 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002140 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00002141 }
2142
Chris Lattnercabe0372010-03-15 06:00:16 +00002143 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00002144 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002145 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002146 // An unnamed register class represents itself as an i32 immediate, for
2147 // example on a COPY_TO_REGCLASS instruction.
2148 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002149 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002150
2151 // In a named operand, the register class provides the possible set of
2152 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002153 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002154 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00002155 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002156 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00002157 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002158
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002159 if (R->isSubClassOf("PatFrags")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002160 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002161 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002162 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00002163 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002164
Chris Lattner6070ee22010-03-23 23:50:31 +00002165 if (R->isSubClassOf("Register")) {
2166 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002167 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002168 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002169 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002170 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00002171 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002172
2173 if (R->isSubClassOf("SubRegIndex")) {
2174 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002175 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002176 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002177
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002178 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002179 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002180 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2181 //
2182 // (sext_inreg GPR:$src, i16)
2183 // ~~~
2184 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002185 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002186 // With a name, the ValueType simply provides the type of the named
2187 // variable.
2188 //
2189 // (sext_inreg i32:$src, i16)
2190 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002191 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002192 return TypeSetByHwMode(); // Unknown.
2193 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2194 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002195 }
2196
2197 if (R->isSubClassOf("CondCode")) {
2198 assert(ResNo == 0 && "This node only has one result!");
2199 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002200 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00002201 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002202
Chris Lattner6070ee22010-03-23 23:50:31 +00002203 if (R->isSubClassOf("ComplexPattern")) {
2204 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002205 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002206 return TypeSetByHwMode(); // Unknown.
2207 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00002208 }
2209 if (R->isSubClassOf("PointerLikeRegClass")) {
2210 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002211 TypeSetByHwMode VTS(MVT::iPTR);
2212 TP.getInfer().expandOverloads(VTS);
2213 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00002214 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002215
Chris Lattner6070ee22010-03-23 23:50:31 +00002216 if (R->getName() == "node" || R->getName() == "srcvalue" ||
Craig Topper1a872f22019-03-10 05:21:52 +00002217 R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
Sjoerd Meijerde234842019-05-30 07:30:37 +00002218 R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002219 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002220 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002221 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002222
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002223 if (R->isSubClassOf("Operand")) {
2224 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2225 Record *T = R->getValueAsDef("Type");
2226 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2227 }
Tim Northoverc807a172014-05-20 11:52:46 +00002228
Chris Lattner8cab0212008-01-05 22:25:12 +00002229 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002230 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00002231}
2232
Chris Lattner89c65662008-01-06 05:36:50 +00002233
2234/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2235/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2236const CodeGenIntrinsic *TreePatternNode::
2237getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2238 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2239 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2240 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00002241 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002242
Florian Hahn6b1db822018-06-14 20:32:58 +00002243 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00002244 return &CDP.getIntrinsicInfo(IID);
2245}
2246
Chris Lattner53c39ba2010-02-14 22:22:58 +00002247/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2248/// return the ComplexPattern information, otherwise return null.
2249const ComplexPattern *
2250TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00002251 Record *Rec;
2252 if (isLeaf()) {
2253 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2254 if (!DI)
2255 return nullptr;
2256 Rec = DI->getDef();
2257 } else
2258 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002259
Tim Northoverc807a172014-05-20 11:52:46 +00002260 if (!Rec->isSubClassOf("ComplexPattern"))
2261 return nullptr;
2262 return &CGP.getComplexPattern(Rec);
2263}
2264
2265unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2266 // A ComplexPattern specifically declares how many results it fills in.
2267 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2268 return CP->getNumOperands();
2269
2270 // If MIOperandInfo is specified, that gives the count.
2271 if (isLeaf()) {
2272 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2273 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2274 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2275 if (MIOps->getNumArgs())
2276 return MIOps->getNumArgs();
2277 }
2278 }
2279
2280 // Otherwise there is just one result.
2281 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00002282}
2283
2284/// NodeHasProperty - Return true if this node has the specified property.
2285bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002286 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002287 if (isLeaf()) {
2288 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2289 return CP->hasProperty(Property);
Matt Arsenault303327d2017-12-20 19:36:28 +00002290
Chris Lattner53c39ba2010-02-14 22:22:58 +00002291 return false;
2292 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002293
Matt Arsenault303327d2017-12-20 19:36:28 +00002294 if (Property != SDNPHasChain) {
2295 // The chain proprety is already present on the different intrinsic node
2296 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2297 // on the intrinsic. Anything else is specific to the individual intrinsic.
2298 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2299 return Int->hasProperty(Property);
2300 }
2301
2302 if (!Operator->isSubClassOf("SDPatternOperator"))
2303 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002304
Chris Lattner53c39ba2010-02-14 22:22:58 +00002305 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2306}
2307
2308
2309
2310
2311/// TreeHasProperty - Return true if any node in this tree has the specified
2312/// property.
2313bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002314 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002315 if (NodeHasProperty(Property, CGP))
2316 return true;
2317 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002318 if (getChild(i)->TreeHasProperty(Property, CGP))
Chris Lattner53c39ba2010-02-14 22:22:58 +00002319 return true;
2320 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002321}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002322
Evan Cheng49bad4c2008-06-16 20:29:38 +00002323/// isCommutativeIntrinsic - Return true if the node corresponds to a
2324/// commutative intrinsic.
2325bool
2326TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2327 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2328 return Int->isCommutative;
2329 return false;
2330}
2331
Florian Hahn6b1db822018-06-14 20:32:58 +00002332static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2333 if (!N->isLeaf())
2334 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002335
Florian Hahn6b1db822018-06-14 20:32:58 +00002336 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
Matt Arsenaulteb492162014-11-02 23:46:51 +00002337 if (DI && DI->getDef()->isSubClassOf(Class))
2338 return true;
2339
2340 return false;
2341}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002342
2343static void emitTooManyOperandsError(TreePattern &TP,
2344 StringRef InstName,
2345 unsigned Expected,
2346 unsigned Actual) {
2347 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2348 " operands but expected only " + Twine(Expected) + "!");
2349}
2350
2351static void emitTooFewOperandsError(TreePattern &TP,
2352 StringRef InstName,
2353 unsigned Actual) {
2354 TP.error("Instruction '" + InstName +
2355 "' expects more than the provided " + Twine(Actual) + " operands!");
2356}
2357
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002358/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002359/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002360/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002361bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002362 if (TP.hasError())
2363 return false;
2364
Chris Lattnerab3242f2008-01-06 01:10:31 +00002365 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002366 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002367 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002368 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002369 bool MadeChange = false;
2370 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2371 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002372 NotRegisters,
2373 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002374 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002375 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002376
Sean Silvafb509ed2012-10-10 20:24:43 +00002377 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002378 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002379
Chris Lattnerf1447252010-03-19 21:37:09 +00002380 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002381 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002382
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002383 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002384 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002385
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002386 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2387 for (auto &P : VVT) {
2388 MVT::SimpleValueType VT = P.second.SimpleTy;
2389 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2390 continue;
2391 unsigned Size = MVT(VT).getSizeInBits();
2392 // Make sure that the value is representable for this type.
2393 if (Size >= 32)
2394 continue;
2395 // Check that the value doesn't use more bits than we have. It must
2396 // either be a sign- or zero-extended equivalent of the original.
2397 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2398 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2399 SignBitAndAbove == 1)
2400 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002401
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002402 TP.error("Integer value '" + Twine(II->getValue()) +
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002403 "' is out of range for type '" + getEnumName(VT) + "'!");
2404 break;
2405 }
2406 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002407 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002408
Chris Lattner8cab0212008-01-05 22:25:12 +00002409 return false;
2410 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002411
Chris Lattneree820ac2010-02-23 05:51:07 +00002412 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002413 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002414
Chris Lattner8cab0212008-01-05 22:25:12 +00002415 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002416 unsigned NumRetVTs = Int->IS.RetVTs.size();
2417 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002418
Bill Wendling91821472008-11-13 09:08:33 +00002419 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002420 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002421
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002422 if (getNumChildren() != NumParamVTs + 1) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002423 TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2424 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002425 return false;
2426 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002427
2428 // Apply type info to the intrinsic ID.
Florian Hahn6b1db822018-06-14 20:32:58 +00002429 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002430
Chris Lattnerf1447252010-03-19 21:37:09 +00002431 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002432 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002433
Chris Lattnerf1447252010-03-19 21:37:09 +00002434 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
Florian Hahn6b1db822018-06-14 20:32:58 +00002435 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2436 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002437 }
2438 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002439 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002440
Chris Lattneree820ac2010-02-23 05:51:07 +00002441 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002442 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002443
Chris Lattner135091b2010-03-28 08:48:47 +00002444 // Check that the number of operands is sane. Negative operands -> varargs.
2445 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002446 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002447 TP.error(getOperator()->getName() + " node requires exactly " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002448 Twine(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002449 return false;
2450 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002451
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002452 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002453 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002454 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2455 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002456 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002457 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002458
Chris Lattneree820ac2010-02-23 05:51:07 +00002459 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002460 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002461 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002462 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002463
Chris Lattnerd44966f2010-03-27 19:15:02 +00002464 bool MadeChange = false;
2465
2466 // Apply the result types to the node, these come from the things in the
2467 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002468 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2469 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002470 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2471 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002472
Chris Lattnerd44966f2010-03-27 19:15:02 +00002473 // If the instruction has implicit defs, we apply the first one as a result.
2474 // FIXME: This sucks, it should apply all implicit defs.
2475 if (!InstInfo.ImplicitDefs.empty()) {
2476 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002477
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002478 // FIXME: Generalize to multiple possible types and multiple possible
2479 // ImplicitDefs.
2480 MVT::SimpleValueType VT =
2481 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002482
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002483 if (VT != MVT::Other)
2484 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002485 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002486
Chris Lattnercabe0372010-03-15 06:00:16 +00002487 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2488 // be the same.
2489 if (getOperator()->getName() == "INSERT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00002490 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2491 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2492 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002493 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2494 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2495 // variadic.
2496
2497 unsigned NChild = getNumChildren();
2498 if (NChild < 3) {
2499 TP.error("REG_SEQUENCE requires at least 3 operands!");
2500 return false;
2501 }
2502
2503 if (NChild % 2 == 0) {
2504 TP.error("REG_SEQUENCE requires an odd number of operands!");
2505 return false;
2506 }
2507
2508 if (!isOperandClass(getChild(0), "RegisterClass")) {
2509 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2510 return false;
2511 }
2512
2513 for (unsigned I = 1; I < NChild; I += 2) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002514 TreePatternNode *SubIdxChild = getChild(I + 1);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002515 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2516 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002517 Twine(I + 1) + "!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00002518 return false;
2519 }
2520 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002521 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002522
Simon Tathamc74322a2019-07-04 08:43:20 +00002523 // If one or more operands with a default value appear at the end of the
2524 // formal operand list for an instruction, we allow them to be overridden
2525 // by optional operands provided in the pattern.
2526 //
2527 // But if an operand B without a default appears at any point after an
2528 // operand A with a default, then we don't allow A to be overridden,
2529 // because there would be no way to specify whether the next operand in
2530 // the pattern was intended to override A or skip it.
2531 unsigned NonOverridableOperands = Inst.getNumOperands();
2532 while (NonOverridableOperands > 0 &&
2533 CDP.operandHasDefault(Inst.getOperand(NonOverridableOperands-1)))
2534 --NonOverridableOperands;
2535
Chris Lattner8cab0212008-01-05 22:25:12 +00002536 unsigned ChildNo = 0;
2537 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2538 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002539
Simon Tathamc74322a2019-07-04 08:43:20 +00002540 // If the operand has a default value, do we use it? We must use the
2541 // default if we've run out of children of the pattern DAG to consume,
2542 // or if the operand is followed by a non-defaulted one.
2543 if (CDP.operandHasDefault(OperandNode) &&
2544 (i < NonOverridableOperands || ChildNo >= getNumChildren()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002545 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002546
Simon Tathamc74322a2019-07-04 08:43:20 +00002547 // If we have run out of child nodes and there _isn't_ a default
2548 // value we can use for the next operand, give an error.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002549 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002550 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002551 return false;
2552 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002553
Florian Hahn6b1db822018-06-14 20:32:58 +00002554 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002555 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002556
2557 // If the operand has sub-operands, they may be provided by distinct
2558 // child patterns, so attempt to match each sub-operand separately.
2559 if (OperandNode->isSubClassOf("Operand")) {
2560 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2561 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2562 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002563 // a single ComplexPattern-related Operand.
2564
2565 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002566 // Match first sub-operand against the child we already have.
2567 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2568 MadeChange |=
2569 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2570
2571 // And the remaining sub-operands against subsequent children.
2572 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2573 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002574 emitTooFewOperandsError(TP, getOperator()->getName(),
2575 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002576 return false;
2577 }
Florian Hahn6b1db822018-06-14 20:32:58 +00002578 Child = getChild(ChildNo++);
Ulrich Weigande618abd2013-03-19 19:51:09 +00002579
2580 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2581 MadeChange |=
2582 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2583 }
2584 continue;
2585 }
2586 }
2587 }
2588
2589 // If we didn't match by pieces above, attempt to match the whole
2590 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002591 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002592 }
Christopher Lamba7312392008-03-11 09:33:47 +00002593
Matt Arsenaulteb492162014-11-02 23:46:51 +00002594 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002595 emitTooManyOperandsError(TP, getOperator()->getName(),
2596 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002597 return false;
2598 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002599
Ulrich Weigande618abd2013-03-19 19:51:09 +00002600 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002601 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002602 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002603 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002604
Tim Northoverc807a172014-05-20 11:52:46 +00002605 if (getOperator()->isSubClassOf("ComplexPattern")) {
2606 bool MadeChange = false;
2607
2608 for (unsigned i = 0; i < getNumChildren(); ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002609 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Tim Northoverc807a172014-05-20 11:52:46 +00002610
2611 return MadeChange;
2612 }
2613
Chris Lattneree820ac2010-02-23 05:51:07 +00002614 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002615
Chris Lattneree820ac2010-02-23 05:51:07 +00002616 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002617 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002618 TP.error("Node transform '" + getOperator()->getName() +
2619 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002620 return false;
2621 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002622
Florian Hahn6b1db822018-06-14 20:32:58 +00002623 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002624 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002625}
2626
2627/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2628/// RHS of a commutative operation, not the on LHS.
Florian Hahn6b1db822018-06-14 20:32:58 +00002629static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2630 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
Chris Lattner8cab0212008-01-05 22:25:12 +00002631 return true;
Florian Hahn6b1db822018-06-14 20:32:58 +00002632 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002633 return true;
2634 return false;
2635}
2636
2637
2638/// canPatternMatch - If it is impossible for this pattern to match on this
2639/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002640/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002641/// that can never possibly work), and to prevent the pattern permuter from
2642/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002643bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002644 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002645 if (isLeaf()) return true;
2646
2647 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002648 if (!getChild(i)->canPatternMatch(Reason, CDP))
Chris Lattner8cab0212008-01-05 22:25:12 +00002649 return false;
2650
2651 // If this is an intrinsic, handle cases that would make it not match. For
2652 // example, if an operand is required to be an immediate.
2653 if (getOperator()->isSubClassOf("Intrinsic")) {
2654 // TODO:
2655 return true;
2656 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002657
Tim Northoverc807a172014-05-20 11:52:46 +00002658 if (getOperator()->isSubClassOf("ComplexPattern"))
2659 return true;
2660
Chris Lattner8cab0212008-01-05 22:25:12 +00002661 // If this node is a commutative operator, check that the LHS isn't an
2662 // immediate.
2663 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002664 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2665 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002666 // Scan all of the operands of the node and make sure that only the last one
2667 // is a constant node, unless the RHS also is.
2668 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002669 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002670 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002671 if (OnlyOnRHSOfCommutative(getChild(i))) {
2672 Reason="Immediate value must be on the RHS of commutative operators!";
2673 return false;
2674 }
2675 }
2676 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002677
Chris Lattner8cab0212008-01-05 22:25:12 +00002678 return true;
2679}
2680
2681//===----------------------------------------------------------------------===//
2682// TreePattern implementation
2683//
2684
David Greeneaf8ee2c2011-07-29 22:43:06 +00002685TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002686 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002687 isInputPattern(isInput), HasError(false),
2688 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002689 for (Init *I : RawPat->getValues())
2690 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002691}
2692
David Greeneaf8ee2c2011-07-29 22:43:06 +00002693TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002694 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002695 isInputPattern(isInput), HasError(false),
2696 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002697 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002698}
2699
Florian Hahn75e87c32018-05-30 21:00:18 +00002700TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2701 CodeGenDAGPatterns &cdp)
2702 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2703 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002704 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002705}
2706
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002707void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002708 if (HasError)
2709 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002710 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002711 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2712 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002713}
2714
Chris Lattnercabe0372010-03-15 06:00:16 +00002715void TreePattern::ComputeNamedNodes() {
Florian Hahn6b1db822018-06-14 20:32:58 +00002716 for (TreePatternNodePtr &Tree : Trees)
2717 ComputeNamedNodes(Tree.get());
Chris Lattnercabe0372010-03-15 06:00:16 +00002718}
2719
Florian Hahn6b1db822018-06-14 20:32:58 +00002720void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002721 if (!N->getName().empty())
Florian Hahn6b1db822018-06-14 20:32:58 +00002722 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002723
Chris Lattnercabe0372010-03-15 06:00:16 +00002724 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002725 ComputeNamedNodes(N->getChild(i));
Chris Lattnercabe0372010-03-15 06:00:16 +00002726}
2727
Florian Hahn75e87c32018-05-30 21:00:18 +00002728TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2729 StringRef OpName) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002730 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002731 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002732
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002733 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002734 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002735 /// (foo GPR, imm) -> (foo GPR, (imm))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002736 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
David Greenee32ebf22011-07-29 19:07:07 +00002737 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002738 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002739 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002740 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002741
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002742 // Input argument?
Florian Hahn75e87c32018-05-30 21:00:18 +00002743 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002744 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002745 if (OpName.empty())
2746 error("'node' argument requires a name to match with operand list");
Benjamin Krameradcd0262020-01-28 20:23:46 +01002747 Args.push_back(std::string(OpName));
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002748 }
2749
2750 Res->setName(OpName);
2751 return Res;
2752 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002753
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002754 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002755 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002756 if (OpName.empty())
2757 error("'?' argument requires a name to match with operand list");
Florian Hahn75e87c32018-05-30 21:00:18 +00002758 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
Benjamin Krameradcd0262020-01-28 20:23:46 +01002759 Args.push_back(std::string(OpName));
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002760 Res->setName(OpName);
2761 return Res;
2762 }
2763
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002764 if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002765 if (!OpName.empty())
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002766 error("Constant int or bit argument should not have a name!");
2767 if (isa<BitInit>(TheInit))
2768 TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2769 return std::make_shared<TreePatternNode>(TheInit, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002770 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002771
Sean Silvafb509ed2012-10-10 20:24:43 +00002772 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002773 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002774 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002775 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002776 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002777 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002778 }
2779
Sean Silvafb509ed2012-10-10 20:24:43 +00002780 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002781 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002782 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002783 error("Pattern has unexpected init kind!");
2784 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002785 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002786 if (!OpDef) error("Pattern has unexpected operator type!");
2787 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002788
Chris Lattner8cab0212008-01-05 22:25:12 +00002789 if (Operator->isSubClassOf("ValueType")) {
2790 // If the operator is a ValueType, then this must be "type cast" of a leaf
2791 // node.
2792 if (Dag->getNumArgs() != 1)
2793 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002794
Florian Hahn75e87c32018-05-30 21:00:18 +00002795 TreePatternNodePtr New =
2796 ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002797
Chris Lattner8cab0212008-01-05 22:25:12 +00002798 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002799 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002800 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2801 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002802
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002803 if (!OpName.empty())
2804 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002805 return New;
2806 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002807
Chris Lattner8cab0212008-01-05 22:25:12 +00002808 // Verify that this is something that makes sense for an operator.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002809 if (!Operator->isSubClassOf("PatFrags") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002810 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002811 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002812 !Operator->isSubClassOf("SDNodeXForm") &&
2813 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002814 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002815 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002816 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002817 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002818
Chris Lattner8cab0212008-01-05 22:25:12 +00002819 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002820 if (isInputPattern) {
2821 if (Operator->isSubClassOf("Instruction") ||
2822 Operator->isSubClassOf("SDNodeXForm"))
2823 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2824 } else {
2825 if (Operator->isSubClassOf("Intrinsic"))
2826 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002827
Chris Lattner2e9eae12010-03-28 06:57:56 +00002828 if (Operator->isSubClassOf("SDNode") &&
2829 Operator->getName() != "imm" &&
Craig Topper80fda372019-09-22 19:49:39 +00002830 Operator->getName() != "timm" &&
Chris Lattner2e9eae12010-03-28 06:57:56 +00002831 Operator->getName() != "fpimm" &&
2832 Operator->getName() != "tglobaltlsaddr" &&
2833 Operator->getName() != "tconstpool" &&
2834 Operator->getName() != "tjumptable" &&
2835 Operator->getName() != "tframeindex" &&
2836 Operator->getName() != "texternalsym" &&
2837 Operator->getName() != "tblockaddress" &&
2838 Operator->getName() != "tglobaladdr" &&
2839 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002840 Operator->getName() != "vt" &&
2841 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002842 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2843 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002844
Florian Hahn75e87c32018-05-30 21:00:18 +00002845 std::vector<TreePatternNodePtr> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002846
2847 // Parse all the operands.
2848 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002849 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002850
Hal Finkel8b4bdfdb2018-01-03 11:35:09 +00002851 // Get the actual number of results before Operator is converted to an intrinsic
2852 // node (which is hard-coded to have either zero or one result).
2853 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2854
Fangrui Song956ee792018-03-30 22:22:31 +00002855 // If the operator is an intrinsic, then this is just syntactic sugar for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002856 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002857 // convert the intrinsic name to a number.
2858 if (Operator->isSubClassOf("Intrinsic")) {
2859 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2860 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2861
2862 // If this intrinsic returns void, it must have side-effects and thus a
2863 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002864 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002865 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Momchil Velikov52c39392019-07-17 10:53:13 +00002866 else if (Int.ModRef != CodeGenIntrinsic::NoMem || Int.hasSideEffects)
Chris Lattner8cab0212008-01-05 22:25:12 +00002867 // Has side-effects, requires chain.
2868 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002869 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002870 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002871
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002872 Children.insert(Children.begin(),
2873 std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
Chris Lattner8cab0212008-01-05 22:25:12 +00002874 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002875
Tim Northoverc807a172014-05-20 11:52:46 +00002876 if (Operator->isSubClassOf("ComplexPattern")) {
2877 for (unsigned i = 0; i < Children.size(); ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002878 TreePatternNodePtr Child = Children[i];
Tim Northoverc807a172014-05-20 11:52:46 +00002879
2880 if (Child->getName().empty())
2881 error("All arguments to a ComplexPattern must be named");
2882
2883 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2884 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2885 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2886 auto OperandId = std::make_pair(Operator, i);
2887 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2888 if (PrevOp != ComplexPatternOperands.end()) {
2889 if (PrevOp->getValue() != OperandId)
2890 error("All ComplexPattern operands must appear consistently: "
2891 "in the same order in just one ComplexPattern instance.");
2892 } else
2893 ComplexPatternOperands[Child->getName()] = OperandId;
2894 }
2895 }
2896
Florian Hahn6b1db822018-06-14 20:32:58 +00002897 TreePatternNodePtr Result =
Craig Topper26fc06352018-07-15 06:52:49 +00002898 std::make_shared<TreePatternNode>(Operator, std::move(Children),
2899 NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002900 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002901
Matthias Braun7cf3b112016-12-05 06:00:41 +00002902 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002903 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002904 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002905 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002906 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002907}
2908
Chris Lattnera787c9e2010-03-28 08:38:32 +00002909/// SimplifyTree - See if we can simplify this tree to eliminate something that
2910/// will never match in favor of something obvious that will. This is here
2911/// strictly as a convenience to target authors because it allows them to write
2912/// more type generic things and have useless type casts fold away.
2913///
2914/// This returns true if any change is made.
Florian Hahn75e87c32018-05-30 21:00:18 +00002915static bool SimplifyTree(TreePatternNodePtr &N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002916 if (N->isLeaf())
2917 return false;
2918
2919 // If we have a bitconvert with a resolved type and if the source and
2920 // destination types are the same, then the bitconvert is useless, remove it.
2921 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002922 N->getExtType(0).isValueTypeByHwMode(false) &&
Florian Hahn6b1db822018-06-14 20:32:58 +00002923 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002924 N->getName().empty()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002925 N = N->getChildShared(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002926 SimplifyTree(N);
2927 return true;
2928 }
2929
2930 // Walk all children.
2931 bool MadeChange = false;
2932 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002933 TreePatternNodePtr Child = N->getChildShared(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002934 MadeChange |= SimplifyTree(Child);
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002935 N->setChild(i, std::move(Child));
Chris Lattnera787c9e2010-03-28 08:38:32 +00002936 }
2937 return MadeChange;
2938}
2939
2940
2941
Chris Lattner8cab0212008-01-05 22:25:12 +00002942/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002943/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002944/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002945bool TreePattern::
2946InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2947 if (NamedNodes.empty())
2948 ComputeNamedNodes();
2949
Chris Lattner8cab0212008-01-05 22:25:12 +00002950 bool MadeChange = true;
2951 while (MadeChange) {
2952 MadeChange = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002953 for (TreePatternNodePtr &Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002954 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2955 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002956 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002957
2958 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002959 for (auto &Entry : NamedNodes) {
2960 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002961
Chris Lattnercabe0372010-03-15 06:00:16 +00002962 // If we have input named node types, propagate their types to the named
2963 // values here.
2964 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002965 if (!InNamedTypes->count(Entry.getKey())) {
2966 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002967 "' in output pattern but not input pattern");
2968 return true;
2969 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002970
2971 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002972 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002973
2974 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002975 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002976 // If this node is a register class, and it is the root of the pattern
2977 // then we're mapping something onto an input register. We allow
2978 // changing the type of the input register in this case. This allows
2979 // us to match things like:
2980 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Florian Hahn75e87c32018-05-30 21:00:18 +00002981 if (Node == Trees[0].get() && Node->isLeaf()) {
Craig Topper306cb122015-11-22 20:46:24 +00002982 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002983 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2984 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002985 continue;
2986 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002987
Craig Topper306cb122015-11-22 20:46:24 +00002988 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002989 InNodes[0]->getNumTypes() == 1 &&
2990 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002991 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2992 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002993 }
2994 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002995
Chris Lattnercabe0372010-03-15 06:00:16 +00002996 // If there are multiple nodes with the same name, they must all have the
2997 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002998 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002999 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003000 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00003001 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00003002 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003003
Chris Lattnerf1447252010-03-19 21:37:09 +00003004 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
3005 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00003006 }
3007 }
3008 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003009 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003010
Chris Lattner8cab0212008-01-05 22:25:12 +00003011 bool HasUnresolvedTypes = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00003012 for (const TreePatternNodePtr &Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003013 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003014 return !HasUnresolvedTypes;
3015}
3016
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00003017void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00003018 OS << getRecord()->getName();
3019 if (!Args.empty()) {
3020 OS << "(" << Args[0];
3021 for (unsigned i = 1, e = Args.size(); i != e; ++i)
3022 OS << ", " << Args[i];
3023 OS << ")";
3024 }
3025 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00003026
Chris Lattner8cab0212008-01-05 22:25:12 +00003027 if (Trees.size() > 1)
3028 OS << "[\n";
Florian Hahn75e87c32018-05-30 21:00:18 +00003029 for (const TreePatternNodePtr &Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003030 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00003031 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00003032 OS << "\n";
3033 }
3034
3035 if (Trees.size() > 1)
3036 OS << "]\n";
3037}
3038
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00003039void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00003040
3041//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00003042// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00003043//
3044
Daniel Sanders7e523672017-11-11 03:23:44 +00003045CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
3046 PatternRewriterFn PatternRewriter)
3047 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
3048 PatternRewriter(PatternRewriter) {
Chris Lattner77d369c2010-12-13 00:23:57 +00003049
Reid Kleckner72c68f12019-12-11 07:37:16 -08003050 Intrinsics = CodeGenIntrinsicTable(Records);
Chris Lattner8cab0212008-01-05 22:25:12 +00003051 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00003052 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00003053 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00003054 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003055 ParseDefaultOperands();
3056 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00003057 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00003058 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003059
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003060 // Break patterns with parameterized types into a series of patterns,
3061 // where each one has a fixed type and is predicated on the conditions
3062 // of the associated HW mode.
3063 ExpandHwModeBasedTypes();
3064
Chris Lattner8cab0212008-01-05 22:25:12 +00003065 // Generate variants. For example, commutative patterns can match
3066 // multiple ways. Add them to PatternsToMatch as well.
3067 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003068
3069 // Infer instruction flags. For example, we can detect loads,
3070 // stores, and side effects in many cases by examining an
3071 // instruction's pattern.
3072 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003073
3074 // Verify that instruction flags match the patterns.
3075 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00003076}
3077
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00003078Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00003079 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00003080 if (!N || !N->isSubClassOf("SDNode"))
3081 PrintFatalError("Error getting SDNode '" + Name + "'!");
3082
Chris Lattner8cab0212008-01-05 22:25:12 +00003083 return N;
3084}
3085
3086// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003087void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003088 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003089 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3090
Chris Lattner8cab0212008-01-05 22:25:12 +00003091 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003092 Record *R = Nodes.back();
3093 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00003094 Nodes.pop_back();
3095 }
3096
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003097 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00003098 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
3099 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
3100 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
3101}
3102
3103/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3104/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003105void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003106 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
3107 while (!Xforms.empty()) {
3108 Record *XFormNode = Xforms.back();
3109 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00003110 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Benjamin Kramer0d401fa2020-01-29 00:42:56 +01003111 SDNodeXForms.insert(
3112 std::make_pair(XFormNode, NodeXForm(SDNode, std::string(Code))));
Chris Lattner8cab0212008-01-05 22:25:12 +00003113
3114 Xforms.pop_back();
3115 }
3116}
3117
Chris Lattnerab3242f2008-01-06 01:10:31 +00003118void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003119 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
3120 while (!AMs.empty()) {
3121 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
3122 AMs.pop_back();
3123 }
3124}
3125
3126
3127/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3128/// file, building up the PatternFragments map. After we've collected them all,
3129/// inline fragments together as necessary, so that there are no references left
3130/// inside a pattern fragment to a pattern fragment.
3131///
Hal Finkel2756dc12014-02-28 00:26:56 +00003132void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003133 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003134
Chris Lattnere7170df2008-01-05 22:43:57 +00003135 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00003136 for (Record *Frag : Fragments) {
3137 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003138 continue;
3139
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003140 ListInit *LI = Frag->getValueAsListInit("Fragments");
Hal Finkel2756dc12014-02-28 00:26:56 +00003141 TreePattern *P =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003142 (PatternFragments[Frag] = std::make_unique<TreePattern>(
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003143 Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00003144 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003145
Chris Lattnere7170df2008-01-05 22:43:57 +00003146 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00003147 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00003148 // Copy the args so we can take StringRefs to them.
3149 auto ArgsCopy = Args;
3150 SmallDenseSet<StringRef, 4> OperandsSet;
3151 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003152
Chris Lattnere7170df2008-01-05 22:43:57 +00003153 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00003154 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003155
Chris Lattner8cab0212008-01-05 22:25:12 +00003156 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00003157 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00003158 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00003159 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003160 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00003161 if (!OpsOp ||
3162 (OpsOp->getDef()->getName() != "ops" &&
3163 OpsOp->getDef()->getName() != "outs" &&
3164 OpsOp->getDef()->getName() != "ins"))
3165 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003166
3167 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00003168 Args.clear();
3169 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003170 if (!isa<DefInit>(OpsList->getArg(j)) ||
3171 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00003172 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00003173 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00003174 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00003175 StringRef ArgNameStr = OpsList->getArgNameStr(j);
3176 if (!OperandsSet.count(ArgNameStr))
3177 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00003178 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00003179 OperandsSet.erase(ArgNameStr);
Benjamin Krameradcd0262020-01-28 20:23:46 +01003180 Args.push_back(std::string(ArgNameStr));
Chris Lattner8cab0212008-01-05 22:25:12 +00003181 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003182
Chris Lattnere7170df2008-01-05 22:43:57 +00003183 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003184 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00003185 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003186
Chris Lattner8cab0212008-01-05 22:25:12 +00003187 // If there is a node transformation corresponding to this, keep track of
3188 // it.
Craig Topper306cb122015-11-22 20:46:24 +00003189 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00003190 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003191 for (auto T : P->getTrees())
3192 T->setTransformFn(Transform);
Chris Lattner8cab0212008-01-05 22:25:12 +00003193 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003194
Chris Lattner8cab0212008-01-05 22:25:12 +00003195 // Now that we've parsed all of the tree fragments, do a closure on them so
3196 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00003197 for (Record *Frag : Fragments) {
3198 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003199 continue;
3200
Craig Topper306cb122015-11-22 20:46:24 +00003201 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00003202 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003203
Chris Lattner8cab0212008-01-05 22:25:12 +00003204 // Infer as many types as possible. Don't worry about it if we don't infer
Ulrich Weigand22b1af82018-07-13 16:42:15 +00003205 // all of them, some may depend on the inputs of the pattern. Also, don't
3206 // validate type sets; validation may cause spurious failures e.g. if a
3207 // fragment needs floating-point types but the current target does not have
3208 // any (this is only an error if that fragment is ever used!).
3209 {
3210 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3211 ThePat.InferAllTypes();
3212 ThePat.resetError();
3213 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003214
Chris Lattner8cab0212008-01-05 22:25:12 +00003215 // If debugging, print out the pattern fragment result.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003216 LLVM_DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003217 }
3218}
3219
Chris Lattnerab3242f2008-01-06 01:10:31 +00003220void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00003221 std::vector<Record*> DefaultOps;
3222 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00003223
3224 // Find some SDNode.
3225 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00003226 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003227
Tom Stellardb7246a72012-09-06 14:15:52 +00003228 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3229 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003230
Tom Stellardb7246a72012-09-06 14:15:52 +00003231 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3232 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00003233 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00003234 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3235 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3236 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00003237 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003238
Tom Stellardb7246a72012-09-06 14:15:52 +00003239 // Create a TreePattern to parse this.
3240 TreePattern P(DefaultOps[i], DI, false, *this);
3241 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003242
Tom Stellardb7246a72012-09-06 14:15:52 +00003243 // Copy the operands over into a DAGDefaultOperand.
3244 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003245
Florian Hahn75e87c32018-05-30 21:00:18 +00003246 const TreePatternNodePtr &T = P.getTree(0);
Tom Stellardb7246a72012-09-06 14:15:52 +00003247 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
Florian Hahn75e87c32018-05-30 21:00:18 +00003248 TreePatternNodePtr TPN = T->getChildShared(op);
Tom Stellardb7246a72012-09-06 14:15:52 +00003249 while (TPN->ApplyTypeConstraints(P, false))
3250 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003251
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003252 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00003253 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3254 DefaultOps[i]->getName() +
3255 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003256 }
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003257 DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
Chris Lattner8cab0212008-01-05 22:25:12 +00003258 }
Tom Stellardb7246a72012-09-06 14:15:52 +00003259
3260 // Insert it into the DefaultOperands map so we can find it later.
3261 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00003262 }
3263}
3264
3265/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3266/// instruction input. Return true if this is a real use.
David Blaikie19b22d42018-06-11 22:14:43 +00003267static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003268 std::map<std::string, TreePatternNodePtr> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003269 // No name -> not interesting.
3270 if (Pat->getName().empty()) {
3271 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003272 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00003273 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3274 DI->getDef()->isSubClassOf("RegisterOperand")))
David Blaikie19b22d42018-06-11 22:14:43 +00003275 I.error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003276 }
3277 return false;
3278 }
3279
3280 Record *Rec;
3281 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003282 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
David Blaikie19b22d42018-06-11 22:14:43 +00003283 if (!DI)
3284 I.error("Input $" + Pat->getName() + " must be an identifier!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003285 Rec = DI->getDef();
3286 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003287 Rec = Pat->getOperator();
3288 }
3289
3290 // SRCVALUE nodes are ignored.
3291 if (Rec->getName() == "srcvalue")
3292 return false;
3293
Florian Hahn75e87c32018-05-30 21:00:18 +00003294 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
Chris Lattner8cab0212008-01-05 22:25:12 +00003295 if (!Slot) {
3296 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003297 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00003298 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003299 Record *SlotRec;
3300 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003301 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003302 } else {
3303 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3304 SlotRec = Slot->getOperator();
3305 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003306
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003307 // Ensure that the inputs agree if we've already seen this input.
3308 if (Rec != SlotRec)
David Blaikie19b22d42018-06-11 22:14:43 +00003309 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003310 // Ensure that the types can agree as well.
3311 Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3312 Pat->UpdateNodeType(0, Slot->getExtType(0), I);
Chris Lattnerf1447252010-03-19 21:37:09 +00003313 if (Slot->getExtTypes() != Pat->getExtTypes())
David Blaikie19b22d42018-06-11 22:14:43 +00003314 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003315 return true;
3316}
3317
3318/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3319/// part of "I", the instruction), computing the set of inputs and outputs of
3320/// the pattern. Report errors if we see anything naughty.
Florian Hahn75e87c32018-05-30 21:00:18 +00003321void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
Florian Hahn6b1db822018-06-14 20:32:58 +00003322 TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003323 std::map<std::string, TreePatternNodePtr> &InstInputs,
Craig Topperbd199f82018-12-05 00:47:59 +00003324 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3325 &InstResults,
Florian Hahn75e87c32018-05-30 21:00:18 +00003326 std::vector<Record *> &InstImpResults) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003327
3328 // The instruction pattern still has unresolved fragments. For *named*
3329 // nodes we must resolve those here. This may not result in multiple
3330 // alternatives.
3331 if (!Pat->getName().empty()) {
3332 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3333 SrcPattern.InlinePatternFragments();
3334 SrcPattern.InferAllTypes();
3335 Pat = SrcPattern.getOnlyTree();
3336 }
3337
Chris Lattner8cab0212008-01-05 22:25:12 +00003338 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003339 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00003340 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003341 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003342 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003343 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003344
Chris Lattnerf2d70992010-02-17 06:53:36 +00003345 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003346 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003347 TreePatternNode *Dest = Pat->getChild(i);
3348 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003349 I.error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003350
Florian Hahn6b1db822018-06-14 20:32:58 +00003351 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003352 if (!Val || !Val->getDef()->isSubClassOf("Register"))
David Blaikie19b22d42018-06-11 22:14:43 +00003353 I.error("implicitly defined value should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003354 InstImpResults.push_back(Val->getDef());
3355 }
3356 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003357 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003358
Chris Lattnerf2d70992010-02-17 06:53:36 +00003359 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003360 // If this is not a set, verify that the children nodes are not void typed,
3361 // and recurse.
3362 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003363 if (Pat->getChild(i)->getNumTypes() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003364 I.error("Cannot have void nodes inside of patterns!");
Florian Hahn75e87c32018-05-30 21:00:18 +00003365 FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3366 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003367 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003368
Chris Lattner8cab0212008-01-05 22:25:12 +00003369 // If this is a non-leaf node with no children, treat it basically as if
3370 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003371 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003372
Chris Lattner8cab0212008-01-05 22:25:12 +00003373 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003374 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003375 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003376 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003377
Chris Lattner8cab0212008-01-05 22:25:12 +00003378 // Otherwise, this is a set, validate and collect instruction results.
3379 if (Pat->getNumChildren() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003380 I.error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003381
Chris Lattner8cab0212008-01-05 22:25:12 +00003382 if (Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003383 I.error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003384
Chris Lattner8cab0212008-01-05 22:25:12 +00003385 // Check the set destinations.
3386 unsigned NumDests = Pat->getNumChildren()-1;
3387 for (unsigned i = 0; i != NumDests; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003388 TreePatternNodePtr Dest = Pat->getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003389 // For set destinations we also must resolve fragments here.
3390 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3391 DestPattern.InlinePatternFragments();
3392 DestPattern.InferAllTypes();
3393 Dest = DestPattern.getOnlyTree();
3394
Chris Lattner8cab0212008-01-05 22:25:12 +00003395 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003396 I.error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003397
Sean Silvafb509ed2012-10-10 20:24:43 +00003398 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003399 if (!Val) {
David Blaikie19b22d42018-06-11 22:14:43 +00003400 I.error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003401 continue;
3402 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003403
3404 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003405 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003406 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003407 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003408 if (Dest->getName().empty())
David Blaikie19b22d42018-06-11 22:14:43 +00003409 I.error("set destination must have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003410 if (InstResults.count(Dest->getName()))
David Blaikie19b22d42018-06-11 22:14:43 +00003411 I.error("cannot set '" + Dest->getName() + "' multiple times");
Chris Lattner8cab0212008-01-05 22:25:12 +00003412 InstResults[Dest->getName()] = Dest;
3413 } else if (Val->getDef()->isSubClassOf("Register")) {
3414 InstImpResults.push_back(Val->getDef());
3415 } else {
David Blaikie19b22d42018-06-11 22:14:43 +00003416 I.error("set destination should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003417 }
3418 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003419
Chris Lattner8cab0212008-01-05 22:25:12 +00003420 // Verify and collect info from the computation.
Florian Hahn75e87c32018-05-30 21:00:18 +00003421 FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3422 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003423}
3424
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003425//===----------------------------------------------------------------------===//
3426// Instruction Analysis
3427//===----------------------------------------------------------------------===//
3428
3429class InstAnalyzer {
3430 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003431public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003432 bool hasSideEffects;
3433 bool mayStore;
3434 bool mayLoad;
3435 bool isBitcast;
3436 bool isVariadic;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003437 bool hasChain;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003438
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003439 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3440 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003441 isBitcast(false), isVariadic(false), hasChain(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003442
Craig Topper2a053a92017-06-20 16:34:37 +00003443 void Analyze(const PatternToMatch &Pat) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003444 const TreePatternNode *N = Pat.getSrcPattern();
3445 AnalyzeNode(N);
3446 // These properties are detected only on the root node.
3447 isBitcast = IsNodeBitcast(N);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003448 }
3449
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003450private:
Florian Hahn6b1db822018-06-14 20:32:58 +00003451 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003452 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003453 return false;
3454
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003455 if (N->isLeaf())
3456 return false;
3457 if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
Evan Cheng880e299d2011-03-15 05:09:26 +00003458 return false;
3459
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003460 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
Evan Cheng880e299d2011-03-15 05:09:26 +00003461 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3462 return false;
3463 return OpInfo.getEnumName() == "ISD::BITCAST";
3464 }
3465
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003466public:
Florian Hahn6b1db822018-06-14 20:32:58 +00003467 void AnalyzeNode(const TreePatternNode *N) {
3468 if (N->isLeaf()) {
3469 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003470 Record *LeafRec = DI->getDef();
3471 // Handle ComplexPattern leaves.
3472 if (LeafRec->isSubClassOf("ComplexPattern")) {
3473 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3474 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3475 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003476 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003477 }
3478 }
3479 return;
3480 }
3481
3482 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003483 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3484 AnalyzeNode(N->getChild(i));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003485
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003486 // Notice properties of the node.
Florian Hahn6b1db822018-06-14 20:32:58 +00003487 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3488 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3489 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3490 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003491 if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003492
Florian Hahn6b1db822018-06-14 20:32:58 +00003493 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003494 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003495 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003496 mayLoad = true;// These may load memory.
3497
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003498 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003499 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3500
Matt Arsenault868af922017-04-28 21:01:46 +00003501 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3502 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003503 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003504 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003505 }
3506 }
3507
3508};
3509
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003510static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003511 const InstAnalyzer &PatInfo,
3512 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003513 bool Error = false;
3514
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003515 // Remember where InstInfo got its flags.
3516 if (InstInfo.hasUndefFlags())
3517 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003518
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003519 // Check explicitly set flags for consistency.
3520 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3521 !InstInfo.hasSideEffects_Unset) {
3522 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3523 // the pattern has no side effects. That could be useful for div/rem
3524 // instructions that may trap.
3525 if (!InstInfo.hasSideEffects) {
3526 Error = true;
3527 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3528 Twine(InstInfo.hasSideEffects));
3529 }
3530 }
3531
3532 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3533 Error = true;
3534 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3535 Twine(InstInfo.mayStore));
3536 }
3537
3538 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3539 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003540 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003541 if (!InstInfo.mayLoad) {
3542 Error = true;
3543 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3544 Twine(InstInfo.mayLoad));
3545 }
3546 }
3547
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003548 // Transfer inferred flags.
3549 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3550 InstInfo.mayStore |= PatInfo.mayStore;
3551 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003552
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003553 // These flags are silently added without any verification.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003554 // FIXME: To match historical behavior of TableGen, for now add those flags
3555 // only when we're inferring from the primary instruction pattern.
3556 if (PatDef->isSubClassOf("Instruction")) {
3557 InstInfo.isBitcast |= PatInfo.isBitcast;
3558 InstInfo.hasChain |= PatInfo.hasChain;
3559 InstInfo.hasChain_Inferred = true;
3560 }
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003561
3562 // Don't infer isVariadic. This flag means something different on SDNodes and
3563 // instructions. For example, a CALL SDNode is variadic because it has the
3564 // call arguments as operands, but a CALL instruction is not variadic - it
3565 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003566
3567 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003568}
3569
Jim Grosbach514410b2012-07-17 00:47:06 +00003570/// hasNullFragReference - Return true if the DAG has any reference to the
3571/// null_frag operator.
3572static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003573 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003574 if (!OpDef) return false;
3575 Record *Operator = OpDef->getDef();
3576
3577 // If this is the null fragment, return true.
3578 if (Operator->getName() == "null_frag") return true;
3579 // If any of the arguments reference the null fragment, return true.
3580 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003581 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003582 if (Arg && hasNullFragReference(Arg))
3583 return true;
3584 }
3585
3586 return false;
3587}
3588
3589/// hasNullFragReference - Return true if any DAG in the list references
3590/// the null_frag operator.
3591static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003592 for (Init *I : LI->getValues()) {
3593 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003594 assert(DI && "non-dag in an instruction Pattern list?!");
3595 if (hasNullFragReference(DI))
3596 return true;
3597 }
3598 return false;
3599}
3600
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003601/// Get all the instructions in a tree.
3602static void
Florian Hahn6b1db822018-06-14 20:32:58 +00003603getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3604 if (Tree->isLeaf())
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003605 return;
Florian Hahn6b1db822018-06-14 20:32:58 +00003606 if (Tree->getOperator()->isSubClassOf("Instruction"))
3607 Instrs.push_back(Tree->getOperator());
3608 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3609 getInstructionsInTree(Tree->getChild(i), Instrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003610}
3611
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003612/// Check the class of a pattern leaf node against the instruction operand it
3613/// represents.
3614static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3615 Record *Leaf) {
3616 if (OI.Rec == Leaf)
3617 return true;
3618
3619 // Allow direct value types to be used in instruction set patterns.
3620 // The type will be checked later.
3621 if (Leaf->isSubClassOf("ValueType"))
3622 return true;
3623
3624 // Patterns can also be ComplexPattern instances.
3625 if (Leaf->isSubClassOf("ComplexPattern"))
3626 return true;
3627
3628 return false;
3629}
3630
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003631void CodeGenDAGPatterns::parseInstructionPattern(
Ahmed Bougacha14107512013-10-28 18:07:21 +00003632 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003633
Craig Topper0d1fb902015-03-10 03:25:04 +00003634 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003635
Craig Topper0d1fb902015-03-10 03:25:04 +00003636 // Parse the instruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003637 TreePattern I(CGI.TheDef, Pat, true, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003638
Craig Topper0d1fb902015-03-10 03:25:04 +00003639 // InstInputs - Keep track of all of the inputs of the instruction, along
3640 // with the record they are declared as.
Florian Hahn75e87c32018-05-30 21:00:18 +00003641 std::map<std::string, TreePatternNodePtr> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003642
Craig Topper0d1fb902015-03-10 03:25:04 +00003643 // InstResults - Keep track of all the virtual registers that are 'set'
3644 // in the instruction, including what reg class they are.
Craig Topperbd199f82018-12-05 00:47:59 +00003645 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3646 InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003647
Craig Topper0d1fb902015-03-10 03:25:04 +00003648 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003649
Craig Topper0d1fb902015-03-10 03:25:04 +00003650 // Verify that the top-level forms in the instruction are of void type, and
3651 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003652 SmallString<32> TypesString;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003653 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003654 TypesString.clear();
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003655 TreePatternNodePtr Pat = I.getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003656 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003657 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003658 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3659 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003660 OS << ", ";
3661 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003662 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003663 I.error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003664 " void types, has types " +
3665 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003666 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003667
Craig Topper0d1fb902015-03-10 03:25:04 +00003668 // Find inputs and outputs, and verify the structure of the uses/defs.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003669 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Craig Topper0d1fb902015-03-10 03:25:04 +00003670 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003671 }
3672
Craig Topper0d1fb902015-03-10 03:25:04 +00003673 // Now that we have inputs and outputs of the pattern, inspect the operands
3674 // list for the instruction. This determines the order that operands are
3675 // added to the machine instruction the node corresponds to.
3676 unsigned NumResults = InstResults.size();
3677
3678 // Parse the operands list from the (ops) list, validating it.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003679 assert(I.getArgList().empty() && "Args list should still be empty here!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003680
3681 // Check that all of the results occur first in the list.
3682 std::vector<Record*> Results;
Craig Topperbd199f82018-12-05 00:47:59 +00003683 std::vector<unsigned> ResultIndices;
Florian Hahn75e87c32018-05-30 21:00:18 +00003684 SmallVector<TreePatternNodePtr, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003685 for (unsigned i = 0; i != NumResults; ++i) {
Craig Topperbd199f82018-12-05 00:47:59 +00003686 if (i == CGI.Operands.size()) {
3687 const std::string &OpName =
3688 std::find_if(InstResults.begin(), InstResults.end(),
3689 [](const std::pair<std::string, TreePatternNodePtr> &P) {
3690 return P.second;
3691 })
3692 ->first;
3693
3694 I.error("'" + OpName + "' set but does not appear in operand list!");
3695 }
3696
Craig Topper0d1fb902015-03-10 03:25:04 +00003697 const std::string &OpName = CGI.Operands[i].Name;
3698
3699 // Check that it exists in InstResults.
Craig Topperbd199f82018-12-05 00:47:59 +00003700 auto InstResultIter = InstResults.find(OpName);
3701 if (InstResultIter == InstResults.end() || !InstResultIter->second)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003702 I.error("Operand $" + OpName + " does not exist in operand list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003703
Craig Topperbd199f82018-12-05 00:47:59 +00003704 TreePatternNodePtr RNode = InstResultIter->second;
Craig Topper0d1fb902015-03-10 03:25:04 +00003705 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003706 ResNodes.push_back(std::move(RNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003707 if (!R)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003708 I.error("Operand $" + OpName + " should be a set destination: all "
Craig Topper0d1fb902015-03-10 03:25:04 +00003709 "outputs must occur before inputs in operand list!");
3710
3711 if (!checkOperandClass(CGI.Operands[i], R))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003712 I.error("Operand $" + OpName + " class mismatch!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003713
3714 // Remember the return type.
3715 Results.push_back(CGI.Operands[i].Rec);
3716
Craig Topperbd199f82018-12-05 00:47:59 +00003717 // Remember the result index.
3718 ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
3719
Craig Topper0d1fb902015-03-10 03:25:04 +00003720 // Okay, this one checks out.
Craig Topperbd199f82018-12-05 00:47:59 +00003721 InstResultIter->second = nullptr;
Craig Topper0d1fb902015-03-10 03:25:04 +00003722 }
3723
Craig Topper765b9202018-07-15 06:52:48 +00003724 // Loop over the inputs next.
Florian Hahn75e87c32018-05-30 21:00:18 +00003725 std::vector<TreePatternNodePtr> ResultNodeOperands;
Craig Topper0d1fb902015-03-10 03:25:04 +00003726 std::vector<Record*> Operands;
3727 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3728 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3729 const std::string &OpName = Op.Name;
3730 if (OpName.empty())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003731 I.error("Operand #" + Twine(i) + " in operands list has no name!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003732
Craig Topper765b9202018-07-15 06:52:48 +00003733 if (!InstInputs.count(OpName)) {
Craig Topper0d1fb902015-03-10 03:25:04 +00003734 // If this is an operand with a DefaultOps set filled in, we can ignore
3735 // this. When we codegen it, we will do so as always executed.
3736 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3737 // Does it have a non-empty DefaultOps field? If so, ignore this
3738 // operand.
3739 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3740 continue;
3741 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003742 I.error("Operand $" + OpName +
Craig Topper0d1fb902015-03-10 03:25:04 +00003743 " does not appear in the instruction pattern");
3744 }
Craig Topper765b9202018-07-15 06:52:48 +00003745 TreePatternNodePtr InVal = InstInputs[OpName];
3746 InstInputs.erase(OpName); // It occurred, remove from map.
Craig Topper0d1fb902015-03-10 03:25:04 +00003747
3748 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3749 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3750 if (!checkOperandClass(Op, InRec))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003751 I.error("Operand $" + OpName + "'s register class disagrees"
Craig Topper0d1fb902015-03-10 03:25:04 +00003752 " between the operand and pattern");
3753 }
3754 Operands.push_back(Op.Rec);
3755
3756 // Construct the result for the dest-pattern operand list.
Florian Hahn75e87c32018-05-30 21:00:18 +00003757 TreePatternNodePtr OpNode = InVal->clone();
Craig Topper0d1fb902015-03-10 03:25:04 +00003758
3759 // No predicate is useful on the result.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003760 OpNode->clearPredicateCalls();
Craig Topper0d1fb902015-03-10 03:25:04 +00003761
3762 // Promote the xform function to be an explicit node if set.
3763 if (Record *Xform = OpNode->getTransformFn()) {
3764 OpNode->setTransformFn(nullptr);
Florian Hahn75e87c32018-05-30 21:00:18 +00003765 std::vector<TreePatternNodePtr> Children;
Craig Topper0d1fb902015-03-10 03:25:04 +00003766 Children.push_back(OpNode);
Craig Topper26fc06352018-07-15 06:52:49 +00003767 OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
Florian Hahn6b1db822018-06-14 20:32:58 +00003768 OpNode->getNumTypes());
Craig Topper0d1fb902015-03-10 03:25:04 +00003769 }
3770
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003771 ResultNodeOperands.push_back(std::move(OpNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003772 }
3773
Craig Topper765b9202018-07-15 06:52:48 +00003774 if (!InstInputs.empty())
3775 I.error("Input operand $" + InstInputs.begin()->first +
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003776 " occurs in pattern but not in operands list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003777
Florian Hahn6b1db822018-06-14 20:32:58 +00003778 TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00003779 I.getRecord(), std::move(ResultNodeOperands),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003780 GetNumNodeResults(I.getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003781 // Copy fully inferred output node types to instruction result pattern.
3782 for (unsigned i = 0; i != NumResults; ++i) {
3783 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3784 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
Craig Topperbd199f82018-12-05 00:47:59 +00003785 ResultPattern->setResultIndex(i, ResultIndices[i]);
Craig Topper3a8eb892015-03-20 05:09:06 +00003786 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003787
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003788 // FIXME: Assume only the first tree is the pattern. The others are clobber
3789 // nodes.
3790 TreePatternNodePtr Pattern = I.getTree(0);
3791 TreePatternNodePtr SrcPattern;
3792 if (Pattern->getOperator()->getName() == "set") {
3793 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3794 } else{
3795 // Not a set (store or something?)
3796 SrcPattern = Pattern;
3797 }
3798
Craig Topper0d1fb902015-03-10 03:25:04 +00003799 // Create and insert the instruction.
3800 // FIXME: InstImpResults should not be part of DAGInstruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003801 Record *R = I.getRecord();
3802 DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3803 std::forward_as_tuple(Results, Operands, InstImpResults,
3804 SrcPattern, ResultPattern));
Craig Topper0d1fb902015-03-10 03:25:04 +00003805
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003806 LLVM_DEBUG(I.dump());
Craig Topper0d1fb902015-03-10 03:25:04 +00003807}
3808
Ahmed Bougacha14107512013-10-28 18:07:21 +00003809/// ParseInstructions - Parse all of the instructions, inlining and resolving
3810/// any fragments involved. This populates the Instructions list with fully
3811/// resolved instructions.
3812void CodeGenDAGPatterns::ParseInstructions() {
3813 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3814
Craig Topper306cb122015-11-22 20:46:24 +00003815 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003816 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003817
Craig Topper306cb122015-11-22 20:46:24 +00003818 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3819 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003820
3821 // If there is no pattern, only collect minimal information about the
3822 // instruction for its operand list. We have to assume that there is one
3823 // result, as we have no detailed info. A pattern which references the
3824 // null_frag operator is as-if no pattern were specified. Normally this
3825 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3826 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003827 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003828 std::vector<Record*> Results;
3829 std::vector<Record*> Operands;
3830
Craig Topper306cb122015-11-22 20:46:24 +00003831 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003832
3833 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003834 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3835 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003836
Craig Topper3a8eb892015-03-20 05:09:06 +00003837 // The rest are inputs.
3838 for (unsigned j = InstInfo.Operands.NumDefs,
3839 e = InstInfo.Operands.size(); j < e; ++j)
3840 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003841 }
3842
3843 // Create and insert the instruction.
3844 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003845 Instructions.insert(std::make_pair(Instr,
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003846 DAGInstruction(Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003847 continue; // no pattern.
3848 }
3849
Craig Topper306cb122015-11-22 20:46:24 +00003850 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003851 parseInstructionPattern(CGI, LI, Instructions);
Chris Lattner8cab0212008-01-05 22:25:12 +00003852 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003853
Chris Lattner8cab0212008-01-05 22:25:12 +00003854 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003855 for (auto &Entry : Instructions) {
Craig Topper306cb122015-11-22 20:46:24 +00003856 Record *Instr = Entry.first;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003857 DAGInstruction &TheInst = Entry.second;
3858 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3859 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3860
3861 if (SrcPattern && ResultPattern) {
3862 TreePattern Pattern(Instr, SrcPattern, true, *this);
3863 TreePattern Result(Instr, ResultPattern, false, *this);
3864 ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3865 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003866 }
3867}
3868
Florian Hahn6b1db822018-06-14 20:32:58 +00003869typedef std::pair<TreePatternNode *, unsigned> NameRecord;
Chris Lattnera7722b62010-02-23 06:55:24 +00003870
Florian Hahn6b1db822018-06-14 20:32:58 +00003871static void FindNames(TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003872 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003873 TreePattern *PatternTop) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003874 if (!P->getName().empty()) {
3875 NameRecord &Rec = Names[P->getName()];
Chris Lattnera7722b62010-02-23 06:55:24 +00003876 // If this is the first instance of the name, remember the node.
3877 if (Rec.second++ == 0)
Florian Hahn6b1db822018-06-14 20:32:58 +00003878 Rec.first = P;
3879 else if (Rec.first->getExtTypes() != P->getExtTypes())
3880 PatternTop->error("repetition of value: $" + P->getName() +
Chris Lattner5b0e2492010-02-23 07:22:28 +00003881 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003882 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003883
Florian Hahn6b1db822018-06-14 20:32:58 +00003884 if (!P->isLeaf()) {
3885 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3886 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003887 }
3888}
3889
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003890std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3891 std::vector<Predicate> Preds;
3892 for (Init *I : L->getValues()) {
3893 if (DefInit *Pred = dyn_cast<DefInit>(I))
3894 Preds.push_back(Pred->getDef());
3895 else
3896 llvm_unreachable("Non-def on the list");
3897 }
3898
3899 // Sort so that different orders get canonicalized to the same string.
Fangrui Song0cac7262018-09-27 02:13:45 +00003900 llvm::sort(Preds);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003901 return Preds;
3902}
3903
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003904void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003905 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003906 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003907 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003908 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3909 PrintWarning(Pattern->getRecord()->getLoc(),
3910 Twine("Pattern can never match: ") + Reason);
3911 return;
3912 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003913
Chris Lattner1e634e32010-03-01 22:29:19 +00003914 // If the source pattern's root is a complex pattern, that complex pattern
3915 // must specify the nodes it can potentially match.
3916 if (const ComplexPattern *CP =
3917 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3918 if (CP->getRootNodes().empty())
3919 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3920 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003921
3922
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003923 // Find all of the named values in the input and output, ensure they have the
3924 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003925 std::map<std::string, NameRecord> SrcNames, DstNames;
Florian Hahn6b1db822018-06-14 20:32:58 +00003926 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3927 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003928
3929 // Scan all of the named values in the destination pattern, rejecting them if
3930 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003931 for (const auto &Entry : DstNames) {
3932 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003933 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003934 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003935 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003936
Chris Lattnera7722b62010-02-23 06:55:24 +00003937 // Scan all of the named values in the source pattern, rejecting them if the
3938 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003939 for (const auto &Entry : SrcNames)
3940 if (DstNames[Entry.first].first == nullptr &&
3941 SrcNames[Entry.first].second == 1)
3942 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003943
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003944 PatternsToMatch.push_back(PTM);
Chris Lattner0c0baa92010-02-23 06:16:51 +00003945}
3946
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003947void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003948 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003949 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003950
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003951 unsigned Errors = 0;
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003952
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003953 // Try to infer flags from all patterns in PatternToMatch. These include
3954 // both the primary instruction patterns (which always come first) and
3955 // patterns defined outside the instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003956 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003957 // We can only infer from single-instruction patterns, otherwise we won't
3958 // know which instruction should get the flags.
3959 SmallVector<Record*, 8> PatInstrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003960 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003961 if (PatInstrs.size() != 1)
3962 continue;
3963
3964 // Get the single instruction.
3965 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3966
3967 // Only infer properties from the first pattern. We'll verify the others.
3968 if (InstInfo.InferredFrom)
3969 continue;
3970
3971 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003972 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003973 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3974 }
3975
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003976 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003977 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003978
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003979 // If requested by the target, guess any undefined properties.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003980 if (Target.guessInstructionProperties()) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003981 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3982 CodeGenInstruction *InstInfo =
3983 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003984 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003985 continue;
3986 // The mayLoad and mayStore flags default to false.
3987 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003988 if (InstInfo->hasSideEffects_Unset)
3989 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003990 }
3991 return;
3992 }
3993
3994 // Complain about any flags that are still undefined.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003995 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3996 CodeGenInstruction *InstInfo =
3997 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003998 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003999 continue;
Craig Topper306cb122015-11-22 20:46:24 +00004000 if (InstInfo->hasSideEffects_Unset)
4001 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00004002 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00004003 if (InstInfo->mayStore_Unset)
4004 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00004005 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00004006 if (InstInfo->mayLoad_Unset)
4007 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00004008 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00004009 }
4010}
4011
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004012
4013/// Verify instruction flags against pattern node properties.
4014void CodeGenDAGPatterns::VerifyInstructionFlags() {
4015 unsigned Errors = 0;
4016 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
4017 const PatternToMatch &PTM = *I;
4018 SmallVector<Record*, 8> Instrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00004019 getInstructionsInTree(PTM.getDstPattern(), Instrs);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004020 if (Instrs.empty())
4021 continue;
4022
4023 // Count the number of instructions with each flag set.
4024 unsigned NumSideEffects = 0;
4025 unsigned NumStores = 0;
4026 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00004027 for (const Record *Instr : Instrs) {
4028 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004029 NumSideEffects += InstInfo.hasSideEffects;
4030 NumStores += InstInfo.mayStore;
4031 NumLoads += InstInfo.mayLoad;
4032 }
4033
4034 // Analyze the source pattern.
4035 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00004036 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004037
4038 // Collect error messages.
4039 SmallVector<std::string, 4> Msgs;
4040
4041 // Check for missing flags in the output.
4042 // Permit extra flags for now at least.
4043 if (PatInfo.hasSideEffects && !NumSideEffects)
4044 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
4045
4046 // Don't verify store flags on instructions with side effects. At least for
4047 // intrinsics, side effects implies mayStore.
4048 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
4049 Msgs.push_back("pattern may store, but mayStore isn't set");
4050
4051 // Similarly, mayStore implies mayLoad on intrinsics.
4052 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
4053 Msgs.push_back("pattern may load, but mayLoad isn't set");
4054
4055 // Print error messages.
4056 if (Msgs.empty())
4057 continue;
4058 ++Errors;
4059
Craig Topper306cb122015-11-22 20:46:24 +00004060 for (const std::string &Msg : Msgs)
4061 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004062 (Instrs.size() == 1 ?
4063 "instruction" : "output instructions"));
4064 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00004065 for (const Record *Instr : Instrs) {
4066 if (Instr != PTM.getSrcRecord())
4067 PrintError(Instr->getLoc(), "defined here");
4068 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004069 if (InstInfo.InferredFrom &&
4070 InstInfo.InferredFrom != InstInfo.TheDef &&
4071 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004072 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004073 }
4074 }
4075 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00004076 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004077}
4078
Chris Lattnercabe0372010-03-15 06:00:16 +00004079/// Given a pattern result with an unresolved type, see if we can find one
4080/// instruction with an unresolved result type. Force this result type to an
4081/// arbitrary element if it's possible types to converge results.
Florian Hahn6b1db822018-06-14 20:32:58 +00004082static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
4083 if (N->isLeaf())
Chris Lattnercabe0372010-03-15 06:00:16 +00004084 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004085
Chris Lattnercabe0372010-03-15 06:00:16 +00004086 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00004087 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4088 if (ForceArbitraryInstResultType(N->getChild(i), TP))
Chris Lattnercabe0372010-03-15 06:00:16 +00004089 return true;
4090
Florian Hahn6b1db822018-06-14 20:32:58 +00004091 if (!N->getOperator()->isSubClassOf("Instruction"))
Chris Lattnercabe0372010-03-15 06:00:16 +00004092 return false;
4093
4094 // If this type is already concrete or completely unknown we can't do
4095 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004096 TypeInfer &TI = TP.getInfer();
Florian Hahn6b1db822018-06-14 20:32:58 +00004097 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
4098 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00004099 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004100
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004101 // Otherwise, force its type to an arbitrary choice.
Florian Hahn6b1db822018-06-14 20:32:58 +00004102 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00004103 return true;
4104 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004105
Chris Lattnerf1447252010-03-19 21:37:09 +00004106 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00004107}
4108
Ulrich Weigand58a97862018-08-01 11:57:58 +00004109// Promote xform function to be an explicit node wherever set.
4110static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4111 if (Record *Xform = N->getTransformFn()) {
4112 N->setTransformFn(nullptr);
4113 std::vector<TreePatternNodePtr> Children;
4114 Children.push_back(PromoteXForms(N));
4115 return std::make_shared<TreePatternNode>(Xform, std::move(Children),
4116 N->getNumTypes());
4117 }
4118
4119 if (!N->isLeaf())
4120 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4121 TreePatternNodePtr Child = N->getChildShared(i);
Ulrich Weigandf989cd72018-08-01 12:07:32 +00004122 N->setChild(i, PromoteXForms(Child));
Ulrich Weigand58a97862018-08-01 11:57:58 +00004123 }
4124 return N;
4125}
4126
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004127void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
4128 TreePattern &Pattern, TreePattern &Result,
4129 const std::vector<Record *> &InstImpResults) {
4130
4131 // Inline pattern fragments and expand multiple alternatives.
4132 Pattern.InlinePatternFragments();
4133 Result.InlinePatternFragments();
4134
4135 if (Result.getNumTrees() != 1)
4136 Result.error("Cannot use multi-alternative fragments in result pattern!");
4137
4138 // Infer types.
4139 bool IterateInference;
4140 bool InferredAllPatternTypes, InferredAllResultTypes;
4141 do {
4142 // Infer as many types as possible. If we cannot infer all of them, we
4143 // can never do anything with this pattern: report it to the user.
4144 InferredAllPatternTypes =
4145 Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
4146
4147 // Infer as many types as possible. If we cannot infer all of them, we
4148 // can never do anything with this pattern: report it to the user.
4149 InferredAllResultTypes =
4150 Result.InferAllTypes(&Pattern.getNamedNodesMap());
4151
4152 IterateInference = false;
4153
4154 // Apply the type of the result to the source pattern. This helps us
4155 // resolve cases where the input type is known to be a pointer type (which
4156 // is considered resolved), but the result knows it needs to be 32- or
4157 // 64-bits. Infer the other way for good measure.
4158 for (auto T : Pattern.getTrees())
4159 for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4160 T->getNumTypes());
4161 i != e; ++i) {
4162 IterateInference |= T->UpdateNodeType(
4163 i, Result.getOnlyTree()->getExtType(i), Result);
4164 IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4165 i, T->getExtType(i), Result);
4166 }
4167
4168 // If our iteration has converged and the input pattern's types are fully
4169 // resolved but the result pattern is not fully resolved, we may have a
4170 // situation where we have two instructions in the result pattern and
4171 // the instructions require a common register class, but don't care about
4172 // what actual MVT is used. This is actually a bug in our modelling:
4173 // output patterns should have register classes, not MVTs.
4174 //
4175 // In any case, to handle this, we just go through and disambiguate some
4176 // arbitrary types to the result pattern's nodes.
4177 if (!IterateInference && InferredAllPatternTypes &&
4178 !InferredAllResultTypes)
4179 IterateInference =
4180 ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4181 } while (IterateInference);
4182
4183 // Verify that we inferred enough types that we can do something with the
4184 // pattern and result. If these fire the user has to add type casts.
4185 if (!InferredAllPatternTypes)
4186 Pattern.error("Could not infer all types in pattern!");
4187 if (!InferredAllResultTypes) {
4188 Pattern.dump();
4189 Result.error("Could not infer all types in pattern result!");
4190 }
4191
Ulrich Weigand58a97862018-08-01 11:57:58 +00004192 // Promote xform function to be an explicit node wherever set.
4193 TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004194
4195 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4196 Temp.InferAllTypes();
4197
4198 ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4199 int Complexity = TheDef->getValueAsInt("AddedComplexity");
4200
4201 if (PatternRewriter)
4202 PatternRewriter(&Pattern);
4203
4204 // A pattern may end up with an "impossible" type, i.e. a situation
4205 // where all types have been eliminated for some node in this pattern.
4206 // This could occur for intrinsics that only make sense for a specific
4207 // value type, and use a specific register class. If, for some mode,
4208 // that register class does not accept that type, the type inference
4209 // will lead to a contradiction, which is not an error however, but
4210 // a sign that this pattern will simply never match.
4211 if (Temp.getOnlyTree()->hasPossibleType())
4212 for (auto T : Pattern.getTrees())
4213 if (T->hasPossibleType())
4214 AddPatternToMatch(&Pattern,
4215 PatternToMatch(TheDef, makePredList(Preds),
4216 T, Temp.getOnlyTree(),
4217 InstImpResults, Complexity,
4218 TheDef->getID()));
4219}
4220
Chris Lattnerab3242f2008-01-06 01:10:31 +00004221void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00004222 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4223
Craig Topper306cb122015-11-22 20:46:24 +00004224 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00004225 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00004226
4227 // If the pattern references the null_frag, there's nothing to do.
4228 if (hasNullFragReference(Tree))
4229 continue;
4230
Florian Hahn75e87c32018-05-30 21:00:18 +00004231 TreePattern Pattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00004232
David Greeneaf8ee2c2011-07-29 22:43:06 +00004233 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00004234 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004235
Chris Lattner8cab0212008-01-05 22:25:12 +00004236 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004237 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004238
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004239 if (Result.getNumTrees() != 1)
4240 Result.error("Cannot handle instructions producing instructions "
4241 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004242
Chris Lattner8cab0212008-01-05 22:25:12 +00004243 // Validate that the input pattern is correct.
Florian Hahn75e87c32018-05-30 21:00:18 +00004244 std::map<std::string, TreePatternNodePtr> InstInputs;
Craig Topperbd199f82018-12-05 00:47:59 +00004245 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
4246 InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00004247 std::vector<Record*> InstImpResults;
Florian Hahn75e87c32018-05-30 21:00:18 +00004248 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
David Blaikie19b22d42018-06-11 22:14:43 +00004249 FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
Florian Hahn75e87c32018-05-30 21:00:18 +00004250 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004251
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004252 ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004253 }
4254}
4255
Florian Hahn6b1db822018-06-14 20:32:58 +00004256static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004257 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4258 for (const auto &I : VTS)
4259 Modes.insert(I.first);
4260
4261 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00004262 collectModes(Modes, N->getChild(i));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004263}
4264
4265void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4266 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4267 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4268 std::vector<PatternToMatch> Copy = PatternsToMatch;
4269 PatternsToMatch.clear();
4270
Florian Hahn75e87c32018-05-30 21:00:18 +00004271 auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4272 TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4273 TreePatternNodePtr NewDst = P.DstPattern->clone();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004274 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004275 return;
4276 }
4277
4278 std::vector<Predicate> Preds = P.Predicates;
4279 const std::vector<Predicate> &MC = ModeChecks[Mode];
4280 Preds.insert(Preds.end(), MC.begin(), MC.end());
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004281 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4282 std::move(NewDst), P.getDstRegs(),
4283 P.getAddedComplexity(), Record::getNewUID(),
4284 Mode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004285 };
4286
4287 for (PatternToMatch &P : Copy) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004288 TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
Florian Hahn6b1db822018-06-14 20:32:58 +00004289 if (P.SrcPattern->hasProperTypeByHwMode())
4290 SrcP = P.SrcPattern;
4291 if (P.DstPattern->hasProperTypeByHwMode())
4292 DstP = P.DstPattern;
4293 if (!SrcP && !DstP) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004294 PatternsToMatch.push_back(P);
4295 continue;
4296 }
4297
4298 std::set<unsigned> Modes;
Florian Hahn6b1db822018-06-14 20:32:58 +00004299 if (SrcP)
4300 collectModes(Modes, SrcP.get());
4301 if (DstP)
4302 collectModes(Modes, DstP.get());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004303
4304 // The predicate for the default mode needs to be constructed for each
4305 // pattern separately.
4306 // Since not all modes must be present in each pattern, if a mode m is
4307 // absent, then there is no point in constructing a check for m. If such
4308 // a check was created, it would be equivalent to checking the default
4309 // mode, except not all modes' predicates would be a part of the checking
4310 // code. The subsequently generated check for the default mode would then
4311 // have the exact same patterns, but a different predicate code. To avoid
4312 // duplicated patterns with different predicate checks, construct the
4313 // default check as a negation of all predicates that are actually present
4314 // in the source/destination patterns.
4315 std::vector<Predicate> DefaultPred;
4316
4317 for (unsigned M : Modes) {
4318 if (M == DefaultMode)
4319 continue;
4320 if (ModeChecks.find(M) != ModeChecks.end())
4321 continue;
4322
4323 // Fill the map entry for this mode.
4324 const HwMode &HM = CGH.getMode(M);
4325 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4326
4327 // Add negations of the HM's predicates to the default predicate.
4328 DefaultPred.emplace_back(Predicate(HM.Features, false));
4329 }
4330
4331 for (unsigned M : Modes) {
4332 if (M == DefaultMode)
4333 continue;
4334 AppendPattern(P, M);
4335 }
4336
4337 bool HasDefault = Modes.count(DefaultMode);
4338 if (HasDefault)
4339 AppendPattern(P, DefaultMode);
4340 }
4341}
4342
4343/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004344typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004345
Florian Hahn6b1db822018-06-14 20:32:58 +00004346static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4347 if (N->isLeaf()) {
4348 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4349 DepMap[N->getName()]++;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004350 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00004351 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4352 FindDepVarsOf(N->getChild(i), DepMap);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004353 }
4354}
4355
4356/// Find dependent variables within child patterns
Florian Hahn6b1db822018-06-14 20:32:58 +00004357static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004358 DepVarMap depcounts;
4359 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004360 for (const auto &Pair : depcounts) {
4361 if (Pair.getValue() > 1)
4362 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004363 }
4364}
4365
4366#ifndef NDEBUG
4367/// Dump the dependent variable set:
4368static void DumpDepVars(MultipleUseVarSet &DepVars) {
4369 if (DepVars.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004370 LLVM_DEBUG(errs() << "<empty set>");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004371 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004372 LLVM_DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004373 for (const auto &DepVar : DepVars) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004374 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004375 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004376 LLVM_DEBUG(errs() << "]");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004377 }
4378}
4379#endif
4380
4381
Chris Lattner8cab0212008-01-05 22:25:12 +00004382/// CombineChildVariants - Given a bunch of permutations of each child of the
4383/// 'operator' node, put them together in all possible ways.
Florian Hahn75e87c32018-05-30 21:00:18 +00004384static void CombineChildVariants(
Florian Hahn6b1db822018-06-14 20:32:58 +00004385 TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004386 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4387 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4388 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004389 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004390 for (const auto &Variants : ChildVariants)
4391 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004392 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004393
Chris Lattner8cab0212008-01-05 22:25:12 +00004394 // The end result is an all-pairs construction of the resultant pattern.
4395 std::vector<unsigned> Idxs;
4396 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004397 bool NotDone;
4398 do {
4399#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004400 LLVM_DEBUG(if (!Idxs.empty()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004401 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004402 for (unsigned Idx : Idxs) {
4403 errs() << Idx << " ";
4404 }
4405 errs() << "]\n";
4406 });
Scott Michel94420742008-03-05 17:49:05 +00004407#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004408 // Create the variant and add it to the output list.
Florian Hahn75e87c32018-05-30 21:00:18 +00004409 std::vector<TreePatternNodePtr> NewChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004410 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4411 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Florian Hahn75e87c32018-05-30 21:00:18 +00004412 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00004413 Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004414
Chris Lattner8cab0212008-01-05 22:25:12 +00004415 // Copy over properties.
Florian Hahn6b1db822018-06-14 20:32:58 +00004416 R->setName(Orig->getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00004417 R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4418 R->setPredicateCalls(Orig->getPredicateCalls());
Florian Hahn6b1db822018-06-14 20:32:58 +00004419 R->setTransformFn(Orig->getTransformFn());
4420 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4421 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004422
Scott Michel94420742008-03-05 17:49:05 +00004423 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004424 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004425 // Scan to see if this pattern has already been emitted. We can get
4426 // duplication due to things like commuting:
4427 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4428 // which are the same pattern. Ignore the dups.
4429 if (R->canPatternMatch(ErrString, CDP) &&
Florian Hahn75e87c32018-05-30 21:00:18 +00004430 none_of(OutVariants, [&](TreePatternNodePtr Variant) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004431 return R->isIsomorphicTo(Variant.get(), DepVars);
David Majnemer0a16c222016-08-11 21:15:00 +00004432 }))
Florian Hahn75e87c32018-05-30 21:00:18 +00004433 OutVariants.push_back(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004434
Scott Michel94420742008-03-05 17:49:05 +00004435 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004436 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004437 // [0, 0], [0, 1], [1, 0], [1, 1].
4438 int IdxsIdx;
4439 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4440 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4441 Idxs[IdxsIdx] = 0;
4442 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004443 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004444 }
Scott Michel94420742008-03-05 17:49:05 +00004445 NotDone = (IdxsIdx >= 0);
4446 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004447}
4448
4449/// CombineChildVariants - A helper function for binary operators.
4450///
Florian Hahn6b1db822018-06-14 20:32:58 +00004451static void CombineChildVariants(TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004452 const std::vector<TreePatternNodePtr> &LHS,
4453 const std::vector<TreePatternNodePtr> &RHS,
4454 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004455 CodeGenDAGPatterns &CDP,
4456 const MultipleUseVarSet &DepVars) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004457 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004458 ChildVariants.push_back(LHS);
4459 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004460 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004461}
Chris Lattner8cab0212008-01-05 22:25:12 +00004462
Florian Hahn75e87c32018-05-30 21:00:18 +00004463static void
Florian Hahn6b1db822018-06-14 20:32:58 +00004464GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004465 std::vector<TreePatternNodePtr> &Children) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004466 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4467 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004468
Chris Lattner8cab0212008-01-05 22:25:12 +00004469 // Only permit raw nodes.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00004470 if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004471 N->getTransformFn()) {
4472 Children.push_back(N);
4473 return;
4474 }
4475
Florian Hahn6b1db822018-06-14 20:32:58 +00004476 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004477 Children.push_back(N->getChildShared(0));
Chris Lattner8cab0212008-01-05 22:25:12 +00004478 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004479 GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004480
Florian Hahn6b1db822018-06-14 20:32:58 +00004481 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004482 Children.push_back(N->getChildShared(1));
Chris Lattner8cab0212008-01-05 22:25:12 +00004483 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004484 GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004485}
4486
4487/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4488/// the (potentially recursive) pattern by using algebraic laws.
4489///
Florian Hahn6b1db822018-06-14 20:32:58 +00004490static void GenerateVariantsOf(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004491 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004492 CodeGenDAGPatterns &CDP,
4493 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004494 // We cannot permute leaves or ComplexPattern uses.
4495 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004496 OutVariants.push_back(N);
4497 return;
4498 }
4499
4500 // Look up interesting info about the node.
4501 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4502
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004503 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004504 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004505 // Re-associate by pulling together all of the linked operators
Florian Hahn75e87c32018-05-30 21:00:18 +00004506 std::vector<TreePatternNodePtr> MaximalChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004507 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4508
4509 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4510 // permutations.
4511 if (MaximalChildren.size() == 3) {
4512 // Find the variants of all of our maximal children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004513 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004514 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4515 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4516 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004517
Chris Lattner8cab0212008-01-05 22:25:12 +00004518 // There are only two ways we can permute the tree:
4519 // (A op B) op C and A op (B op C)
4520 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004521
Chris Lattner8cab0212008-01-05 22:25:12 +00004522 // Generate legal pair permutations of A/B/C.
Florian Hahn75e87c32018-05-30 21:00:18 +00004523 std::vector<TreePatternNodePtr> ABVariants;
4524 std::vector<TreePatternNodePtr> BAVariants;
4525 std::vector<TreePatternNodePtr> ACVariants;
4526 std::vector<TreePatternNodePtr> CAVariants;
4527 std::vector<TreePatternNodePtr> BCVariants;
4528 std::vector<TreePatternNodePtr> CBVariants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004529 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4530 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4531 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4532 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4533 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4534 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004535
4536 // Combine those into the result: (x op x) op x
Florian Hahn6b1db822018-06-14 20:32:58 +00004537 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4538 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4539 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4540 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4541 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4542 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004543
4544 // Combine those into the result: x op (x op x)
Florian Hahn6b1db822018-06-14 20:32:58 +00004545 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4546 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4547 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4548 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4549 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4550 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004551 return;
4552 }
4553 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004554
Chris Lattner8cab0212008-01-05 22:25:12 +00004555 // Compute permutations of all children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004556 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004557 ChildVariants.resize(N->getNumChildren());
4558 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn75e87c32018-05-30 21:00:18 +00004559 GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004560
4561 // Build all permutations based on how the children were formed.
Florian Hahn6b1db822018-06-14 20:32:58 +00004562 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004563
4564 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004565 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4566 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004567 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004568 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004569 // Don't count children which are actually register references.
4570 unsigned NC = 0;
4571 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004572 TreePatternNode *Child = N->getChild(i);
4573 if (Child->isLeaf())
4574 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004575 Record *RR = DI->getDef();
4576 if (RR->isSubClassOf("Register"))
4577 continue;
4578 }
4579 NC++;
4580 }
4581 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004582 if (isCommIntrinsic) {
4583 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4584 // operands are the commutative operands, and there might be more operands
4585 // after those.
4586 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004587 "Commutative intrinsic should have at least 3 children!");
Florian Hahn75e87c32018-05-30 21:00:18 +00004588 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004589 Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4590 Variants.push_back(std::move(ChildVariants[2]));
4591 Variants.push_back(std::move(ChildVariants[1]));
Evan Cheng49bad4c2008-06-16 20:29:38 +00004592 for (unsigned i = 3; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004593 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004594 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004595 } else if (NC == N->getNumChildren()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004596 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004597 Variants.push_back(std::move(ChildVariants[1]));
4598 Variants.push_back(std::move(ChildVariants[0]));
Craig Topper98a96282017-09-04 03:44:33 +00004599 for (unsigned i = 2; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004600 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004601 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004602 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004603 }
4604}
4605
4606
4607// GenerateVariants - Generate variants. For example, commutative patterns can
4608// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004609void CodeGenDAGPatterns::GenerateVariants() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004610 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004611
Chris Lattner8cab0212008-01-05 22:25:12 +00004612 // Loop over all of the patterns we've collected, checking to see if we can
4613 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004614 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004615 // the .td file having to contain tons of variants of instructions.
4616 //
4617 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4618 // intentionally do not reconsider these. Any variants of added patterns have
4619 // already been added.
4620 //
Simon Pilgrim0621f562018-09-18 11:30:30 +00004621 const unsigned NumOriginalPatterns = PatternsToMatch.size();
4622 BitVector MatchedPatterns(NumOriginalPatterns);
4623 std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
4624 BitVector(NumOriginalPatterns));
4625
4626 typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
4627 DepsAndVariants;
4628 std::map<unsigned, DepsAndVariants> PatternsWithVariants;
4629
4630 // Collect patterns with more than one variant.
4631 for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
4632 MultipleUseVarSet DepVars;
Florian Hahn75e87c32018-05-30 21:00:18 +00004633 std::vector<TreePatternNodePtr> Variants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004634 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004635 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4636 LLVM_DEBUG(DumpDepVars(DepVars));
4637 LLVM_DEBUG(errs() << "\n");
Florian Hahn75e87c32018-05-30 21:00:18 +00004638 GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4639 *this, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004640
4641 assert(!Variants.empty() && "Must create at least original variant!");
Simon Pilgrim0621f562018-09-18 11:30:30 +00004642 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004643 continue;
4644
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004645 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4646 PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004647
Simon Pilgrim0621f562018-09-18 11:30:30 +00004648 PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
4649
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004650 // Cache matching predicates.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004651 if (MatchedPatterns[i])
4652 continue;
4653
4654 const std::vector<Predicate> &Predicates =
4655 PatternsToMatch[i].getPredicates();
4656
4657 BitVector &Matches = MatchedPredicates[i];
Simon Pilgrim6d706772018-09-19 12:23:50 +00004658 MatchedPatterns.set(i);
4659 Matches.set(i);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004660
4661 // Don't test patterns that have already been cached - it won't match.
4662 for (unsigned p = 0; p != NumOriginalPatterns; ++p)
4663 if (!MatchedPatterns[p])
4664 Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
4665
4666 // Copy this to all the matching patterns.
4667 for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
Simon Pilgrime3c6f8d2018-09-18 12:01:25 +00004668 if (p != (int)i) {
Simon Pilgrim6d706772018-09-19 12:23:50 +00004669 MatchedPatterns.set(p);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004670 MatchedPredicates[p] = Matches;
4671 }
4672 }
4673
4674 for (auto it : PatternsWithVariants) {
4675 unsigned i = it.first;
4676 const MultipleUseVarSet &DepVars = it.second.first;
4677 const std::vector<TreePatternNodePtr> &Variants = it.second.second;
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004678
Chris Lattner8cab0212008-01-05 22:25:12 +00004679 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004680 TreePatternNodePtr Variant = Variants[v];
Simon Pilgrim0621f562018-09-18 11:30:30 +00004681 BitVector &Matches = MatchedPredicates[i];
Chris Lattner8cab0212008-01-05 22:25:12 +00004682
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004683 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4684 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004685
Chris Lattner8cab0212008-01-05 22:25:12 +00004686 // Scan to see if an instruction or explicit pattern already matches this.
4687 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004688 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004689 // Skip if the top level predicates do not match.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004690 if (!Matches[p])
Evan Cheng34c8c742009-06-26 05:59:16 +00004691 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004692 // Check to see if this variant already exists.
Florian Hahn6b1db822018-06-14 20:32:58 +00004693 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004694 DepVars)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004695 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004696 AlreadyExists = true;
4697 break;
4698 }
4699 }
4700 // If we already have it, ignore the variant.
4701 if (AlreadyExists) continue;
4702
4703 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004704 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004705 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
Florian Hahn75e87c32018-05-30 21:00:18 +00004706 Variant, PatternsToMatch[i].getDstPatternShared(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004707 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004708 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Simon Pilgrim0621f562018-09-18 11:30:30 +00004709 MatchedPredicates.push_back(Matches);
4710
Simon Pilgrimb2444352018-09-18 14:05:07 +00004711 // Add a new match the same as this pattern.
Simon Pilgrimb2444352018-09-18 14:05:07 +00004712 for (auto &P : MatchedPredicates)
Simon Pilgrim429df292018-09-19 11:18:49 +00004713 P.push_back(P[i]);
Chris Lattner8cab0212008-01-05 22:25:12 +00004714 }
4715
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004716 LLVM_DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004717 }
4718}